Spaces:
Runtime error
Runtime error
update code
Browse files- .gitignore +0 -220
- LICENSE +201 -0
- app.py +30 -31
- pipeline_flux_kontext.py → dreamomni2/pipeline_dreamomni2.py +3 -6
- {edit_tests → example_input/edit_tests}/1/ref_0.jpg +0 -0
- {edit_tests → example_input/edit_tests}/1/ref_1.jpg +0 -0
- {edit_tests → example_input/edit_tests}/1/res.jpg +0 -0
- {edit_tests → example_input/edit_tests}/2/ref_0.jpg +0 -0
- {edit_tests → example_input/edit_tests}/2/ref_1.jpg +0 -0
- {edit_tests → example_input/edit_tests}/2/res.jpg +0 -0
- {edit_tests → example_input/edit_tests}/3/ref_0.jpg +0 -0
- {edit_tests → example_input/edit_tests}/3/ref_1.jpg +0 -0
- {edit_tests → example_input/edit_tests}/3/res.jpg +0 -0
- {edit_tests → example_input/edit_tests}/4/ref_0.jpg +0 -0
- {edit_tests → example_input/edit_tests}/4/ref_1.jpg +0 -0
- {edit_tests → example_input/edit_tests}/4/res.jpg +0 -0
- {edit_tests → example_input/edit_tests}/5/ref_0.jpg +0 -0
- {edit_tests → example_input/edit_tests}/5/ref_1.jpg +0 -0
- {edit_tests → example_input/edit_tests}/5/res.jpg +0 -0
- {edit_tests → example_input/edit_tests}/6/ref_0.jpg +0 -0
- {edit_tests → example_input/edit_tests}/6/ref_1.jpg +0 -0
- {edit_tests → example_input/edit_tests}/6/res.jpg +0 -0
- {edit_tests → example_input/edit_tests}/7/ref_0.jpg +0 -0
- {edit_tests → example_input/edit_tests}/7/ref_1.jpg +0 -0
- {edit_tests → example_input/edit_tests}/7/res.jpg +0 -0
- {edit_tests → example_input/edit_tests}/8/ref_0.jpg +0 -0
- {edit_tests → example_input/edit_tests}/8/ref_1.jpg +0 -0
- {edit_tests → example_input/edit_tests}/8/res.jpg +0 -0
- {edit_tests → example_input/edit_tests}/edi_res.png +2 -2
- {edit_tests → example_input/edit_tests}/ref.jpg +0 -0
- {edit_tests → example_input/edit_tests}/src.jpg +0 -0
- {gen_tests → example_input/gen_tests}/gen_res.png +2 -2
- {gen_tests → example_input/gen_tests}/img1.jpg +0 -0
- {gen_tests → example_input/gen_tests}/img2.jpg +0 -0
- imgs/gallery.png +3 -0
- inference_edit.py +180 -0
- inference_gen.py +192 -0
- my_datasets/.gitkeep +327 -0
- script.sh +0 -12
- 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 +21 -21
- web_generate.py +13 -13
.gitignore
DELETED
|
@@ -1,220 +0,0 @@
|
|
| 1 |
-
# Byte-compiled / optimized / DLL files
|
| 2 |
-
__pycache__/
|
| 3 |
-
*.py[codz]
|
| 4 |
-
*$py.class
|
| 5 |
-
|
| 6 |
-
# C extensions
|
| 7 |
-
*.so
|
| 8 |
-
|
| 9 |
-
# Distribution / packaging
|
| 10 |
-
.Python
|
| 11 |
-
build/
|
| 12 |
-
develop-eggs/
|
| 13 |
-
dist/
|
| 14 |
-
downloads/
|
| 15 |
-
eggs/
|
| 16 |
-
.eggs/
|
| 17 |
-
lib/
|
| 18 |
-
lib64/
|
| 19 |
-
parts/
|
| 20 |
-
sdist/
|
| 21 |
-
var/
|
| 22 |
-
wheels/
|
| 23 |
-
share/python-wheels/
|
| 24 |
-
*.egg-info/
|
| 25 |
-
.installed.cfg
|
| 26 |
-
*.egg
|
| 27 |
-
MANIFEST
|
| 28 |
-
|
| 29 |
-
# PyInstaller
|
| 30 |
-
# Usually these files are written by a python script from a template
|
| 31 |
-
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
| 32 |
-
*.manifest
|
| 33 |
-
*.spec
|
| 34 |
-
|
| 35 |
-
# Installer logs
|
| 36 |
-
pip-log.txt
|
| 37 |
-
pip-delete-this-directory.txt
|
| 38 |
-
|
| 39 |
-
# Unit test / coverage reports
|
| 40 |
-
htmlcov/
|
| 41 |
-
.tox/
|
| 42 |
-
.nox/
|
| 43 |
-
.coverage
|
| 44 |
-
.coverage.*
|
| 45 |
-
.cache
|
| 46 |
-
nosetests.xml
|
| 47 |
-
coverage.xml
|
| 48 |
-
*.cover
|
| 49 |
-
*.py.cover
|
| 50 |
-
.hypothesis/
|
| 51 |
-
.pytest_cache/
|
| 52 |
-
cover/
|
| 53 |
-
|
| 54 |
-
# Translations
|
| 55 |
-
*.mo
|
| 56 |
-
*.pot
|
| 57 |
-
|
| 58 |
-
# Django stuff:
|
| 59 |
-
*.log
|
| 60 |
-
local_settings.py
|
| 61 |
-
db.sqlite3
|
| 62 |
-
db.sqlite3-journal
|
| 63 |
-
|
| 64 |
-
# Flask stuff:
|
| 65 |
-
instance/
|
| 66 |
-
.webassets-cache
|
| 67 |
-
|
| 68 |
-
# Scrapy stuff:
|
| 69 |
-
.scrapy
|
| 70 |
-
|
| 71 |
-
# Sphinx documentation
|
| 72 |
-
docs/_build/
|
| 73 |
-
|
| 74 |
-
# PyBuilder
|
| 75 |
-
.pybuilder/
|
| 76 |
-
target/
|
| 77 |
-
|
| 78 |
-
# Jupyter Notebook
|
| 79 |
-
.ipynb_checkpoints
|
| 80 |
-
|
| 81 |
-
# IPython
|
| 82 |
-
profile_default/
|
| 83 |
-
ipython_config.py
|
| 84 |
-
|
| 85 |
-
# pyenv
|
| 86 |
-
# For a library or package, you might want to ignore these files since the code is
|
| 87 |
-
# intended to run in multiple environments; otherwise, check them in:
|
| 88 |
-
# .python-version
|
| 89 |
-
|
| 90 |
-
# pipenv
|
| 91 |
-
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
| 92 |
-
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
| 93 |
-
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
| 94 |
-
# install all needed dependencies.
|
| 95 |
-
# Pipfile.lock
|
| 96 |
-
|
| 97 |
-
# UV
|
| 98 |
-
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
| 99 |
-
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
| 100 |
-
# commonly ignored for libraries.
|
| 101 |
-
# uv.lock
|
| 102 |
-
|
| 103 |
-
# poetry
|
| 104 |
-
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
| 105 |
-
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
| 106 |
-
# commonly ignored for libraries.
|
| 107 |
-
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
| 108 |
-
# poetry.lock
|
| 109 |
-
# poetry.toml
|
| 110 |
-
|
| 111 |
-
# pdm
|
| 112 |
-
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
| 113 |
-
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
| 114 |
-
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
| 115 |
-
# pdm.lock
|
| 116 |
-
# pdm.toml
|
| 117 |
-
.pdm-python
|
| 118 |
-
.pdm-build/
|
| 119 |
-
|
| 120 |
-
# pixi
|
| 121 |
-
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
| 122 |
-
# pixi.lock
|
| 123 |
-
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
| 124 |
-
# in the .venv directory. It is recommended not to include this directory in version control.
|
| 125 |
-
.pixi
|
| 126 |
-
|
| 127 |
-
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
| 128 |
-
__pypackages__/
|
| 129 |
-
|
| 130 |
-
# Celery stuff
|
| 131 |
-
celerybeat-schedule
|
| 132 |
-
celerybeat.pid
|
| 133 |
-
|
| 134 |
-
# Redis
|
| 135 |
-
*.rdb
|
| 136 |
-
*.aof
|
| 137 |
-
*.pid
|
| 138 |
-
|
| 139 |
-
# RabbitMQ
|
| 140 |
-
mnesia/
|
| 141 |
-
rabbitmq/
|
| 142 |
-
rabbitmq-data/
|
| 143 |
-
|
| 144 |
-
# ActiveMQ
|
| 145 |
-
activemq-data/
|
| 146 |
-
|
| 147 |
-
# SageMath parsed files
|
| 148 |
-
*.sage.py
|
| 149 |
-
|
| 150 |
-
# Environments
|
| 151 |
-
.env
|
| 152 |
-
.envrc
|
| 153 |
-
.venv
|
| 154 |
-
env/
|
| 155 |
-
venv/
|
| 156 |
-
ENV/
|
| 157 |
-
env.bak/
|
| 158 |
-
venv.bak/
|
| 159 |
-
|
| 160 |
-
# Spyder project settings
|
| 161 |
-
.spyderproject
|
| 162 |
-
.spyproject
|
| 163 |
-
|
| 164 |
-
# Rope project settings
|
| 165 |
-
.ropeproject
|
| 166 |
-
|
| 167 |
-
# mkdocs documentation
|
| 168 |
-
/site
|
| 169 |
-
|
| 170 |
-
# mypy
|
| 171 |
-
.mypy_cache/
|
| 172 |
-
.dmypy.json
|
| 173 |
-
dmypy.json
|
| 174 |
-
|
| 175 |
-
# Pyre type checker
|
| 176 |
-
.pyre/
|
| 177 |
-
|
| 178 |
-
# pytype static type analyzer
|
| 179 |
-
.pytype/
|
| 180 |
-
|
| 181 |
-
# Cython debug symbols
|
| 182 |
-
cython_debug/
|
| 183 |
-
|
| 184 |
-
# PyCharm
|
| 185 |
-
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
| 186 |
-
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
| 187 |
-
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
| 188 |
-
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
| 189 |
-
# .idea/
|
| 190 |
-
|
| 191 |
-
# Abstra
|
| 192 |
-
# Abstra is an AI-powered process automation framework.
|
| 193 |
-
# Ignore directories containing user credentials, local state, and settings.
|
| 194 |
-
# Learn more at https://abstra.io/docs
|
| 195 |
-
.abstra/
|
| 196 |
-
|
| 197 |
-
# Visual Studio Code
|
| 198 |
-
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
| 199 |
-
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
| 200 |
-
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
| 201 |
-
# you could uncomment the following to ignore the entire vscode folder
|
| 202 |
-
# .vscode/
|
| 203 |
-
|
| 204 |
-
# Ruff stuff:
|
| 205 |
-
.ruff_cache/
|
| 206 |
-
|
| 207 |
-
# PyPI configuration file
|
| 208 |
-
.pypirc
|
| 209 |
-
|
| 210 |
-
# Marimo
|
| 211 |
-
marimo/_static/
|
| 212 |
-
marimo/_lsp/
|
| 213 |
-
__marimo__/
|
| 214 |
-
|
| 215 |
-
# Streamlit
|
| 216 |
-
.streamlit/secrets.toml
|
| 217 |
-
|
| 218 |
-
tmp_script.sh
|
| 219 |
-
.gradio/
|
| 220 |
-
gradio_tmp
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
| 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.
|
app.py
CHANGED
|
@@ -8,12 +8,16 @@ import argparse
|
|
| 8 |
from huggingface_hub import login, snapshot_download
|
| 9 |
|
| 10 |
import torch
|
| 11 |
-
from
|
| 12 |
from diffusers.utils import load_image
|
| 13 |
from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
|
| 14 |
-
from
|
| 15 |
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
def _load_model_processor():
|
| 18 |
|
| 19 |
local_dir = snapshot_download(
|
|
@@ -21,22 +25,22 @@ def _load_model_processor():
|
|
| 21 |
revision="main",
|
| 22 |
allow_patterns=["vlm-model/**", "edit_lora/**"],
|
| 23 |
)
|
| 24 |
-
|
| 25 |
-
|
| 26 |
|
| 27 |
-
print(f"Loading models from vlm_path: {
|
| 28 |
-
pipe =
|
| 29 |
"black-forest-labs/FLUX.1-Kontext-dev",
|
| 30 |
torch_dtype=torch.bfloat16
|
| 31 |
)
|
| 32 |
-
pipe.load_lora_weights(
|
| 33 |
pipe.set_adapters(["edit"], adapter_weights=[1])
|
| 34 |
|
| 35 |
vlm_model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
| 36 |
-
|
| 37 |
torch_dtype="bfloat16"
|
| 38 |
)
|
| 39 |
-
processor = AutoProcessor.from_pretrained(
|
| 40 |
return vlm_model, processor, pipe
|
| 41 |
|
| 42 |
|
|
@@ -88,28 +92,23 @@ def _launch_demo(vlm_model, processor, pipe):
|
|
| 88 |
key=lambda res: abs((res[0] / res[1]) - input_ratio)
|
| 89 |
)
|
| 90 |
return closest_resolution
|
| 91 |
-
|
| 92 |
-
def extract_gen_content(text):
|
| 93 |
-
text = text[6:-7]
|
| 94 |
-
return text
|
| 95 |
|
| 96 |
@spaces.GPU()
|
| 97 |
def perform_edit(input_img_paths, input_instruction, output_path):
|
| 98 |
prefix = " It is editing task."
|
| 99 |
-
source_imgs = [
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
resized_imgs.append(resized_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=
|
| 111 |
-
height=
|
| 112 |
-
width=
|
| 113 |
prompt=prompt,
|
| 114 |
num_inference_steps=30,
|
| 115 |
guidance_scale=3.5,
|
|
@@ -205,15 +204,15 @@ def _launch_demo(vlm_model, processor, pipe):
|
|
| 205 |
gr.Examples(
|
| 206 |
label="Editing Examples",
|
| 207 |
examples=[
|
| 208 |
-
["edit_tests/4/ref_0.jpg", "edit_tests/4/ref_1.jpg", "Replace the first image have the same image style as the second image.","edit_tests/4/res.jpg"],
|
| 209 |
-
["edit_tests/5/ref_0.jpg", "edit_tests/5/ref_1.jpg", "Make the person in the first image have the same hairstyle as the person in the second image.","edit_tests/5/res.jpg"],
|
| 210 |
-
["edit_tests/src.jpg", "edit_tests/ref.jpg", "Make the woman from the second image stand on the road in the first image.","edit_tests/edi_res.png"],
|
| 211 |
-
["edit_tests/1/ref_0.jpg", "edit_tests/1/ref_1.jpg", "Replace the lantern in the first image with the dog in the second image.","edit_tests/1/res.jpg"],
|
| 212 |
-
["edit_tests/2/ref_0.jpg", "edit_tests/2/ref_1.jpg", "Replace the suit in the first image with the clothes in the second image.","edit_tests/2/res.jpg"],
|
| 213 |
-
["edit_tests/3/ref_0.jpg", "edit_tests/3/ref_1.jpg", "Make the first image has the same light condition as the second image.","edit_tests/3/res.jpg"],
|
| 214 |
-
["edit_tests/6/ref_0.jpg", "edit_tests/6/ref_1.jpg", "Make the words in the first image have the same font as the words in the second image.","edit_tests/6/res.jpg"],
|
| 215 |
-
["edit_tests/7/ref_0.jpg", "edit_tests/7/ref_1.jpg", "Make the car in the first image have the same pattern as the mouse in the second image.","edit_tests/7/res.jpg"],
|
| 216 |
-
["edit_tests/8/ref_0.jpg", "edit_tests/8/ref_1.jpg", "Make the dress in the first image have the same pattern in the second image.","edit_tests/8/res.jpg"],
|
| 217 |
],
|
| 218 |
inputs=[image_uploader_1, image_uploader_2, instruction_text, output_image],
|
| 219 |
cache_examples=False,
|
|
|
|
| 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 |
local_dir = snapshot_download(
|
|
|
|
| 25 |
revision="main",
|
| 26 |
allow_patterns=["vlm-model/**", "edit_lora/**"],
|
| 27 |
)
|
| 28 |
+
vlm_dir = os.path.join(local_dir, 'vlm-model')
|
| 29 |
+
lora_dir = os.path.join(local_dir, 'edit_lora')
|
| 30 |
|
| 31 |
+
print(f"Loading models from vlm_path: {vlm_dir}, edit_lora_path: {lora_dir}")
|
| 32 |
+
pipe = DreamOmni2Pipeline.from_pretrained(
|
| 33 |
"black-forest-labs/FLUX.1-Kontext-dev",
|
| 34 |
torch_dtype=torch.bfloat16
|
| 35 |
)
|
| 36 |
+
pipe.load_lora_weights(lora_dir, adapter_name="edit")
|
| 37 |
pipe.set_adapters(["edit"], adapter_weights=[1])
|
| 38 |
|
| 39 |
vlm_model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
| 40 |
+
vlm_dir,
|
| 41 |
torch_dtype="bfloat16"
|
| 42 |
)
|
| 43 |
+
processor = AutoProcessor.from_pretrained(vlm_dir)
|
| 44 |
return vlm_model, processor, pipe
|
| 45 |
|
| 46 |
|
|
|
|
| 92 |
key=lambda res: abs((res[0] / res[1]) - input_ratio)
|
| 93 |
)
|
| 94 |
return closest_resolution
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
@spaces.GPU()
|
| 97 |
def perform_edit(input_img_paths, input_instruction, output_path):
|
| 98 |
prefix = " It is editing task."
|
| 99 |
+
source_imgs = []
|
| 100 |
+
for path in input_img_paths:
|
| 101 |
+
img = load_image(path)
|
| 102 |
+
# source_imgs.append(img)
|
| 103 |
+
source_imgs.append(resizeinput(img))
|
|
|
|
| 104 |
prompt = infer_vlm(input_img_paths, input_instruction, prefix)
|
| 105 |
prompt = extract_gen_content(prompt)
|
| 106 |
print(f"Generated Prompt for VLM: {prompt}")
|
| 107 |
|
| 108 |
image = pipe(
|
| 109 |
+
images=source_imgs,
|
| 110 |
+
height=source_imgs[0].height,
|
| 111 |
+
width=source_imgs[0].width,
|
| 112 |
prompt=prompt,
|
| 113 |
num_inference_steps=30,
|
| 114 |
guidance_scale=3.5,
|
|
|
|
| 204 |
gr.Examples(
|
| 205 |
label="Editing Examples",
|
| 206 |
examples=[
|
| 207 |
+
["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"],
|
| 208 |
+
["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"],
|
| 209 |
+
["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"],
|
| 210 |
+
["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"],
|
| 211 |
+
["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"],
|
| 212 |
+
["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"],
|
| 213 |
+
["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"],
|
| 214 |
+
["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"],
|
| 215 |
+
["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"],
|
| 216 |
],
|
| 217 |
inputs=[image_uploader_1, image_uploader_2, instruction_text, output_image],
|
| 218 |
cache_examples=False,
|
pipeline_flux_kontext.py → dreamomni2/pipeline_dreamomni2.py
RENAMED
|
@@ -57,10 +57,10 @@ EXAMPLE_DOC_STRING = """
|
|
| 57 |
Examples:
|
| 58 |
```py
|
| 59 |
>>> import torch
|
| 60 |
-
>>> from diffusers import
|
| 61 |
>>> from diffusers.utils import load_image
|
| 62 |
|
| 63 |
-
>>> pipe =
|
| 64 |
... "black-forest-labs/FLUX.1-Kontext-dev", torch_dtype=torch.bfloat16
|
| 65 |
... )
|
| 66 |
>>> pipe.to("cuda")
|
|
@@ -187,7 +187,7 @@ def retrieve_latents(
|
|
| 187 |
raise AttributeError("Could not access latents of provided encoder_output")
|
| 188 |
|
| 189 |
|
| 190 |
-
class
|
| 191 |
DiffusionPipeline,
|
| 192 |
FluxLoraLoaderMixin,
|
| 193 |
FromSingleFileMixin,
|
|
@@ -694,10 +694,7 @@ class FluxKontextPipeline(
|
|
| 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 are the same as latent ids with the first dimension set to 1 instead of 0
|
| 698 |
-
# image_ids[..., 0] = 0.9+i*0.1
|
| 699 |
image_ids[..., 0] = i+1
|
| 700 |
-
# image_ids[..., 1] += h_offset
|
| 701 |
image_ids[..., 2] += w_offset
|
| 702 |
tp_image_latents.append(image_latents)
|
| 703 |
tp_image_ids.append(image_ids)
|
|
|
|
| 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")
|
|
|
|
| 187 |
raise AttributeError("Could not access latents of provided encoder_output")
|
| 188 |
|
| 189 |
|
| 190 |
+
class DreamOmni2Pipeline(
|
| 191 |
DiffusionPipeline,
|
| 192 |
FluxLoraLoaderMixin,
|
| 193 |
FromSingleFileMixin,
|
|
|
|
| 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)
|
{edit_tests → example_input/edit_tests}/1/ref_0.jpg
RENAMED
|
File without changes
|
{edit_tests → example_input/edit_tests}/1/ref_1.jpg
RENAMED
|
File without changes
|
{edit_tests → example_input/edit_tests}/1/res.jpg
RENAMED
|
File without changes
|
{edit_tests → example_input/edit_tests}/2/ref_0.jpg
RENAMED
|
File without changes
|
{edit_tests → example_input/edit_tests}/2/ref_1.jpg
RENAMED
|
File without changes
|
{edit_tests → example_input/edit_tests}/2/res.jpg
RENAMED
|
File without changes
|
{edit_tests → example_input/edit_tests}/3/ref_0.jpg
RENAMED
|
File without changes
|
{edit_tests → example_input/edit_tests}/3/ref_1.jpg
RENAMED
|
File without changes
|
{edit_tests → example_input/edit_tests}/3/res.jpg
RENAMED
|
File without changes
|
{edit_tests → example_input/edit_tests}/4/ref_0.jpg
RENAMED
|
File without changes
|
{edit_tests → example_input/edit_tests}/4/ref_1.jpg
RENAMED
|
File without changes
|
{edit_tests → example_input/edit_tests}/4/res.jpg
RENAMED
|
File without changes
|
{edit_tests → example_input/edit_tests}/5/ref_0.jpg
RENAMED
|
File without changes
|
{edit_tests → example_input/edit_tests}/5/ref_1.jpg
RENAMED
|
File without changes
|
{edit_tests → example_input/edit_tests}/5/res.jpg
RENAMED
|
File without changes
|
{edit_tests → example_input/edit_tests}/6/ref_0.jpg
RENAMED
|
File without changes
|
{edit_tests → example_input/edit_tests}/6/ref_1.jpg
RENAMED
|
File without changes
|
{edit_tests → example_input/edit_tests}/6/res.jpg
RENAMED
|
File without changes
|
{edit_tests → example_input/edit_tests}/7/ref_0.jpg
RENAMED
|
File without changes
|
{edit_tests → example_input/edit_tests}/7/ref_1.jpg
RENAMED
|
File without changes
|
{edit_tests → example_input/edit_tests}/7/res.jpg
RENAMED
|
File without changes
|
{edit_tests → example_input/edit_tests}/8/ref_0.jpg
RENAMED
|
File without changes
|
{edit_tests → example_input/edit_tests}/8/ref_1.jpg
RENAMED
|
File without changes
|
{edit_tests → example_input/edit_tests}/8/res.jpg
RENAMED
|
File without changes
|
{edit_tests → example_input/edit_tests}/edi_res.png
RENAMED
|
File without changes
|
{edit_tests → example_input/edit_tests}/ref.jpg
RENAMED
|
File without changes
|
{edit_tests → example_input/edit_tests}/src.jpg
RENAMED
|
File without changes
|
{gen_tests → example_input/gen_tests}/gen_res.png
RENAMED
|
File without changes
|
{gen_tests → example_input/gen_tests}/img1.jpg
RENAMED
|
File without changes
|
{gen_tests → example_input/gen_tests}/img2.jpg
RENAMED
|
File without changes
|
imgs/gallery.png
ADDED
|
Git LFS Details
|
in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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_path
|
| 180 |
+
image.save(output_path)
|
inference_gen.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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)
|
script.sh
DELETED
|
@@ -1,12 +0,0 @@
|
|
| 1 |
-
CUDA_VISIBLE_DEVICES=3 GRADIO_TEMP_DIR=gradio_tmp python web_edit.py \
|
| 2 |
-
--vlm_path /gpfs/bhpeng/generation/do2/vlm-model \
|
| 3 |
-
--edit_lora_path /gpfs/bhpeng/generation/do2/edit_lora \
|
| 4 |
-
--server_name "0.0.0.0" \
|
| 5 |
-
--server_port 7869
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
CUDA_VISIBLE_DEVICES=1 python web_generate.py \
|
| 9 |
-
--vlm_path /gpfs/bhpeng/generation/do2/vlm-model \
|
| 10 |
-
--gen_lora_path /gpfs/bhpeng/generation/do2/gen_lora \
|
| 11 |
-
--server_name "0.0.0.0" \
|
| 12 |
-
--server_port 7861
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
utils/fsdp_utils.py
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
|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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_kwargs:
|
| 567 |
+
return image_inputs, video_inputs, video_kwargs
|
| 568 |
+
return image_inputs, video_inputs
|
web_edit.py
CHANGED
|
@@ -1,8 +1,9 @@
|
|
| 1 |
import torch
|
| 2 |
-
from
|
| 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 |
import os
|
| 7 |
import re
|
| 8 |
from PIL import Image
|
|
@@ -53,7 +54,7 @@ def extract_gen_content(text):
|
|
| 53 |
|
| 54 |
print(f"Loading models from vlm_path: {vlm_path}, edit_lora_path: {edit_lora_path}")
|
| 55 |
|
| 56 |
-
pipe =
|
| 57 |
"black-forest-labs/FLUX.1-Kontext-dev",
|
| 58 |
torch_dtype=torch.bfloat16
|
| 59 |
)
|
|
@@ -117,20 +118,19 @@ def find_closest_resolution(width, height, preferred_resolutions):
|
|
| 117 |
|
| 118 |
def perform_edit(input_img_paths, input_instruction, output_path):
|
| 119 |
prefix = " It is editing task."
|
| 120 |
-
source_imgs = [
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
resized_imgs.append(resized_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=
|
| 132 |
-
height=
|
| 133 |
-
width=
|
| 134 |
prompt=prompt,
|
| 135 |
num_inference_steps=30,
|
| 136 |
guidance_scale=3.5,
|
|
@@ -227,15 +227,15 @@ with gr.Blocks(theme=gr.themes.Soft(), title="DreamOmni2", css=css) as demo:
|
|
| 227 |
gr.Examples(
|
| 228 |
label="Editing Examples",
|
| 229 |
examples=[
|
| 230 |
-
["edit_tests/4/ref_0.jpg", "edit_tests/4/ref_1.jpg", "Replace the first image have the same image style as the second image.","edit_tests/4/res.jpg"],
|
| 231 |
-
["edit_tests/5/ref_0.jpg", "edit_tests/5/ref_1.jpg", "Make the person in the first image have the same hairstyle as the person in the second image.","edit_tests/5/res.jpg"],
|
| 232 |
-
["edit_tests/src.jpg", "edit_tests/ref.jpg", "Make the woman from the second image stand on the road in the first image.","edit_tests/edi_res.png"],
|
| 233 |
-
["edit_tests/1/ref_0.jpg", "edit_tests/1/ref_1.jpg", "Replace the lantern in the first image with the dog in the second image.","edit_tests/1/res.jpg"],
|
| 234 |
-
["edit_tests/2/ref_0.jpg", "edit_tests/2/ref_1.jpg", "Replace the suit in the first image with the clothes in the second image.","edit_tests/2/res.jpg"],
|
| 235 |
-
["edit_tests/3/ref_0.jpg", "edit_tests/3/ref_1.jpg", "Make the first image has the same light condition as the second image.","edit_tests/3/res.jpg"],
|
| 236 |
-
["edit_tests/6/ref_0.jpg", "edit_tests/6/ref_1.jpg", "Make the words in the first image have the same font as the words in the second image.","edit_tests/6/res.jpg"],
|
| 237 |
-
["edit_tests/7/ref_0.jpg", "edit_tests/7/ref_1.jpg", "Make the car in the first image have the same pattern as the mouse in the second image.","edit_tests/7/res.jpg"],
|
| 238 |
-
["edit_tests/8/ref_0.jpg", "edit_tests/8/ref_1.jpg", "Make the dress in the first image have the same pattern in the second image.","edit_tests/8/res.jpg"],
|
| 239 |
],
|
| 240 |
inputs=[image_uploader_1, image_uploader_2, instruction_text, output_image],
|
| 241 |
cache_examples=False,
|
|
|
|
| 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
|
|
|
|
| 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 |
)
|
|
|
|
| 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,
|
|
|
|
| 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,
|
web_generate.py
CHANGED
|
@@ -1,8 +1,9 @@
|
|
| 1 |
import torch
|
| 2 |
-
from
|
| 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 |
import os
|
| 7 |
import re
|
| 8 |
from PIL import Image
|
|
@@ -53,7 +54,7 @@ def extract_gen_content(text):
|
|
| 53 |
|
| 54 |
print(f"Loading models from vlm_path: {vlm_path}, gen_lora_path: {gen_lora_path}")
|
| 55 |
|
| 56 |
-
pipe =
|
| 57 |
"black-forest-labs/FLUX.1-Kontext-dev",
|
| 58 |
torch_dtype=torch.bfloat16
|
| 59 |
)
|
|
@@ -118,18 +119,17 @@ def find_closest_resolution(width, height, preferred_resolutions):
|
|
| 118 |
|
| 119 |
def perform_generation(input_img_paths, input_instruction, output_path, height=1024, width=1024):
|
| 120 |
prefix = " It is generation task."
|
| 121 |
-
source_imgs = [
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
resized_imgs.append(resized_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=
|
| 133 |
height=height,
|
| 134 |
width=width,
|
| 135 |
prompt=prompt,
|
|
@@ -229,10 +229,10 @@ with gr.Blocks(theme=gr.themes.Soft(), title="DreamOmni2", css=css) as demo:
|
|
| 229 |
label="Generation Examples",
|
| 230 |
examples=[
|
| 231 |
[
|
| 232 |
-
"gen_tests/img1.jpg",
|
| 233 |
-
"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 |
-
"gen_tests/gen_res.png"
|
| 236 |
]
|
| 237 |
],
|
| 238 |
inputs=[image_uploader_1, image_uploader_2, instruction_text, output_image],
|
|
|
|
| 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
|
|
|
|
| 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 |
)
|
|
|
|
| 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,
|
|
|
|
| 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],
|