Commit f17c9671 authored by zzg_666's avatar zzg_666
Browse files

first commit

parents
Pipeline #3026 failed with stages
in 0 seconds
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
# Emu3.5_pytorch
## 论文
[Emu3.5](https://arxiv.org/pdf/2510.26583)
## 模型结构
Emu3.5在“Next-Token Prediction”范式的基础上,模拟人类自然学习方式,以自回归架构实现了对多模态序列的“Next-State Prediction (NSP)”,获得了可泛化的世界建模能力。
<div align=center>
<img src="./doc/arch.png"/>
</div>
## 算法原理
Emu3.5 是由北京智源人工智能研究院发布的多模态世界大模型。它通过在超过10万亿的多模态Token(主要源自互联网视频,总时长约790年)上进行端到端预训练,具备了原生的世界建模能力,能够理解和生成文本、图像和视频等多种模态的数据。
## 环境配置
### 硬件需求
DCU型号:BW1000,节点数量:1台,卡数:2张。
`-v 路径``docker_name``imageID`根据实际情况修改
### Docker(方法一)
```bash
docker pull image.sourcefind.cn:5000/dcu/admin/base/pytorch:2.7.1-ubuntu22.04-dtk25.04.2-py3.10-alpha
docker run -it --shm-size 200g --network=host --name {docker_name} --privileged --device=/dev/kfd --device=/dev/dri --device=/dev/mkfd --group-add video --cap-add=SYS_PTRACE --security-opt seccomp=unconfined -u root -v /path/your_code_data/:/path/your_code_data/ -v /opt/hyhal/:/opt/hyhal/:ro {imageID} bash
pip install http://10.16.4.1:8000/debug/torchaudio/dtk25.04.2-beta-bug-fix/torch251-audio/torch251-audio-fastpt/torchaudio-2.5.1a0%2Bd178b24-cp310-cp310-manylinux_2_28_x86_64.whl
pip install http://10.16.4.1:8000/debug/flash_attn/dtk25.04.2-rc1/dtk25.04-llvm0106/flash_attn-2.6.1%2Bdas.opt1.dtk2504-cp310-cp310-manylinux_2_28_x86_64.whl
pip install transformers -U
cd /your_code_path/emu3.5_pytorch
pip install -r requirements.txt
```
### Dockerfile(方法二)
```bash
cd docker
docker build --no-cache -t emu3.5_pytorch:latest .
docker run -it --shm-size 200g --network=host --name {docker_name} --privileged --device=/dev/kfd --device=/dev/dri --device=/dev/mkfd --group-add video --cap-add=SYS_PTRACE --security-opt seccomp=unconfined -u root -v /path/your_code_data/:/path/your_code_data/ -v /opt/hyhal/:/opt/hyhal/:ro {imageID} bash
pip install http://10.16.4.1:8000/debug/torchaudio/dtk25.04.2-beta-bug-fix/torch251-audio/torch251-audio-fastpt/torchaudio-2.5.1a0%2Bd178b24-cp310-cp310-manylinux_2_28_x86_64.whl
pip install http://10.16.4.1:8000/debug/flash_attn/dtk25.04.2-rc1/dtk25.04-llvm0106/flash_attn-2.6.1%2Bdas.opt1.dtk2504-cp310-cp310-manylinux_2_28_x86_64.whl
pip install transformers -U
cd /your_code_path/emu3.5_pytorch
pip install -r requirements.txt
```
### Anaconda(方法三)
关于本项目DCU显卡所需的特殊深度学习库可从[光合](https://developer.sourcefind.cn/tool/)开发者社区下载安装。
```bash
DTK: 25.04.2
python: 3.10
torch: 2.7.1a0+das.opt1.dtk25042
accelerate:1.11.0
transformers: 4.48.2
flash_attn:2.6.1+das.opt1.dtk2504
```
`Tips:以上dtk驱动、python、torch等DCU相关工具版本需要严格一一对应`
```bash
pip install http://10.16.4.1:8000/debug/torchaudio/dtk25.04.2-beta-bug-fix/torch251-audio/torch251-audio-fastpt/torchaudio-2.5.1a0%2Bd178b24-cp310-cp310-manylinux_2_28_x86_64.whl
pip install http://10.16.4.1:8000/debug/flash_attn/dtk25.04.2-rc1/dtk25.04-llvm0106/flash_attn-2.6.1%2Bdas.opt1.dtk2504-cp310-cp310-manylinux_2_28_x86_64.whl
pip install transformers -U
cd /your_code_path/emu3.5_pytorch
pip install -r requirements.txt
```
## 数据集
## 训练
暂无
## 推理
样例模型:[Emu3.5](https://huggingface.co/BAAI/Emu3.5-Image)
不同任务推理命令如下:
```bash
# 🖼️ Text-to-Image (T2I) task
python inference.py --cfg configs/example_config_t2i.py
# 🔄 Any-to-Image (X2I) task
python inference.py --cfg configs/example_config_x2i.py
# 🎯 Visual Guidance task
python inference.py --cfg configs/example_config_visual_guidance.py
# 📖 Visual Narrative task
python inference.py --cfg configs/example_config_visual_narrative.py
# After running inference, the model will generate results in protobuf format (.pb files) for each input prompt.
```
可视化Protobuf文件输出
```bash
python src/utils/vis_proto.py --input <input_proto_file> --output <output_dir> [--video]
```
## result
```bash
Handling prompt: <|extra_203|>You are a helpful assistant for t2i task. USER: A lively comic-style illustration depicting two humorous cartoon dogs interacting near a freshly dug backyard hole surrounded by scattered dirt, garden tools, blooming flowers, and a wooden fence background. At the upper-left side, Dog One stands nervously near the messy hole, ears down and eyes wide open with an expression of concern. Its speech bubble is an oval shape, outlined neatly with smooth, slightly rounded corners, positioned clearly above Dog One's head. Inside, clearly readable playful handwritten-style text emphasizes the dog's worried tone, saying, "You sure the humans won't notice this giant hole here?". Toward the lower-right side, Dog Two sits calmly and confidently with a cheerful, carefree expression, wagging its tail gently. Its speech bubble is rectangular with softly rounded edges, placed slightly overlapping with Dog One's speech bubble to guide the reader naturally downward diagonally across the frame. Dog Two's friendly, humorous response appears in a whimsical italicized comic font, clearly stating, "Relax! We'll just blame it on the neighbor's cat again!". Each speech bubble creats the playful and engaging backyard scene. ASSISTANT: <|extra_100|>
```
<div align=center>
<img src="./doc/result.png"/>
</div>
### 精度
DCU与GPU精度一致,推理框架:pytorch。
## 应用场景
### 算法类别
多模态
### 热点应用行业
制造,广媒,家居,教育
## 预训练权重
- [Emu3.5](https://huggingface.co/BAAI/Emu3.5/tree/main)
- [Emu3.5-Image](https://huggingface.co/BAAI/Emu3.5-Image/tree/main)
- [Emu3.5-VisionTokenizer](https://huggingface.co/BAAI/Emu3.5-VisionTokenizer/tree/main)
## 源码仓库及问题反馈
- https://developer.sourcefind.cn/codes/modelzoo/emu3.5_pytorch
## 参考资料
- https://huggingface.co/BAAI/Emu3.5-Image
# Copyright 2025 BAAI. and/or its affiliates.
# SPDX-License-Identifier: Apache-2.0
from pathlib import Path
from src.utils.logging_utils import setup_logger
cfg_name = Path(__file__).stem
model_path = "/home/zzg_zone/LLM-Models/BAAI/Emu3.5-Image" # download from hf
vq_path = "./BAAI/Emu3.5-VisionTokenizer" # download from hf
tokenizer_path = "./src/tokenizer_emu3_ibq"
vq_type = "ibq"
# task_type in {"t2i", "x2i", "howto", "story", "explore", "vla"}
task_type = "story"
# whether prompts include an input image token and provide reference_image paths
use_image = True
# saving config
exp_name = "emu3p5"
save_path = f"./outputs/{exp_name}"
save_to_proto = True
setup_logger(save_path)
hf_device = "auto"
vq_device = "cuda:0"
streaming = False
unconditional_type = "no_text"
classifier_free_guidance = 3.0 # (recommended)Emu3.5 interleaved: 3, T2I/X2I: 2; Emu3.5-Image T2I/X2I: 5
max_new_tokens = 32768
image_area = 518400
def build_unc_and_template(task: str, with_image: bool):
# System prompt header and role formatting remain consistent
task_str = task.lower()
if with_image:
unc_p = "<|extra_203|>You are a helpful assistant. USER: <|IMAGE|> ASSISTANT: <|extra_100|>"
tmpl = "<|extra_203|>You are a helpful assistant for %s task. USER: {question}<|IMAGE|> ASSISTANT: <|extra_100|>" % task_str
else:
unc_p = "<|extra_203|>You are a helpful assistant. USER: ASSISTANT: <|extra_100|>"
tmpl = "<|extra_203|>You are a helpful assistant for %s task. USER: {question} ASSISTANT: <|extra_100|>" % task_str
return unc_p, tmpl
unc_prompt, template = build_unc_and_template(task_type, use_image)
sampling_params = dict(
use_cache=True,
# text token sampling config
text_top_k=1024,
text_top_p=0.9,
text_temperature=1.0,
# image token sampling config
image_top_k=10240,
image_top_p=1.0,
image_temperature=1.0,
# general config
top_k=131072, # default topk (backward compatible)
top_p=1.0, # default top_p (backward compatible)
temperature=1.0, # default temperature (backward compatible)
num_beams_per_group=1,
num_beam_groups=1,
diversity_penalty=0.0,
max_new_tokens=max_new_tokens,
guidance_scale=1.0,
# enable differential sampling
use_differential_sampling=True,
)
sampling_params["do_sample"] = sampling_params["num_beam_groups"] <= 1
sampling_params["num_beams"] = sampling_params["num_beams_per_group"] * sampling_params["num_beam_groups"]
special_tokens = dict(
BOS="<|extra_203|>",
EOS="<|extra_204|>",
PAD="<|endoftext|>",
EOL="<|extra_200|>",
EOF="<|extra_201|>",
TMS="<|extra_202|>",
IMG="<|image token|>",
BOI="<|image start|>",
EOI="<|image end|>",
BSS="<|extra_100|>",
ESS="<|extra_101|>",
BOG="<|extra_60|>",
EOG="<|extra_61|>",
BOC="<|extra_50|>",
EOC="<|extra_51|>",
)
seed = 6666
# prompts config
# If use_image=True, each item should be a dict with {"prompt", "reference_image"}.
# If use_image=False, each item is a plain text string.
_prompts_base = [
{
"prompt": "Tell a story about a clay astronaut exploring Mars and discovering a new continent hidden beneath the red dust.",
"reference_image": "assets/ref_img.png",
},
# {
# "prompt": "Generate a clay astronaut in the given image exploring Mars.",
# "reference_image": "assets/ref_img.png",
# },
]
if use_image:
prompts = _prompts_base
else:
prompts = [p["prompt"] for p in _prompts_base]
# Copyright 2025 BAAI. and/or its affiliates.
# SPDX-License-Identifier: Apache-2.0
from pathlib import Path
from src.utils.logging_utils import setup_logger
cfg_name = Path(__file__).stem
model_path = "/home/zzg_zone/LLM-Models/BAAI/Emu3.5-Image" # download from hf
vq_path = "./BAAI/Emu3.5-VisionTokenizer" # download from hf
tokenizer_path = "./src/tokenizer_emu3_ibq"
vq_type = "ibq"
# task_type in {"t2i", "x2i", "howto", "story", "explore", "vla"}
task_type = "t2i"
# whether prompts include an input image token and provide reference_image paths
use_image = False
# saving config
exp_name = "emu3p5-image"
save_path = f"./outputs/{exp_name}/{task_type}"
save_to_proto = True
setup_logger(save_path)
hf_device = "auto"
vq_device = "cuda:0"
streaming = False
unconditional_type = "no_text"
classifier_free_guidance = 5.0
max_new_tokens = 5120
image_area = 1048576
aspect_ratios = {
"4:3": "55*73",
"21:9": "41*97",
"16:9": "47*85",
"3:2": "52*78",
"1:1": "64*64",
"3:4": "73*55",
"9:16": "85*47",
"2:3": "78*52",
"default": "55*73",
"auto": None,
}
def get_target_size(aspect_ratio: str):
value = aspect_ratios.get(aspect_ratio, None)
if value is None:
return None, None
h, w = map(int, value.split("*"))
return h, w
# --- example usage ---
aspect_ratio = "default" # User input, which can be replaced by "4:3", "1:1", "auto" etc.
target_height, target_width = get_target_size(aspect_ratio)
print(f"Aspect Ratio = {aspect_ratio}")
print(f"target_height = {target_height}, target_width = {target_width}")
def build_unc_and_template(task: str, with_image: bool):
# System prompt header and role formatting remain consistent
task_str = task.lower()
if with_image:
unc_p = "<|extra_203|>You are a helpful assistant. USER: <|IMAGE|> ASSISTANT: <|extra_100|>"
tmpl = "<|extra_203|>You are a helpful assistant for %s task. USER: {question}<|IMAGE|> ASSISTANT: <|extra_100|>" % task_str
else:
unc_p = "<|extra_203|>You are a helpful assistant. USER: ASSISTANT: <|extra_100|>"
tmpl = "<|extra_203|>You are a helpful assistant for %s task. USER: {question} ASSISTANT: <|extra_100|>" % task_str
return unc_p, tmpl
unc_prompt, template = build_unc_and_template(task_type, use_image)
sampling_params = dict(
use_cache=True,
# text token sampling config
text_top_k=1024,
text_top_p=0.9,
text_temperature=1.0,
# image token sampling config
image_top_k=5120,
image_top_p=1.0,
image_temperature=1.0,
# general config
top_k=131072, # default topk (backward compatible)
top_p=1.0, # default top_p (backward compatible)
temperature=1.0, # default temperature (backward compatible)
num_beams_per_group=1,
num_beam_groups=1,
diversity_penalty=0.0,
max_new_tokens=max_new_tokens,
guidance_scale=1.0,
# enable differential sampling
use_differential_sampling=True,
)
sampling_params["do_sample"] = sampling_params["num_beam_groups"] <= 1
sampling_params["num_beams"] = sampling_params["num_beams_per_group"] * sampling_params["num_beam_groups"]
special_tokens = dict(
BOS="<|extra_203|>",
EOS="<|extra_204|>",
PAD="<|endoftext|>",
EOL="<|extra_200|>",
EOF="<|extra_201|>",
TMS="<|extra_202|>",
IMG="<|image token|>",
BOI="<|image start|>",
EOI="<|image end|>",
BSS="<|extra_100|>",
ESS="<|extra_101|>",
BOG="<|extra_60|>",
EOG="<|extra_61|>",
BOC="<|extra_50|>",
EOC="<|extra_51|>",
)
seed = 6666
# prompts config
# If use_image=True, each item should be a dict with {"prompt", "reference_image"}.
# If use_image=False, each item is a plain text string.
_prompts_base = [
{
"prompt":"""A lively comic-style illustration depicting two humorous cartoon dogs interacting near a freshly dug backyard hole surrounded by scattered dirt, garden tools, blooming flowers, and a wooden fence background. At the upper-left side, Dog One stands nervously near the messy hole, ears down and eyes wide open with an expression of concern. Its speech bubble is an oval shape, outlined neatly with smooth, slightly rounded corners, positioned clearly above Dog One's head. Inside, clearly readable playful handwritten-style text emphasizes the dog's worried tone, saying, "You sure the humans won't notice this giant hole here?". Toward the lower-right side, Dog Two sits calmly and confidently with a cheerful, carefree expression, wagging its tail gently. Its speech bubble is rectangular with softly rounded edges, placed slightly overlapping with Dog One's speech bubble to guide the reader naturally downward diagonally across the frame. Dog Two's friendly, humorous response appears in a whimsical italicized comic font, clearly stating, "Relax! We'll just blame it on the neighbor's cat again!". Each speech bubble creats the playful and engaging backyard scene.""",
},
]
if use_image:
prompts = _prompts_base
else:
prompts = [p["prompt"] for p in _prompts_base]
# Copyright 2025 BAAI. and/or its affiliates.
# SPDX-License-Identifier: Apache-2.0
from pathlib import Path
from src.utils.logging_utils import setup_logger
cfg_name = Path(__file__).stem
model_path = "./weights/Emu3.5" # download from hf
vq_path = "./weights/Emu3.5-VisionTokenizer" # download from hf
tokenizer_path = "./src/tokenizer_emu3_ibq"
vq_type = "ibq"
# task_type in {"t2i", "x2i", "howto", "story", "explore", "vla"}
task_type = "howto"
# whether prompts include an input image token and provide reference_image paths
use_image = False
# saving config
exp_name = "emu3p5"
save_path = f"./outputs/{exp_name}/{task_type}"
save_to_proto = True
setup_logger(save_path)
hf_device = "auto"
vq_device = "cuda:0"
streaming = False
unconditional_type = "no_text"
classifier_free_guidance = 3.0
max_new_tokens = 32768
image_area = 518400
def build_unc_and_template(task: str, with_image: bool):
# System prompt header and role formatting remain consistent
task_str = task.lower()
if task_str == 'howto':
extra_system_prompt = ' Please generate a response with interleaved text and images.'
else:
extra_system_prompt = ''
if with_image:
unc_p = "<|extra_203|>You are a helpful assistant. USER: <|IMAGE|> ASSISTANT: <|extra_100|>"
tmpl = "<|extra_203|>You are a helpful assistant for %s task.%s USER: {question}<|IMAGE|> ASSISTANT: <|extra_100|>"% (task_str, extra_system_prompt)
else:
unc_p = "<|extra_203|>You are a helpful assistant. USER: ASSISTANT: <|extra_100|>"
tmpl = "<|extra_203|>You are a helpful assistant for %s task.%s USER: {question} ASSISTANT: <|extra_100|>" % (task_str, extra_system_prompt)
return unc_p, tmpl
unc_prompt, template = build_unc_and_template(task_type, use_image)
sampling_params = dict(
use_cache=True,
# text token sampling config
text_top_k=200,
text_top_p=0.8,
text_temperature=0.7,
# image token sampling config
image_top_k=10240,
image_top_p=1.0,
image_temperature=1.0,
# general config
top_k=131072, # default topk (backward compatible)
top_p=1.0, # default top_p (backward compatible)
temperature=1.0, # default temperature (backward compatible)
num_beams_per_group=1,
num_beam_groups=1,
diversity_penalty=0.0,
max_new_tokens=max_new_tokens,
guidance_scale=1.0,
# enable differential sampling
use_differential_sampling=True,
)
sampling_params["do_sample"] = sampling_params["num_beam_groups"] <= 1
sampling_params["num_beams"] = sampling_params["num_beams_per_group"] * sampling_params["num_beam_groups"]
special_tokens = dict(
BOS="<|extra_203|>",
EOS="<|extra_204|>",
PAD="<|endoftext|>",
EOL="<|extra_200|>",
EOF="<|extra_201|>",
TMS="<|extra_202|>",
IMG="<|image token|>",
BOI="<|image start|>",
EOI="<|image end|>",
BSS="<|extra_100|>",
ESS="<|extra_101|>",
BOG="<|extra_60|>",
EOG="<|extra_61|>",
BOC="<|extra_50|>",
EOC="<|extra_51|>",
)
seed = 6666
# prompts config
# If use_image=True, each item should be a dict with {"prompt", "reference_image"}.
# If use_image=False, each item is a plain text string.
_prompts_base = [
{
"prompt": "How to cook Shrimp, Celery, and Pork Dumplings.",
"reference_image": "",
},
# You can specify the length of the generated steps of Visual Guidance task by adding 'Please provide xxx steps for the task.'.
# {
# "prompt": "How to cook Shrimp, Celery, and Pork Dumplings. Please provide 7 steps for the task.",
# "reference_image": "",
# },
]
if use_image:
prompts = _prompts_base
else:
prompts = [p["prompt"] for p in _prompts_base]
\ No newline at end of file
# Copyright 2025 BAAI. and/or its affiliates.
# SPDX-License-Identifier: Apache-2.0
from pathlib import Path
from src.utils.logging_utils import setup_logger
cfg_name = Path(__file__).stem
model_path = "./weights/Emu3.5" # download from hf
vq_path = "./weights/Emu3.5-VisionTokenizer" # download from hf
tokenizer_path = "./src/tokenizer_emu3_ibq"
vq_type = "ibq"
# task_type in {"t2i", "x2i", "howto", "story", "explore", "vla"}
task_type = "story"
# whether prompts include an input image token and provide reference_image paths
use_image = False
# saving config
exp_name = "emu3p5"
save_path = f"./outputs/{exp_name}/{task_type}"
save_to_proto = True
setup_logger(save_path)
hf_device = "auto"
vq_device = "cuda:0"
streaming = False
unconditional_type = "no_text"
classifier_free_guidance = 3.0
max_new_tokens = 32768
image_area = 518400
def build_unc_and_template(task: str, with_image: bool):
# System prompt header and role formatting remain consistent
task_str = task.lower()
if with_image:
unc_p = "<|extra_203|>You are a helpful assistant. USER: <|IMAGE|> ASSISTANT: <|extra_100|>"
tmpl = "<|extra_203|>You are a helpful assistant for %s task. USER: {question}<|IMAGE|> ASSISTANT: <|extra_100|>" % task_str
else:
unc_p = "<|extra_203|>You are a helpful assistant. USER: ASSISTANT: <|extra_100|>"
tmpl = "<|extra_203|>You are a helpful assistant for %s task. USER: {question} ASSISTANT: <|extra_100|>" % task_str
return unc_p, tmpl
unc_prompt, template = build_unc_and_template(task_type, use_image)
sampling_params = dict(
use_cache=True,
# text token sampling config
text_top_k=1024,
text_top_p=0.9,
text_temperature=1.0,
# image token sampling config
image_top_k=10240,
image_top_p=1.0,
image_temperature=1.0,
# general config
top_k=131072, # default topk (backward compatible)
top_p=1.0, # default top_p (backward compatible)
temperature=1.0, # default temperature (backward compatible)
num_beams_per_group=1,
num_beam_groups=1,
diversity_penalty=0.0,
max_new_tokens=max_new_tokens,
guidance_scale=1.0,
# enable differential sampling
use_differential_sampling=True,
)
sampling_params["do_sample"] = sampling_params["num_beam_groups"] <= 1
sampling_params["num_beams"] = sampling_params["num_beams_per_group"] * sampling_params["num_beam_groups"]
special_tokens = dict(
BOS="<|extra_203|>",
EOS="<|extra_204|>",
PAD="<|endoftext|>",
EOL="<|extra_200|>",
EOF="<|extra_201|>",
TMS="<|extra_202|>",
IMG="<|image token|>",
BOI="<|image start|>",
EOI="<|image end|>",
BSS="<|extra_100|>",
ESS="<|extra_101|>",
BOG="<|extra_60|>",
EOG="<|extra_61|>",
BOC="<|extra_50|>",
EOC="<|extra_51|>",
)
seed = 6666
# prompts config
# If use_image=True, each item should be a dict with {"prompt", "reference_image"}.
# If use_image=False, each item is a plain text string.
_prompts_base = [
{
"prompt": "Imagine a heartwarming tale about a little hedgehog who overcomes his fear of the dark with the help of glowing fireflies.",
"reference_image": "",
},
# {
# "prompt": "Tell a story about a clay astronaut exploring Mars and discovering a new continent hidden beneath the red dust.",
# "reference_image": "assets/ref_img.png",
# },
# {
# "prompt": "Generate a clay astronaut in the given image exploring Mars.",
# "reference_image": "assets/ref_img.png",
# },
]
if use_image:
prompts = _prompts_base
else:
prompts = [p["prompt"] for p in _prompts_base]
# Copyright 2025 BAAI. and/or its affiliates.
# SPDX-License-Identifier: Apache-2.0
from pathlib import Path
from src.utils.logging_utils import setup_logger
cfg_name = Path(__file__).stem
model_path = "path_to_emu3.5_model" # download from hf
vq_path = "path_to_vq_model" # download from hf
tokenizer_path = "path_to_tokenizer"
vq_type = "ibq"
task_type = "x2i"
# whether prompts include an input image token and provide reference_image paths
use_image = True
# saving config
exp_name = "emu3p5-image"
save_path = f"./outputs/{exp_name}/{task_type}"
save_to_proto = True
setup_logger(save_path)
hf_device = "auto"
vq_device = "cuda:0"
streaming = False
unconditional_type = "no_text"
classifier_free_guidance = 3.0 # For Emu3.5 model: we recommend set to 2
max_new_tokens = 5120
image_area = 1048576
# prompts config
# If use_image=True, each item should be a dict with {"prompt", "reference_image"}. reference_image should be a list of image (maximum 3 images).
# If use_image=False, each item is a plain text string.
_prompts_base = [
{
"prompt": "As shown in the second figure: The ripe strawberry rests on a green leaf in the garden. Replace the chocolate truffle in first image with ripe strawberry from 2nd image",
"reference_image": ["./assets/ref_0.png", "./assets/ref_1.png"],
},
]
if use_image:
prompts = _prompts_base
else:
prompts = [p["prompt"] for p in _prompts_base]
def build_unc_and_template(task: str, with_image: bool):
# System prompt header and role formatting remain consistent
task_str = task.lower()
if with_image:
unc_p = "<|extra_203|>You are a helpful assistant. USER: <|IMAGE|> ASSISTANT: <|extra_100|>"
tmpl = "<|extra_203|>You are a helpful assistant for %s task. USER: <|IMAGE|>{question} ASSISTANT: <|extra_100|>" % task_str
else:
unc_p = "<|extra_203|>You are a helpful assistant. USER: ASSISTANT: <|extra_100|>"
tmpl = "<|extra_203|>You are a helpful assistant for %s task. USER: {question} ASSISTANT: <|extra_100|>" % task_str
return unc_p, tmpl
unc_prompt, template = build_unc_and_template(task_type, use_image)
# sampling paras config
sampling_params = dict(
use_cache=True,
# text token sampling config
text_top_k=1024,
text_top_p=0.9,
text_temperature=1.0,
# image token sampling config
image_top_k=5120,
image_top_p=1.0,
image_temperature=1.0,
# general config
top_k=131072, # default topk (backward compatible)
top_p=1.0, # default top_p (backward compatible)
temperature=1.0, # default temperature (backward compatible)
num_beams_per_group=1,
num_beam_groups=1,
diversity_penalty=0.0,
max_new_tokens=max_new_tokens,
guidance_scale=1.0,
# enable differential sampling
use_differential_sampling=True,
)
sampling_params["do_sample"] = sampling_params["num_beam_groups"] <= 1
sampling_params["num_beams"] = sampling_params["num_beams_per_group"] * sampling_params["num_beam_groups"]
special_tokens = dict(
BOS="<|extra_203|>",
EOS="<|extra_204|>",
PAD="<|endoftext|>",
EOL="<|extra_200|>",
EOF="<|extra_201|>",
TMS="<|extra_202|>",
IMG="<|image token|>",
BOI="<|image start|>",
EOI="<|image end|>",
BSS="<|extra_100|>",
ESS="<|extra_101|>",
BOG="<|extra_60|>",
EOG="<|extra_61|>",
BOC="<|extra_50|>",
EOC="<|extra_51|>",
)
seed = 6666
FROM image.sourcefind.cn:5000/dcu/admin/base/pytorch:2.7.1-ubuntu22.04-dtk25.04.2-py3.10-alpha
\ No newline at end of file
icon.png

50.3 KB

# Copyright 2025 BAAI. and/or its affiliates.
# SPDX-License-Identifier: Apache-2.0
import argparse
import importlib as imp
import os
import os.path as osp
from pathlib import Path
import random
from time import sleep
from PIL import Image
import torch
from tqdm import tqdm
from src.utils.model_utils import build_emu3p5
from src.utils.generation_utils import generate, multimodal_decode
from src.utils.painting_utils import ProtoWriter
from src.utils.input_utils import build_image, smart_resize
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--cfg", default="", type=str)
parser.add_argument("--num_workers", default=1, type=int)
parser.add_argument("--worker_id", default=0, type=int)
args = parser.parse_args()
return args
def inference(
cfg,
model,
tokenizer,
vq_model,
):
save_path = cfg.save_path
os.makedirs(save_path, exist_ok=True)
os.makedirs(f"{save_path}/proto", exist_ok=True)
proto_writer = ProtoWriter()
for name, question in tqdm(cfg.prompts, total=len(cfg.prompts)):
if osp.exists(f"{save_path}/proto/{name}.pb"):
print(f"[WARNING] Result already exists, skipping {name}", flush=True)
continue
torch.cuda.empty_cache()
reference_image = None
if not isinstance(question, str):
if isinstance(question["reference_image"], list):
print(f"[INFO] {len(question['reference_image'])} reference images are provided")
reference_image = []
for img in question["reference_image"]:
reference_image.append(Image.open(img).convert("RGB"))
else:
print (f"[INFO] 1 reference image is provided")
reference_image = Image.open(question["reference_image"]).convert("RGB")
question = question["prompt"]
else:
print(f"[INFO] No reference image is provided")
proto_writer.clear()
proto_writer.extend([["question", question]])
if reference_image is not None:
if isinstance(reference_image, list):
for idx, img in enumerate(reference_image):
proto_writer.extend([[f"reference_image", img]])
else:
proto_writer.extend([["reference_image", reference_image]])
success = True
prompt = cfg.template.format(question=question)
print(f"[INFO] Handling prompt: {prompt}")
if reference_image is not None:
if isinstance(reference_image, list):
image_str = ""
for img in reference_image:
image_str += build_image(img, cfg, tokenizer, vq_model)
else:
image_str = build_image(reference_image, cfg, tokenizer, vq_model)
prompt = prompt.replace("<|IMAGE|>", image_str)
unc_prompt = cfg.unc_prompt.replace("<|IMAGE|>", image_str)
else:
unc_prompt = cfg.unc_prompt
input_ids = tokenizer.encode(prompt, return_tensors="pt", add_special_tokens=False).to(model.device)
if input_ids[0, 0] != cfg.special_token_ids["BOS"]:
BOS = torch.Tensor([[cfg.special_token_ids["BOS"]]], device=input_ids.device, dtype=input_ids.dtype)
input_ids = torch.cat([BOS, input_ids], dim=1)
unconditional_ids = tokenizer.encode(unc_prompt, return_tensors="pt", add_special_tokens=False).to(model.device)
if hasattr(cfg, "img_unc_prompt"):
full_unc_ids = tokenizer.encode(cfg.img_unc_prompt, return_tensors="pt", add_special_tokens=False).to(model.device)
else:
full_unc_ids = None
force_same_image_size = True
# for x2i task, if multiple reference images are provided as a list, force_same_image_size should be False
if isinstance(reference_image, list) and len(reference_image) > 1:
force_same_image_size = False
for result_tokens in generate(cfg, model, tokenizer, input_ids, unconditional_ids, full_unc_ids, force_same_image_size):
try:
result = tokenizer.decode(result_tokens, skip_special_tokens=False)
mm_out = multimodal_decode(result, tokenizer, vq_model)
proto_writer.extend(mm_out)
except Exception as e:
success = False
print(f"[ERROR] Failed to generate token sequence: {e}")
break
if not success:
continue
proto_writer.save(f"{save_path}/proto/{name}.pb")
def main():
args = parse_args()
cfg_name = Path(args.cfg).stem
cfg_package = Path(args.cfg).parent.__str__().replace("/", ".")
cfg = imp.import_module(f".{cfg_name}", package=cfg_package)
rank, world_size = args.worker_id, args.num_workers
cfg.rank = rank
cfg.world_size = world_size
if isinstance(cfg.prompts, dict):
cfg.prompts = [(n, p) for n, p in cfg.prompts.items()]
else:
cfg.prompts = [(f"{idx:03d}", p) for idx, p in enumerate(cfg.prompts)]
cfg.prompts = [(n, p) for n, p in cfg.prompts if not osp.exists(f"{cfg.save_path}/proto/{n}.pb")]
cfg.prompts = cfg.prompts[rank::world_size]
cfg.num_prompts = len(cfg.prompts)
hf_device, vq_device = cfg.hf_device, cfg.vq_device
model, tokenizer, vq_model = build_emu3p5(
cfg.model_path,
cfg.tokenizer_path,
cfg.vq_path,
vq_type=cfg.vq_type,
model_device=hf_device,
vq_device=vq_device,
**getattr(cfg, "diffusion_decoder_kwargs", {}),
)
print(f"[INFO] Model loaded successfully")
cfg.special_token_ids = {}
for k, v in cfg.special_tokens.items():
cfg.special_token_ids[k] = tokenizer.encode(v)[0]
random.seed(cfg.seed + rank)
inference(
cfg=cfg,
model=model,
tokenizer=tokenizer,
vq_model=vq_model,
)
print(f"[INFO] Inference finished")
if __name__ == "__main__":
main()
# 模型唯一标识
modelCode=1806
# 模型名称
modelName=Emu3.5_pytorch
# 模型描述
modelDescription=通过在超过10万亿的多模态Token(主要源自互联网视频,总时长约790年)上进行端到端预训练,具备了原生的世界建模能力,能够理解和生成文本、图像和视频等多种模态的数据。
# 应用场景
appScenario=推理,制造,广媒,家居,教育
# 框架类型
frameType=pytorch
#加速卡类型
accelerateType=BW1000
#torch>=2.6.0
#torchvision>=0.15.0
#torchaudio>=2.0.0
transformers==4.48.2
accelerate>=0.20.0
pillow>=9.0.0
numpy>=1.21.0
tqdm>=4.64.0
protobuf>=3.20.0
tiktoken>=0.12.0
imageio==2.37.0
imageio-ffmpeg==0.6.0
omegaconf==2.3.0
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