Commit f91d2ea3 authored by mashun1's avatar mashun1
Browse files

hunyuandit

parents
blank_issues_enabled: false
---
name: Error report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
Thanks for your error report and we appreciate it a lot.
**Checklist**
1. I have searched related issues but cannot get the expected help.
2. The bug has not been fixed in the latest version.
**Describe the bug**
A clear and concise description of what the bug is.
**Reproduction**
1. What command or script did you run?
```none
A placeholder for the command.
```
2. Did you make any modifications on the code or config? Did you understand what you have modified?
3. What dataset did you use?
**Environment**
1. Please run `python utils/collect_env.py` to collect necessary environment information and paste it here.
2. You may add addition that may be helpful for locating the problem, such as
- How you installed PyTorch \[e.g., pip, conda, source\]
- Other environment variables that may be related (such as `$PATH`, `$LD_LIBRARY_PATH`, `$PYTHONPATH`, etc.)
**Error traceback**
If applicable, paste the error trackback here.
```none
A placeholder for trackback.
```
**Bug fix**
If you have already identified the reason, you can provide the information here. If you are willing to create a PR to fix it, please also leave a comment here and that would be much appreciated!
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Describe the feature**
**Motivation**
A clear and concise description of the motivation of the feature.
Ex1. It is inconvenient when \[....\].
Ex2. There is a recent paper \[....\], which is very helpful for \[....\].
**Related resources**
If there is an official code release or third-party implementations, please also provide the information here, which would be very helpful.
**Additional context**
Add any other context or screenshots about the feature request here.
If you would like to implement the feature and create a PR, please leave a comment here and that would be much appreciated.
---
name: General questions
about: Ask general questions to get help
title: ''
labels: ''
assignees: ''
---
---
name: Reimplementation Questions
about: Ask about questions during model reimplementation
title: ''
labels: reimplementation
assignees: ''
---
**Notice**
There are several common situations in the reimplementation issues as below
1. Reimplement a model in the model zoo using the provided configs
2. Reimplement a model in the model zoo on other dataset (e.g., custom datasets)
3. Reimplement a custom model but all the components are implemented in HunyuanDiT
4. Reimplement a custom model with new modules implemented by yourself
There are several things to do for different cases as below.
- For case 1 & 3, please follow the steps in the following sections thus we could help to quick identify the issue.
- For case 2 & 4, please understand that we are not able to do much help here because we usually do not know the full code and the users should be responsible to the code they write.
- One suggestion for case 2 & 4 is that the users should first check whether the bug lies in the self-implemented code or the original code. For example, users can first make sure that the same model runs well on supported datasets. If you still need help, please describe what you have done and what you obtain in the issue, and follow the steps in the following sections and try as clear as possible so that we can better help you.
**Checklist**
1. I have searched related issues but cannot get the expected help.
2. The issue has not been fixed in the latest version.
**Describe the issue**
A clear and concise description of what the problem you meet and what have you done.
**Reproduction**
1. What command or script did you run?
```none
A placeholder for the command.
```
2. What config dir you run?
```none
A placeholder for the config.
```
3. Did you make any modifications on the code or config? Did you understand what you have modified?
4. What dataset did you use?
**Environment**
1. Please run `python utils/collect_env.py` to collect necessary environment information and paste it here.
2. You may add addition that may be helpful for locating the problem, such as
1. How you installed PyTorch \[e.g., pip, conda, source\]
2. Other environment variables that may be related (such as `$PATH`, `$LD_LIBRARY_PATH`, `$PYTHONPATH`, etc.)
**Results**
If applicable, paste the related results here, e.g., what you expect and what you get.
```none
A placeholder for results comparison
```
**Issue fix**
If you have already identified the reason, you can provide the information here. If you are willing to create a PR to fix it, please also leave a comment here and that would be much appreciated!
---
name: 一般问题
about: 提出一般性问题以获得帮助
title: ''
labels: ''
assignees: ''
---
---
name: 功能请求
about: 为此项目提出一个想法
title: ''
labels: ''
assignees: ''
---
**描述功能**
**动机**
清晰简洁地描述该功能的动机。
例如1. 当\[....\]时很不方便。
例如2. 最近有一篇论文\[....\],这对\[....\]非常有帮助。
**相关资源**
如果有官方代码发布或第三方实现,也请在此提供信息,这将非常有帮助。
**其他上下文**
在此添加有关功能请求的其他上下文或截图。
如果您希望实现该功能并创建 PR,请在此留言,我们将不胜感激。
---
name: 复现问题
about: 询问模型复现中的问题
title: ''
labels: reimplementation
assignees: ''
---
**注意**
在复现的问题中,通常有以下几种常见情况:
1. 使用提供的配置复现模型库中的模型
2. 在其他数据集(例如自定义数据集)上复现模型库中的模型
3. 实现自定义模型,但利用的都是HunyuanDiT中实现的组件
4. 使用自己实现的新模块实现自定义模型
针对不同情况需要做的事情如下:
- 对于情况 1 和 3,请按照以下部分的步骤操作,以便我们快速识别问题。
- 对于情况 2 和 4,请理解我们无法提供太多帮助,因为我们通常不了解全部代码,用户应对自己编写的代码负责。
- 针对情况 2 和 4 的一个建议是,用户应首先检查错误是否在自实现代码中或原始代码中。例如,用户可以首先确保相同的模型在支持的数据集上运行良好。如果您仍然需要帮助,请描述您所做的工作和遇到的问题,并按照以下部分的步骤尽可能清晰地描述,以便我们更好地帮助您。
**检查清单**
1. 我已搜索相关问题,但无法获得预期的帮助。
2. 最新版本中尚未修复此问题。
**描述问题**
清晰简洁地描述您遇到的问题以及您所做的工作。
**重现步骤**
1. 您运行了什么命令或脚本?
```none
命令的占位符。
```
2. 您运行的配置目录是什么?
```none
配置目录的占位符
```
3. 您是否对代码或配置进行了任何修改?您是否理解您所修改的内容?
4. 您使用了什么数据集?
**环境**
1. 请运行 python utils/collect_env.py 收集必要的环境信息并粘贴在此。
2. 您可以添加其他有助于定位问题的信息,例如
- 您如何安装的 PyTorch \[例如,pip, conda, source\]
- 其他可能相关的环境变量 (例如 `$PATH`, `$LD_LIBRARY_PATH`, `$PYTHONPATH` 等)
**结果**
如果适用,请在此粘贴相关结果,例如,您的预期结果和实际结果。
```none
结果比较的占位符
```
**Bug修复**
如果您已经确定了原因,可以在此提供信息。如果您愿意创建 PR 进行修复,也请在此留言,我们将不胜感激!
\ No newline at end of file
---
name: 错误报告
about: 创建报告以帮助我们改进
title: ''
labels: ''
assignees: ''
---
感谢您的错误报告,我们非常感谢。
**检查清单**
1. 我已搜索相关问题,但无法获得预期的帮助。
2. 最新版本中尚未修复此错误。
**描述错误**
对错误的清晰简洁描述。
**重现步骤**
1. 您运行了什么命令或脚本?
```none
命令的占位符。
```
2. 您是否对代码或配置进行了任何修改?您是否理解您所修改的内容?
3. 您使用了什么数据集?
**环境**
1. 请运行 python utils/collect_env.py 收集必要的环境信息并粘贴在此。
2. 您可以添加其他有助于定位问题的信息,例如
- 您如何安装的 PyTorch \[例如,pip, conda, source\]
- 其他可能相关的环境变量 (例如 `$PATH`, `$LD_LIBRARY_PATH`, `$PYTHONPATH` 等)
**错误回溯**
如可以,请在此粘贴错误回溯信息。
```none
回溯信息的占位符。
```
**Bug修复**
如果您已经确定了原因,可以在此提供信息。如果您愿意创建 PR 进行修复,也请在此留言,我们将不胜感激!
results/
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
.vscode/
.idea/
.DS_Store
results/
trt/activate.sh
trt/deactivate.sh
*.onnx
ckpts/
FROM image.sourcefind.cn:5000/dcu/admin/base/pytorch:2.1.0-centos7.6-dtk24.04-py310
\ No newline at end of file
TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT
Tencent Hunyuan Release Date: 2024/5/14
By clicking to agree or by using, reproducing, modifying, distributing, performing or displaying any portion or element of the Tencent Hunyuan Works, including via any Hosted Service, You will be deemed to have recognized and accepted the content of this Agreement, which is effective immediately.
1. DEFINITIONS.
a. “Acceptable Use Policy” shall mean the policy made available by Tencent as set forth in the Exhibit A.
b. “Agreement” shall mean the terms and conditions for use, reproduction, distribution, modification, performance and displaying of the Hunyuan Works or any portion or element thereof set forth herein.
c. “Documentation” shall mean the specifications, manuals and documentation for Tencent Hunyuan made publicly available by Tencent.
d. “Hosted Service” shall mean a hosted service offered via an application programming interface (API), web access, or any other electronic or remote means.
e. “Licensee,” “You” or “Your” shall mean a natural person or legal entity exercising the rights granted by this Agreement and/or using the Tencent Hunyuan Works for any purpose and in any field of use.
f. “Materials” shall mean, collectively, Tencent’s proprietary Tencent Hunyuan and Documentation (and any portion thereof) as made available by Tencent under this Agreement.
g. “Model Derivatives” shall mean all: (i) modifications to Tencent Hunyuan or any Model Derivative of Tencent Hunyuan; (ii) works based on Tencent Hunyuan or any Model Derivative of Tencent Hunyuan; or (iii) any other machine learning model which is created by transfer of patterns of the weights, parameters, operations, or Output of Tencent Hunyuan or any Model Derivative of Tencent Hunyuan, to that model in order to cause that model to perform similarly to Tencent Hunyuan or a Model Derivative of Tencent Hunyuan, including distillation methods, methods that use intermediate data representations, or methods based on the generation of synthetic data Outputs by Tencent Hunyuan or a Model Derivative of Tencent Hunyuan for training that model. For clarity, Outputs by themselves are not deemed Model Derivatives.
h. “Output” shall mean the information and/or content output of Tencent Hunyuan or a Model Derivative that results from operating or otherwise using Tencent Hunyuan or a Model Derivative, including via a Hosted Service.
i. “Tencent,” “We” or “Us” shall mean THL A29 Limited.
j. “Tencent Hunyuan” shall mean the large language models, image/video/audio/3D generation models, and multimodal large language models and their software and algorithms, including trained model weights, parameters (including optimizer states), machine-learning model code, inference-enabling code, training-enabling code, fine-tuning enabling code and other elements of the foregoing made publicly available by Us at https://huggingface.co/Tencent-Hunyuan/HunyuanDiT and https://github.com/Tencent/HunyuanDiT .
k. “Tencent Hunyuan Works” shall mean: (i) the Materials; (ii) Model Derivatives; and (iii) all derivative works thereof.
l. “Third Party” or “Third Parties” shall mean individuals or legal entities that are not under common control with Us or You.
m. “including” shall mean including but not limited to.
2. GRANT OF RIGHTS.
We grant You a non-exclusive, worldwide, non-transferable and royalty-free limited license under Tencent’s intellectual property or other rights owned by Us embodied in or utilized by the Materials to use, reproduce, distribute, create derivative works of (including Model Derivatives), and make modifications to the Materials, only in accordance with the terms of this Agreement and the Acceptable Use Policy, and You must not violate (or encourage or permit anyone else to violate) any term of this Agreement or the Acceptable Use Policy.
3. DISTRIBUTION.
You may, subject to Your compliance with this Agreement, distribute or make available to Third Parties the Tencent Hunyuan Works, provided that You meet all of the following conditions:
a. You must provide all such Third Party recipients of the Tencent Hunyuan Works or products or services using them a copy of this Agreement;
b. You must cause any modified files to carry prominent notices stating that You changed the files;
c. You are encouraged to: (i) publish at least one technology introduction blogpost or one public statement expressing Your experience of using the Tencent Hunyuan Works; and (ii) mark the products or services developed by using the Tencent Hunyuan Works to indicate that the product/service is “Powered by Tencent Hunyuan”; and
d. All distributions to Third Parties (other than through a Hosted Service) must be accompanied by a “Notice” text file that contains the following notice: “Tencent Hunyuan is licensed under the Tencent Hunyuan Community License Agreement, Copyright © 2024 Tencent. All Rights Reserved. The trademark rights of “Tencent Hunyuan” are owned by Tencent or its affiliate.”
You may add Your own copyright statement to Your modifications and, except as set forth in this Section and in Section 5, may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Model Derivatives as a whole, provided Your use, reproduction, modification, distribution, performance and display of the work otherwise complies with the terms and conditions of this Agreement. If You receive Tencent Hunyuan Works from a Licensee as part of an integrated end user product, then this Section 3 of this Agreement will not apply to You.
4. ADDITIONAL COMMERCIAL TERMS.
If, on the Tencent Hunyuan version release date, the monthly active users of all products or services made available by or for Licensee is greater than 100 million monthly active users in the preceding calendar month, You must request a license from Tencent, which Tencent may grant to You in its sole discretion, and You are not authorized to exercise any of the rights under this Agreement unless or until Tencent otherwise expressly grants You such rights.
5. RULES OF USE.
a. Your use of the Tencent Hunyuan Works must comply with applicable laws and regulations (including trade compliance laws and regulations) and adhere to the Acceptable Use Policy for the Tencent Hunyuan Works, which is hereby incorporated by reference into this Agreement. You must include the use restrictions referenced in these Sections 5(a) and 5(b) as an enforceable provision in any agreement (e.g., license agreement, terms of use, etc.) governing the use and/or distribution of Tencent Hunyuan Works and You must provide notice to subsequent users to whom You distribute that Tencent Hunyuan Works are subject to the use restrictions in these Sections 5(a) and 5(b).
b. You must not use the Tencent Hunyuan Works or any Output or results of the Tencent Hunyuan Works to improve any other large language model (other than Tencent Hunyuan or Model Derivatives thereof).
6. INTELLECTUAL PROPERTY.
a. Subject to Tencent’s ownership of Tencent Hunyuan Works made by or for Tencent and intellectual property rights therein, conditioned upon Your compliance with the terms and conditions of this Agreement, as between You and Tencent, You will be the owner of any derivative works and modifications of the Materials and any Model Derivatives that are made by or for You.
b. No trademark licenses are granted under this Agreement, and in connection with the Tencent Hunyuan Works, Licensee may not use any name or mark owned by or associated with Tencent or any of its affiliates, except as required for reasonable and customary use in describing and distributing the Tencent Hunyuan Works. Tencent hereby grants You a license to use “Tencent Hunyuan” (the “Mark”) solely as required to comply with the provisions of Section 3(c), provided that You comply with any applicable laws related to trademark protection. All goodwill arising out of Your use of the Mark will inure to the benefit of Tencent.
c. If You commence a lawsuit or other proceedings (including a cross-claim or counterclaim in a lawsuit) against Us or any person or entity alleging that the Materials or any Output, or any portion of any of the foregoing, infringe any intellectual property or other right owned or licensable by You, then all licenses granted to You under this Agreement shall terminate as of the date such lawsuit or other proceeding is filed. You will defend, indemnify and hold harmless Us from and against any claim by any Third Party arising out of or related to Your or the Third Party’s use or distribution of the Tencent Hunyuan Works.
d. Tencent claims no rights in Outputs You generate. You and Your users are solely responsible for Outputs and their subsequent uses.
7. DISCLAIMERS OF WARRANTY AND LIMITATIONS OF LIABILITY.
a. We are not obligated to support, update, provide training for, or develop any further version of the Tencent Hunyuan Works or to grant any license thereto.
b. UNLESS AND ONLY TO THE EXTENT REQUIRED BY APPLICABLE LAW, THE TENCENT HUNYUAN WORKS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED “AS IS” WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES OF ANY KIND INCLUDING ANY WARRANTIES OF TITLE, MERCHANTABILITY, NONINFRINGEMENT, COURSE OF DEALING, USAGE OF TRADE, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING, REPRODUCING, MODIFYING, PERFORMING, DISPLAYING OR DISTRIBUTING ANY OF THE TENCENT HUNYUAN WORKS OR OUTPUTS AND ASSUME ANY AND ALL RISKS ASSOCIATED WITH YOUR OR A THIRD PARTY’S USE OR DISTRIBUTION OF ANY OF THE TENCENT HUNYUAN WORKS OR OUTPUTS AND YOUR EXERCISE OF RIGHTS AND PERMISSIONS UNDER THIS AGREEMENT.
c. TO THE FULLEST EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL TENCENT OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, EXEMPLARY, CONSEQUENTIAL OR PUNITIVE DAMAGES, OR LOST PROFITS OF ANY KIND ARISING FROM THIS AGREEMENT OR RELATED TO ANY OF THE TENCENT HUNYUAN WORKS OR OUTPUTS, EVEN IF TENCENT OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING.
8. SURVIVAL AND TERMINATION.
a. The term of this Agreement shall commence upon Your acceptance of this Agreement or access to the Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein.
b. We may terminate this Agreement if You breach any of the terms or conditions of this Agreement. Upon termination of this Agreement, You must promptly delete and cease use of the Tencent Hunyuan Works. Sections 6(a), 6(c), 7 and 9 shall survive the termination of this Agreement.
9. GOVERNING LAW AND JURISDICTION.
a. This Agreement and any dispute arising out of or relating to it will be governed by the laws of the Hong Kong Special Administrative Region of the People’s Republic of China, without regard to conflict of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement.
b. Exclusive jurisdiction and venue for any dispute arising out of or relating to this Agreement will be a court of competent jurisdiction in the Hong Kong Special Administrative Region of the People’s Republic of China, and Tencent and Licensee consent to the exclusive jurisdiction of such court with respect to any such dispute.
EXHIBIT A
ACCEPTABLE USE POLICY
Tencent reserves the right to update this Acceptable Use Policy from time to time.
Last modified: 2024/5/14
Tencent endeavors to promote safe and fair use of its tools and features, including Tencent Hunyuan. You agree not to use Tencent Hunyuan or Model Derivatives:
1. In any way that violates any applicable national, federal, state, local, international or any other law or regulation;
2. To harm Yourself or others;
3. To repurpose or distribute output from Tencent Hunyuan or any Model Derivatives to harm Yourself or others;
4. To override or circumvent the safety guardrails and safeguards We have put in place;
5. For the purpose of exploiting, harming or attempting to exploit or harm minors in any way;
6. To generate or disseminate verifiably false information and/or content with the purpose of harming others or influencing elections;
7. To generate or facilitate false online engagement, including fake reviews and other means of fake online engagement;
8. To intentionally defame, disparage or otherwise harass others;
9. To generate and/or disseminate malware (including ransomware) or any other content to be used for the purpose of harming electronic systems;
10. To generate or disseminate personal identifiable information with the purpose of harming others;
11. To generate or disseminate information (including images, code, posts, articles), and place the information in any public context (including –through the use of bot generated tweets), without expressly and conspicuously identifying that the information and/or content is machine generated;
12. To impersonate another individual without consent, authorization, or legal right;
13. To make high-stakes automated decisions in domains that affect an individual’s safety, rights or wellbeing (e.g., law enforcement, migration, medicine/health, management of critical infrastructure, safety components of products, essential services, credit, employment, housing, education, social scoring, or insurance);
14. In a manner that violates or disrespects the social ethics and moral standards of other countries or regions;
15. To perform, facilitate, threaten, incite, plan, promote or encourage violent extremism or terrorism;
16. For any use intended to discriminate against or harm individuals or groups based on protected characteristics or categories, online or offline social behavior or known or predicted personal or personality characteristics;
17. To intentionally exploit any of the vulnerabilities of a specific group of persons based on their age, social, physical or mental characteristics, in order to materially distort the behavior of a person pertaining to that group in a manner that causes or is likely to cause that person or another person physical or psychological harm;
18. For military purposes;
19. To engage in the unauthorized or unlicensed practice of any profession including, but not limited to, financial, legal, medical/health, or other professional practices.
This diff is collapsed.
# HunyuanDiT
## 论文
**Hunyuan-DiT : A Powerful Multi-Resolution Diffusion Transformer with Fine-Grained Chinese Understanding**
* https://arxiv.org/pdf/2405.08748
## 模型结构
模型基于`transformer decoder`结构,在`DiT`基础上重新设计了`Time Embedding`以及`positional Embedding`的添加方式,`Text Prompt`通过两个`text encoder`进行编码,其余与DiT一致。
![alt text](readme_imgs/model_structure.png)
## 算法原理
使用`self-attention`捕获图像内部的结构信息,使用`cross attention`对齐文本与图像。
![alt text](readme_imgs/alg.png)
## 环境配置
### Docker(方法一)
docker pull image.sourcefind.cn:5000/dcu/admin/base/pytorch:2.1.0-centos7.6-dtk24.04-py310
docker run --shm-size 10g --network=host --name=hunyuan --privileged --device=/dev/kfd --device=/dev/dri --group-add video --cap-add=SYS_PTRACE --security-opt seccomp=unconfined -v 项目地址(绝对路径):/home/ -v /opt/hyhal:/opt/hyhal:ro -it <your IMAGE ID> bash
pip install -r requirements.txt
pip install timm --no-deps
pip install flash_attn-2.0.4+das1.0+82379d7.abi0.dtk2404.torch2.1-cp310-cp310-manylinux2014_x86_64.whl (开发者社区)
### Dockerfile(方法二)
docker build -t <IMAGE_NAME>:<TAG> .
docker run --shm-size 10g --network=host --name=hunyuan --privileged --device=/dev/kfd --device=/dev/dri --group-add video --cap-add=SYS_PTRACE --security-opt seccomp=unconfined -v 项目地址(绝对路径):/home/ -v /opt/hyhal:/opt/hyhal:ro -it <your IMAGE ID> bash
pip install -r requirements.txt
pip install timm --no-deps
pip install flash_attn-2.0.4+das1.0+82379d7.abi0.dtk2404.torch2.1-cp310-cp310-manylinux2014_x86_64.whl (开发者社区)
### Anaconda (方法三)
1、关于本项目DCU显卡所需的特殊深度学习库可从光合开发者社区下载安装:
https://developer.hpccube.com/tool/
DTK驱动:dtk24.04
python:python3.10
torch: 2.1.0
torchvision: 0.16.0
onnx: 1.15.0
flash-attn: 2.0.4
Tips:以上dtk驱动、python、torch等DCU相关工具版本需要严格一一对应
2、其它非特殊库参照requirements.txt安装
pip install -r requirements.txt
pip install timm --no-deps
## 数据集
## 推理
### 模型下载
https://hf-mirror.com/Tencent-Hunyuan/HunyuanDiT/tree/main
下载链接中的所有模型文件,并放入`ckpts`文件中。
ckpts/
├── dialoggen
│ ├── config.json
│ ├── generation_config.json
│ ├── model-00001-of-00004.safetensors
│ ├── model-00002-of-00004.safetensors
│ ├── model-00003-of-00004.safetensors
│ ├── model-00004-of-00004.safetensors
│ ├── model.safetensors.index.json
│ ├── openai
│ │ └── clip-vit-large-patch14-336
│ │ ├── config.json
│ │ ├── merges.txt
│ │ ├── preprocessor_config.json
│ │ ├── pytorch_model.bin
│ │ ├── README.md
│ │ ├── special_tokens_map.json
│ │ ├── tokenizer_config.json
│ │ ├── tokenizer.json
│ │ └── vocab.json
│ ├── special_tokens_map.json
│ ├── tokenizer_config.json
│ └── tokenizer.model
└── t2i
├── clip_text_encoder
│ ├── config.json
│ └── pytorch_model.bin
├── model
│ ├── pytorch_model_ema.pt
│ └── pytorch_model_module.pt
├── mt5
│ ├── config.json
│ ├── download.sh
│ ├── generation_config.json
│ ├── nohup.out
│ ├── pytorch_model.bin
│ ├── README.md
│ ├── special_tokens_map.json
│ ├── spiece.model
│ └── tokenizer_config.json
├── sdxl-vae-fp16-fix
│ ├── config.json
│ ├── diffusion_pytorch_model.bin
│ └── diffusion_pytorch_model.safetensors
└── tokenizer
├── special_tokens_map.json
├── tokenizer_config.json
├── vocab_org.txt
└── vocab.txt
### 命令行
# Prompt Enhancement + Text-to-Image. Torch mode
python sample_t2i.py --prompt "千里冰封万里雪飘"
# Prompt Enhancement + Text-to-Image. Torch mode(在最新硬件上可用)
python sample_t2i.py --prompt "千里冰封万里雪飘" --infer-mode fa
# Only Text-to-Image. Torch mode
python sample_t2i.py --prompt "飞流直下三千尺疑是银河落九天" --no-enhance
# Generate an image with other image sizes.
python sample_t2i.py --prompt "飞流直下三千尺疑是银河落九天" --image-size 1280 768
# Prompt Enhancement + Text-to-Image. DialogGen loads with 4-bit quantization, but it may loss performance.
# 版本问题,暂不支持
python sample_t2i.py --prompt "飞流直下三千尺疑是银河落九天" --load-4bit
参数列表
| Argument | Default | Description |
|:---------------:|:---------:|:---------------------------------------------------:|
| `--prompt` | None | The text prompt for image generation |
| `--image-size` | 1024 1024 | The size of the generated image |
| `--seed` | 42 | The random seed for generating images |
| `--infer-steps` | 100 | The number of steps for sampling |
| `--negative` | - | The negative prompt for image generation |
| `--infer-mode` | torch | The inference mode (torch, fa) |
| `--sampler` | ddpm | The diffusion sampler (ddpm, ddim, or dpmms) |
| `--no-enhance` | False | Disable the prompt enhancement model |
| `--model-root` | ckpts | The root directory of the model checkpoints |
| `--load-key` | ema | Load the student model or EMA model (ema or module) |
| `--load-4bit` | Fasle | Load DialogGen model with 4bit quantization |
### webui(推荐)
# By default, we start a Chinese UI.
python app/hydit_app.py
# Using Flash Attention for acceleration. (在最新硬件上可用)
python app/hydit_app.py --infer-mode fa
# You can disable the enhancement model if the GPU memory is insufficient.
# The enhancement will be unavailable until you restart the app without the `--no-enhance` flag.
python app/hydit_app.py --no-enhance
# Start with English UI
python app/hydit_app.py --lang en
# Start a multi-turn(对话形式) T2I generation UI.
# If your DCU memory is less than 32GB, use '--load-4bit' to enable 4-bit quantization, which requires at least 22GB of memory.
python app/multiTurnT2I_app.py
## result
|||||
|:---|:---:|:---:|:---:|
|结果|![alt text](readme_imgs/result_1.png)|![alt text](readme_imgs/result_2.png)|![alt text](readme_imgs/result_3.png)|
|prompt|千里冰封万里雪飘|飞流直下三千尺疑是银河落九天|一只金毛犬叼着一个RTX4090显卡|
### 精度
## 应用场景
### 算法类别
`AIGC`
### 热点应用行业
`零售,广媒,电商`
## 源码仓库及问题反馈
* https://developer.hpccube.com/codes/modelzoo/hunyuandit_pytorch
## 参考资料
* https://github.com/Tencent/HunyuanDiT/tree/main
<!-- ## **HunyuanDiT** -->
<p align="center">
<img src="https://raw.githubusercontent.com/Tencent/HunyuanDiT/main/asset/logo.png" height=100>
</p>
# Hunyuan-DiT : A Powerful Multi-Resolution Diffusion Transformer with Fine-Grained Chinese Understanding
<div align="center">
<a href="https://github.com/Tencent/HunyuanDiT"><img src="https://img.shields.io/static/v1?label=Hunyuan-DiT Code&message=Github&color=blue&logo=github-pages"></a> &ensp;
<a href="https://dit.hunyuan.tencent.com"><img src="https://img.shields.io/static/v1?label=Project%20Page&message=Github&color=blue&logo=github-pages"></a> &ensp;
<a href="https://arxiv.org/abs/2405.08748"><img src="https://img.shields.io/static/v1?label=Tech Report&message=Arxiv:HunYuan-DiT&color=red&logo=arxiv"></a> &ensp;
<a href="https://arxiv.org/abs/2403.08857"><img src="https://img.shields.io/static/v1?label=Paper&message=Arxiv:DialogGen&color=red&logo=arxiv"></a> &ensp;
<a href="https://huggingface.co/Tencent-Hunyuan/HunyuanDiT"><img src="https://img.shields.io/static/v1?label=Hunyuan-DiT&message=HuggingFace&color=yellow"></a> &ensp;
<a href="https://hunyuan.tencent.com/bot/chat"><img src="https://img.shields.io/static/v1?label=Hunyuan Bot&message=Web&color=green"></a> &ensp;
<a href="https://huggingface.co/spaces/Tencent-Hunyuan/HunyuanDiT"><img src="https://img.shields.io/static/v1?label=Hunyuan-DiT Demo&message=HuggingFace&color=yellow"></a> &ensp;
</div>
-----
This repo contains PyTorch model definitions, pre-trained weights and inference/sampling code for our paper exploring Hunyuan-DiT. You can find more visualizations on our [project page](https://dit.hunyuan.tencent.com/).
> [**Hunyuan-DiT : A Powerful Multi-Resolution Diffusion Transformer with Fine-Grained Chinese Understanding**](https://arxiv.org/abs/2405.08748) <br>
> [**DialogGen:Multi-modal Interactive Dialogue System for Multi-turn Text-to-Image Generation**](https://arxiv.org/abs/2403.08857)<br>
## 🔥🔥🔥 News!!
* May 22, 2024: 🚀 We introduce TensorRT version for Hunyuan-DiT acceleration, which achieves **47%** acceleration on NVIDIA GPUs. Please check [TensorRT-libs](https://huggingface.co/Tencent-Hunyuan/TensorRT-libs) for instructions.
* May 22, 2024: 💬 We support demo running multi-turn text2image generation now. Please check the [script](#using-gradio) below.
## 🤖 Try it on the web
Welcome to our web-based [**Tencent Hunyuan Bot**](https://hunyuan.tencent.com/bot/chat), where you can explore our innovative products! Just input the suggested prompts below or any other **imaginative prompts containing drawing-related keywords** to activate the Hunyuan text-to-image generation feature. Unleash your creativity and create any picture you desire, **all for free!**
You can use simple prompts similar to natural language text
> 画一只穿着西装的猪
>
> draw a pig in a suit
>
> 生成一幅画,赛博朋克风,跑车
>
> generate a painting, cyberpunk style, sports car
or multi-turn language interactions to create the picture.
> 画一个木制的鸟
>
> draw a wooden bird
>
> 变成玻璃的
>
> turn into glass
## 📑 Open-source Plan
- Hunyuan-DiT (Text-to-Image Model)
- [x] Inference
- [x] Checkpoints
- [ ] Distillation Version (Coming soon ⏩️)
- [x] TensorRT Version (Coming soon ⏩️)
- [ ] Training (Coming later ⏩️)
- [DialogGen](https://github.com/Centaurusalpha/DialogGen) (Prompt Enhancement Model)
- [x] Inference
- [X] Web Demo (Gradio)
- [x] Multi-turn T2I Demo (Gradio)
- [X] Cli Demo
## Contents
- [Hunyuan-DiT](#hunyuan-dit--a-powerful-multi-resolution-diffusion-transformer-with-fine-grained-chinese-understanding)
- [Abstract](#abstract)
- [🎉 Hunyuan-DiT Key Features](#-hunyuan-dit-key-features)
- [Chinese-English Bilingual DiT Architecture](#chinese-english-bilingual-dit-architecture)
- [Multi-turn Text2Image Generation](#multi-turn-text2image-generation)
- [📈 Comparisons](#-comparisons)
- [🎥 Visualization](#-visualization)
- [📜 Requirements](#-requirements)
- [🛠 Dependencies and Installation](#%EF%B8%8F-dependencies-and-installation)
- [🧱 Download Pretrained Models](#-download-pretrained-models)
- [🔑 Inference](#-inference)
- [Using Gradio](#using-gradio)
- [Using Command Line](#using-command-line)
- [More Configurations](#more-configurations)
- [🚀 Acceleration (for Linux)](#-acceleration-for-linux)
- [🔗 BibTeX](#-bibtex)
## **Abstract**
We present Hunyuan-DiT, a text-to-image diffusion transformer with fine-grained understanding of both English and Chinese. To construct Hunyuan-DiT, we carefully designed the transformer structure, text encoder, and positional encoding. We also build from scratch a whole data pipeline to update and evaluate data for iterative model optimization. For fine-grained language understanding, we train a Multimodal Large Language Model to refine the captions of the images. Finally, Hunyuan-DiT can perform multi-round multi-modal dialogue with users, generating and refining images according to the context.
Through our carefully designed holistic human evaluation protocol with more than 50 professional human evaluators, Hunyuan-DiT sets a new state-of-the-art in Chinese-to-image generation compared with other open-source models.
## 🎉 **Hunyuan-DiT Key Features**
### **Chinese-English Bilingual DiT Architecture**
Hunyuan-DiT is a diffusion model in the latent space, as depicted in figure below. Following the Latent Diffusion Model, we use a pre-trained Variational Autoencoder (VAE) to compress the images into low-dimensional latent spaces and train a diffusion model to learn the data distribution with diffusion models. Our diffusion model is parameterized with a transformer. To encode the text prompts, we leverage a combination of pre-trained bilingual (English and Chinese) CLIP and multilingual T5 encoder.
<p align="center">
<img src="https://raw.githubusercontent.com/Tencent/HunyuanDiT/main/asset/framework.png" height=450>
</p>
### Multi-turn Text2Image Generation
Understanding natural language instructions and performing multi-turn interaction with users are important for a
text-to-image system. It can help build a dynamic and iterative creation process that bring the user’s idea into reality
step by step. In this section, we will detail how we empower Hunyuan-DiT with the ability to perform multi-round
conversations and image generation. We train MLLM to understand the multi-round user dialogue
and output the new text prompt for image generation.
<p align="center">
<img src="https://raw.githubusercontent.com/Tencent/HunyuanDiT/main/asset/mllm.png" height=300>
</p>
## 📈 Comparisons
In order to comprehensively compare the generation capabilities of HunyuanDiT and other models, we constructed a 4-dimensional test set, including Text-Image Consistency, Excluding AI Artifacts, Subject Clarity, Aesthetic. More than 50 professional evaluators performs the evaluation.
<p align="center">
<table>
<thead>
<tr>
<th rowspan="2">Model</th> <th rowspan="2">Open Source</th> <th>Text-Image Consistency (%)</th> <th>Excluding AI Artifacts (%)</th> <th>Subject Clarity (%)</th> <th rowspan="2">Aesthetics (%)</th> <th rowspan="2">Overall (%)</th>
</tr>
</thead>
<tbody>
<tr>
<td>SDXL</td> <td></td> <td>64.3</td> <td>60.6</td> <td>91.1</td> <td>76.3</td> <td>42.7</td>
</tr>
<tr>
<td>PixArt-α</td> <td></td> <td>68.3</td> <td>60.9</td> <td>93.2</td> <td>77.5</td> <td>45.5</td>
</tr>
<tr>
<td>Playground 2.5</td> <td></td> <td>71.9</td> <td>70.8</td> <td>94.9</td> <td>83.3</td> <td>54.3</td>
</tr>
<tr>
<td>SD 3</td> <td>&#10008</td> <td>77.1</td> <td>69.3</td> <td>94.6</td> <td>82.5</td> <td>56.7</td>
</tr>
<tr>
<td>MidJourney v6</td><td>&#10008</td> <td>73.5</td> <td>80.2</td> <td>93.5</td> <td>87.2</td> <td>63.3</td>
</tr>
<tr>
<td>DALL-E 3</td><td>&#10008</td> <td>83.9</td> <td>80.3</td> <td>96.5</td> <td>89.4</td> <td>71.0</td>
</tr>
<tr style="font-weight: bold; background-color: #f2f2f2;">
<td>Hunyuan-DiT</td><td></td> <td>74.2</td> <td>74.3</td> <td>95.4</td> <td>86.6</td> <td>59.0</td>
</tr>
</tbody>
</table>
</p>
## 🎥 Visualization
* **Chinese Elements**
<p align="center">
<img src="https://raw.githubusercontent.com/Tencent/HunyuanDiT/main/asset/chinese elements understanding.png" height=220>
</p>
* **Long Text Input**
<p align="center">
<img src="https://raw.githubusercontent.com/Tencent/HunyuanDiT/main/asset/long text understanding.png" height=310>
</p>
* **Multi-turn Text2Image Generation**
https://github.com/Tencent/tencent.github.io/assets/27557933/94b4dcc3-104d-44e1-8bb2-dc55108763d1
---
## 📜 Requirements
This repo consists of DialogGen (a prompt enhancement model) and Hunyuan-DiT (a text-to-image model).
The following table shows the requirements for running the models (batch size = 1):
| Model | --load-4bit (DialogGen) | GPU Peak Memory | GPU |
|:-----------------------:|:-----------------------:|:---------------:|:---------------:|
| DialogGen + Hunyuan-DiT | ✘ | 32G | A100 |
| DialogGen + Hunyuan-DiT | ✔ | 22G | A100 |
| Hunyuan-DiT | - | 11G | A100 |
| Hunyuan-DiT | - | 14G | RTX3090/RTX4090 |
* An NVIDIA GPU with CUDA support is required.
* We have tested V100 and A100 GPUs.
* **Minimum**: The minimum GPU memory required is 11GB.
* **Recommended**: We recommend using a GPU with 32GB of memory for better generation quality.
* Tested operating system: Linux
## 🛠️ Dependencies and Installation
Begin by cloning the repository:
```shell
git clone https://github.com/tencent/HunyuanDiT
cd HunyuanDiT
```
### Installation Guide for Linux
We provide an `environment.yml` file for setting up a Conda environment.
Conda's installation instructions are available [here](https://docs.anaconda.com/free/miniconda/index.html).
```shell
# 1. Prepare conda environment
conda env create -f environment.yml
# 2. Activate the environment
conda activate HunyuanDiT
# 3. Install pip dependencies
python -m pip install -r requirements.txt
# 4. (Optional) Install flash attention v2 for acceleration (requires CUDA 11.6 or above)
python -m pip install git+https://github.com/Dao-AILab/flash-attention.git@v2.1.2.post3
```
## 🧱 Download Pretrained Models
To download the model, first install the huggingface-cli. (Detailed instructions are available [here](https://huggingface.co/docs/huggingface_hub/guides/cli).)
```shell
python -m pip install "huggingface_hub[cli]"
```
Then download the model using the following commands:
```shell
# Create a directory named 'ckpts' where the model will be saved, fulfilling the prerequisites for running the demo.
mkdir ckpts
# Use the huggingface-cli tool to download the model.
# The download time may vary from 10 minutes to 1 hour depending on network conditions.
huggingface-cli download Tencent-Hunyuan/HunyuanDiT --local-dir ./ckpts
```
<details>
<summary>💡Tips for using huggingface-cli (network problem)</summary>
##### 1. Using HF-Mirror
If you encounter slow download speeds in China, you can try a mirror to speed up the download process. For example,
```shell
HF_ENDPOINT=https://hf-mirror.com huggingface-cli download Tencent-Hunyuan/HunyuanDiT --local-dir ./ckpts
```
##### 2. Resume Download
`huggingface-cli` supports resuming downloads. If the download is interrupted, you can just rerun the download
command to resume the download process.
Note: If an `No such file or directory: 'ckpts/.huggingface/.gitignore.lock'` like error occurs during the download
process, you can ignore the error and rerun the download command.
</details>
---
All models will be automatically downloaded. For more information about the model, visit the Hugging Face repository [here](https://huggingface.co/Tencent-Hunyuan/HunyuanDiT).
| Model | #Params | Download URL |
|:------------------:|:-------:|:-------------------------------------------------------------------------------------------------------:|
| mT5 | 1.6B | [mT5](https://huggingface.co/Tencent-Hunyuan/HunyuanDiT/tree/main/t2i/mt5) |
| CLIP | 350M | [CLIP](https://huggingface.co/Tencent-Hunyuan/HunyuanDiT/tree/main/t2i/clip_text_encoder) |
| DialogGen | 7.0B | [DialogGen](https://huggingface.co/Tencent-Hunyuan/HunyuanDiT/tree/main/dialoggen) |
| sdxl-vae-fp16-fix | 83M | [sdxl-vae-fp16-fix](https://huggingface.co/Tencent-Hunyuan/HunyuanDiT/tree/main/t2i/sdxl-vae-fp16-fix) |
| Hunyuan-DiT | 1.5B | [Hunyuan-DiT](https://huggingface.co/Tencent-Hunyuan/HunyuanDiT/tree/main/t2i/model) |
## 🔑 Inference
### Using Gradio
Make sure you have activated the conda environment before running the following command.
```shell
# By default, we start a Chinese UI.
python app/hydit_app.py
# Using Flash Attention for acceleration.
python app/hydit_app.py --infer-mode fa
# You can disable the enhancement model if the GPU memory is insufficient.
# The enhancement will be unavailable until you restart the app without the `--no-enhance` flag.
python app/hydit_app.py --no-enhance
# Start with English UI
python app/hydit_app.py --lang en
# Start a multi-turn T2I generation UI.
# If your GPU memory is less than 32GB, use '--load-4bit' to enable 4-bit quantization, which requires at least 22GB of memory.
python app/multiTurnT2I_app.py
```
Then the demo can be accessed through http://0.0.0.0:443
### Using Command Line
We provide several commands to quick start:
```shell
# Prompt Enhancement + Text-to-Image. Torch mode
python sample_t2i.py --prompt "渔舟唱晚"
# Only Text-to-Image. Torch mode
python sample_t2i.py --prompt "渔舟唱晚" --no-enhance
# Only Text-to-Image. Flash Attention mode
python sample_t2i.py --infer-mode fa --prompt "渔舟唱晚"
# Generate an image with other image sizes.
python sample_t2i.py --prompt "渔舟唱晚" --image-size 1280 768
# Prompt Enhancement + Text-to-Image. DialogGen loads with 4-bit quantization, but it may loss performance.
python sample_t2i.py --prompt "渔舟唱晚" --load-4bit
```
More example prompts can be found in [example_prompts.txt](example_prompts.txt)
### More Configurations
We list some more useful configurations for easy usage:
| Argument | Default | Description |
|:---------------:|:---------:|:---------------------------------------------------:|
| `--prompt` | None | The text prompt for image generation |
| `--image-size` | 1024 1024 | The size of the generated image |
| `--seed` | 42 | The random seed for generating images |
| `--infer-steps` | 100 | The number of steps for sampling |
| `--negative` | - | The negative prompt for image generation |
| `--infer-mode` | torch | The inference mode (torch, fa, or trt) |
| `--sampler` | ddpm | The diffusion sampler (ddpm, ddim, or dpmms) |
| `--no-enhance` | False | Disable the prompt enhancement model |
| `--model-root` | ckpts | The root directory of the model checkpoints |
| `--load-key` | ema | Load the student model or EMA model (ema or module) |
| `--load-4bit` | Fasle | Load DialogGen model with 4bit quantization |
## 🚀 Acceleration (for Linux)
We provide TensorRT version of HunyuanDiT for inference acceleration (faster than flash attention).
See [Tencent-Hunyuan/TensorRT-libs](https://huggingface.co/Tencent-Hunyuan/TensorRT-libs) for more details.
## 🔗 BibTeX
If you find [Hunyuan-DiT](https://arxiv.org/abs/2405.08748) or [DialogGen](https://arxiv.org/abs/2403.08857) useful for your research and applications, please cite using this BibTeX:
```BibTeX
@misc{li2024hunyuandit,
title={Hunyuan-DiT: A Powerful Multi-Resolution Diffusion Transformer with Fine-Grained Chinese Understanding},
author={Zhimin Li and Jianwei Zhang and Qin Lin and Jiangfeng Xiong and Yanxin Long and Xinchi Deng and Yingfang Zhang and Xingchao Liu and Minbin Huang and Zedong Xiao and Dayou Chen and Jiajun He and Jiahao Li and Wenyue Li and Chen Zhang and Rongwei Quan and Jianxiang Lu and Jiabin Huang and Xiaoyan Yuan and Xiaoxiao Zheng and Yixuan Li and Jihong Zhang and Chao Zhang and Meng Chen and Jie Liu and Zheng Fang and Weiyan Wang and Jinbao Xue and Yangyu Tao and Jianchen Zhu and Kai Liu and Sihuan Lin and Yifu Sun and Yun Li and Dongdong Wang and Mingtao Chen and Zhichao Hu and Xiao Xiao and Yan Chen and Yuhong Liu and Wei Liu and Di Wang and Yong Yang and Jie Jiang and Qinglin Lu},
year={2024},
eprint={2405.08748},
archivePrefix={arXiv},
primaryClass={cs.CV}
}
@article{huang2024dialoggen,
title={DialogGen: Multi-modal Interactive Dialogue System for Multi-turn Text-to-Image Generation},
author={Huang, Minbin and Long, Yanxin and Deng, Xinchi and Chu, Ruihang and Xiong, Jiangfeng and Liang, Xiaodan and Cheng, Hong and Lu, Qinglin and Liu, Wei},
journal={arXiv preprint arXiv:2403.08857},
year={2024}
}
```
## Start History
<a href="https://star-history.com/#Tencent/HunyuanDiT&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Tencent/HunyuanDiT&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Tencent/HunyuanDiT&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=Tencent/HunyuanDiT&type=Date" />
</picture>
</a>
import gradio as gr
import pandas as pd
from pathlib import Path
from PIL import Image
import sys
sys.path.insert(0, str(Path(__file__).parent.parent))
from hydit.constants import SAMPLER_FACTORY
from sample_t2i import inferencer
ROOT = Path(__file__).parent.parent
SAMPLERS = list(SAMPLER_FACTORY.keys())
SIZES = {
"square": (1024, 1024),
"landscape": (768, 1280),
"portrait": (1280, 768),
}
def get_strings(lang):
lang_file = Path(f"app/lang/{lang}.csv")
strings = pd.read_csv(lang_file, header=0)
strings = strings.set_index("key")['value'].to_dict()
return strings
args, gen, enhancer = inferencer()
strings = get_strings(args.lang)
def infer(
prompt,
negative_prompt,
seed,
cfg_scale,
infer_steps,
oriW, oriH,
sampler,
size,
enhance
):
if enhance and enhancer is not None:
success, enhanced_prompt = enhancer(prompt)
if not success:
fail_image = Image.open(ROOT / 'app/fail.png')
return fail_image
else:
enhanced_prompt = None
height, width = SIZES[size]
results = gen.predict(prompt,
height=height,
width=width,
seed=seed,
enhanced_prompt=enhanced_prompt,
negative_prompt=negative_prompt,
infer_steps=infer_steps,
guidance_scale=cfg_scale,
batch_size=1,
src_size_cond=(oriW, oriH),
sampler=sampler,
)
image = results['images'][0]
return image
def ui():
block = gr.Blocks()
description = f"""
# {strings['title']}
## {strings['desc']}
"""
with block:
with gr.Row():
gr.Markdown(description)
with gr.Row():
with gr.Column():
with gr.Row():
size = gr.Radio(
label=strings['size'], choices=[
(strings['square'], 'square'),
(strings['landscape'], 'landscape'),
(strings['portrait'], 'portrait'),
],
value="square"
)
prompt = gr.Textbox(label=strings['prompt'], value=strings['default prompt'], lines=3)
with gr.Row():
infer_steps = gr.Slider(
label=strings['infer steps'], minimum=1, maximum=200, value=100, step=1,
)
seed = gr.Number(
label=strings['seed'], minimum=-1, maximum=1_000_000_000, value=42, step=1, precision=0,
)
enhance = gr.Checkbox(
label=strings['enhance'], value=enhancer is not None, interactive=True,
)
with gr.Accordion(
strings['accordion'], open=False
):
with gr.Row():
negative_prompt = gr.Textbox(label=strings['negative_prompt'],
value=gen.default_negative_prompt,
lines=2,
)
with gr.Row():
sampler = gr.Dropdown(SAMPLERS, label=strings['sampler'], value="ddpm")
cfg_scale = gr.Slider(
label=strings['cfg'], minimum=1.0, maximum=16.0, value=6.0, step=1
)
oriW = gr.Number(
label=strings['width cond'], minimum=1024, maximum=4096, value=1024, step=64, precision=0,
min_width=80,
)
oriH = gr.Number(
label=strings['height cond'], minimum=1024, maximum=4096, value=1024, step=64, precision=0,
min_width=80,
)
with gr.Row():
advanced_button = gr.Button(strings['run'])
with gr.Column():
default_img = Image.open(ROOT / 'app/default.png')
output_img = gr.Image(
label=strings['generated image'],
interactive=False,
format='png',
value=default_img,
)
advanced_button.click(
fn=infer,
inputs=[
prompt, negative_prompt, seed, cfg_scale, infer_steps,
oriW, oriH, sampler, size, enhance,
],
outputs=output_img,
)
with gr.Row():
gr.Examples([
['一只小猫'],
['现实主义风格,画面主要描述一个巴洛克风格的花瓶,带有金色的装饰边框,花瓶上盛开着各种色彩鲜艳的花,白色背景'],
['一只聪明的狐狸走在阔叶树林里, 旁边是一条小溪, 细节真实, 摄影'],
['飞流直下三千尺,疑是银河落九天'],
['一只长靴猫手持亮银色的宝剑,身着铠甲,眼神坚毅,站在一堆金币上,背景是暗色调的洞穴,图像上有金币的光影点缀。'],
['麻婆豆腐'],
['苏州园林'],
['一颗新鲜的草莓特写,红色的外表,表面布满许多种子,背景是淡绿色的叶子'],
['请将“杞人忧天”的样子画出来'],
['枯藤老树昏鸦,小桥流水人家'],
['湖水清澈,天空湛蓝,阳光灿烂。一只优雅的白天鹅在湖边游泳。它周围有几只小鸭子,看起来非常可爱,整个画面给人一种宁静祥和的感觉。'],
['一朵鲜艳的红色玫瑰花,花瓣撒有一些水珠,晶莹剔透,特写镜头'],
['臭豆腐'],
['九寨沟'],
['俗语“鲤鱼跃龙门”'],
['风格是写实,画面主要描述一个亚洲戏曲艺术家正在表演,她穿着华丽的戏服,脸上戴着精致的面具,身姿优雅,背景是古色古香的舞台,镜头是近景'],
],
[prompt],
label=strings['examples']
)
return block
if __name__ == "__main__":
interface = ui()
interface.launch(server_name="0.0.0.0", server_port=443, share=True)
key,value
size,Size
sampler,Sampler
prompt,Prompt
default prompt,"A cute cat"
negative_prompt,Negative Prompt
seed,Seed
cfg,CFG Scale
infer steps,Sampling Steps
batch size,Batch Size
width cond,Width Cond
height cond,Height Cond
enhance,Prompt Enhancement
run,Submit
square,Square(1024x1024)
landscape,Landscape(1280x768)
portrait,Portrait(768x1280)
accordion,Advanced Options
generated image,HunYuanDiT Generated Image
examples,More Examples
title,Hunyuan-DiT
desc,A Powerful Multi-Resolution Diffusion Transformer with Fine-Grained Chinese Understanding
\ No newline at end of file
key,value
size,尺寸
sampler,采样器
prompt,文本描述
default prompt,"一只可爱的猫"
negative_prompt,负向词
seed,种子
cfg,CFG系数
infer steps,采样步数
batch size,批大小
width cond,宽度条件
height cond,高度条件
enhance,文本增强
run,提交生成
square,方形(1024x1024)
portrait,竖屏(1280x768)
landscape,横屏(768x1280)
accordion,高级设置
generated image,HunYuanDiT 生成
examples,更多示例
title,混元-DiT
desc,具有细粒度中文理解的高性能多分辨率 Diffusion Transformer 模型
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment