Commit c0ac5e6d authored by zhangwq5's avatar zhangwq5
Browse files

edit

parent 98eaf5d7
Pipeline #2895 failed with stages
in 0 seconds
# Contributors
This file contains the list of everyone who contributed to the repository
<br>
<table>
<th>Contributors1</th><th>Contributors2</th> <tr>
<td><img src="xxx1">
<br>
<a href="xxx1">xxx1</a></td>
<td><img src="xxx2">
<br>
<a href="xxx2">xxx2</a></td>
</tr>
</table>
<br>
### Thanks to everyone who helped in building this Repository :)
Copyright 2018-2020 Open-MMLab. All rights reserved.
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 2018-2020 Open-MMLab.
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.
# Qwen-Image-Edit_hf
## 论文
`Qwen-Image Technical Report`
- https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-Image/Qwen_Image.pdf
## 模型结构
Qwen-Image-Edit 是 Qwen-Image 的图像编辑版本。它基于强大的 20B Qwen-Image 模型构建而成,成功地将 Qwen-Image 独特的文字呈现能力扩展到了图像编辑任务中,实现了精准的文字编辑功能。此外,Qwen-Image-Edit 同时将输入的图像传递给 Qwen2.5-VL(用于视觉语义控制)和 VAE 编码器(用于视觉外观控制),从而在语义和外观编辑方面都具备了相应的能力。
<div align=center>
<img src="./doc/MMDIT.png"/>
</div>
## 算法原理
Qwen-Image-Edit的核心是扩散模型,并创新地使用了一个强大的多模态大语言模型(Qwen2.5-VL)来深度理解复杂的图文指令,从而在生成高质量图像的同时,实现了业界领先的、尤其是在中英文上的精准文字渲染能力。
<div align=center>
<img src="./doc/qwen-image.png"/>
</div>
## 环境配置
### 硬件需求
DCU型号:K100_AI,节点数量:1台,卡数:2张。
### Docker(方法一)
```bash
docker pull image.sourcefind.cn:5000/dcu/admin/base/custom:vllm0.8.5-ubuntu22.04-dtk25.04-rc7-das1.5-py3.10-20250612-fixpy-rocblas0611-rc2
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
cd /your_code_path/qwen-image-edit_hf
pip install -r requirements.txt
# 需要安装torch2.5.1或以上版本
wget https://download.sourcefind.cn:65024/directlink/4/pytorch/DAS1.6/torch-2.5.1+das.opt1.dtk25041-cp310-cp310-manylinux_2_28_x86_64.whl
pip install torch-2.5.1+das.opt1.dtk25041-cp310-cp310-manylinux_2_28_x86_64.whl
```
### Dockerfile(方法二)
此处提供dockerfile的使用方法
```bash
cd docker
docker build --no-cache -t qwen-image-edit: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
cd /your_code_path/qwen-image-edit_hf
pip install -r requirements.txt
# 需要安装torch2.5.1或以上版本
wget https://download.sourcefind.cn:65024/directlink/4/pytorch/DAS1.6/torch-2.5.1+das.opt1.dtk25041-cp310-cp310-manylinux_2_28_x86_64.whl
pip install torch-2.5.1+das.opt1.dtk25041-cp310-cp310-manylinux_2_28_x86_64.whl
```
### Anaconda(方法三)
关于本项目DCU显卡所需的特殊深度学习库可从[光合](https://developer.sourcefind.cn/tool/)开发者社区下载安装。
```bash
DTK: 25.04
python: 3.10
torch: 2.5.1+das.opt2.dtk25041
```
`Tips:以上dtk驱动、pytorch等DCU相关工具版本需要严格一一对应`
其它非深度学习库安装方式如下:
```bash
pip install -r requirements.txt
```
## 数据集
暂无
## 训练
暂无
## 推理
### diffusers推理方法
```bash
## 设置双卡推理
export HIP_VISIBLE_DEVICES=6,7
## 代码内部请修改model_name路径
python ./infer/infer_hf.py
```
## result
```bash
Processing task 1:
......
......
......
All inference tasks completed.
```
### 精度
```bash
# 运行acc.py之前,请分别在DCU和GPU上运行infer_hf.py,并将代码中folder_gpu变量和folder_dcu变量替换成生成的文件夹路径
开始对比文件夹 './output_images_A800' (基准)'./output_images_K100AI' (测试)...
- 对比 Add_a_small_wooden_output_5.png: MAE=2.0897, PSNR=32.24dB, SSIM=0.9842
- 对比 Change_the_word_output_2.png: MAE=0.4869, PSNR=39.33dB, SSIM=0.9954
- 对比 Replace_the_background_output_4.png: MAE=1.7056, PSNR=31.50dB, SSIM=0.9824
- 对比 Replace_the_woman_output_6.png: MAE=0.3702, PSNR=50.32dB, SSIM=0.9975
- 对比 Take_a_Breather_output_1.png: MAE=0.4357, PSNR=41.63dB, SSIM=0.9963
==================================================
--- 批量对比平均结果 ---
成功对比图片对数: 5
平均绝对误差 (MAE): 1.0176
平均峰值信噪比 (PSNR): 39.00 dB
平均结构相似性 (SSIM): 0.9912
==================================================
```
DCU(K100AI)与GPU(A800)在BF16精度下推理Qwen-Image-Edit模型,结果精度一致,推理框架:diffusers。
## 应用场景
### 算法类别
`图像生成`
### 热点应用行业
`制造,金融,教育`
## 预训练权重
- [Qwen/Qwen-Image-Edit](https://hf-mirror.com/Qwen/Qwen-Image-Edit)
## 源码仓库及问题反馈
- http://developer.sourcefind.cn/codes/modelzoo/qwen-image-edit_hf.git
## 参考资料
- https://qwenlm.github.io/blog/qwen-image-edit/
Qwen-Image-Edit是 Qwen-Image 的图像编辑版本,将文字渲染能力拓展到了图像编辑任务中,实现了精准的文字编辑。
\ No newline at end of file
FROM image.sourcefind.cn:5000/dcu/admin/base/custom:vllm0.8.5-ubuntu22.04-dtk25.04-rc7-das1.5-py3.10-20250612-fixpy-rocblas0611-rc2
\ No newline at end of file
icon.png

67.5 KB

import numpy as np
from PIL import Image
from skimage.metrics import peak_signal_noise_ratio as psnr
from skimage.metrics import structural_similarity as ssim
import os
import csv
def calculate_mae(image_a, image_b):
"""计算两张图片的平均绝对误差 (Mean Absolute Error, MAE)"""
image_a = image_a.astype(np.float32)
image_b = image_b.astype(np.float32)
mae_value = np.mean(np.abs(image_a - image_b))
return mae_value
def compare_images(image_path1, image_path2):
"""加载两张图片并计算它们的MAE, PSNR, 和 SSIM"""
try:
img1_pil = Image.open(image_path1).convert('RGB')
img2_pil = Image.open(image_path2).convert('RGB')
except FileNotFoundError as e:
print(f"错误: 无法找到文件。 {e}")
return None
img1_np = np.array(img1_pil)
img2_np = np.array(img2_pil)
if img1_np.shape != img2_np.shape:
print(f"错误: 图片 '{os.path.basename(image_path1)}' 尺寸不匹配。")
print(f" - 图片1尺寸: {img1_np.shape}")
print(f" - 图片2尺寸: {img2_np.shape}")
return None
mae_value = calculate_mae(img1_np, img2_np)
psnr_value = psnr(img1_np, img2_np, data_range=255)
try:
ssim_value = ssim(img1_np, img2_np, data_range=255, channel_axis=-1, win_size=7)
except TypeError:
ssim_value = ssim(img1_np, img2_np, data_range=255, multichannel=True, win_size=7)
return {"MAE": mae_value, "PSNR": psnr_value, "SSIM": ssim_value}
if __name__ == "__main__":
# *****************************************************************
# * 请在这里修改你的文件夹路径 *
# *****************************************************************
folder_gpu = "./output_images_A800" # 基准文件夹 (GPU推理结果)
folder_dcu = "./output_images_K100AI" # 待测试文件夹 (DCU推理结果)
report_filename = "comparison_report.csv"
if not os.path.isdir(folder_gpu) or not os.path.isdir(folder_dcu):
print(f"错误:请确保文件夹 '{folder_gpu}' 和 '{folder_dcu}' 都存在。")
exit()
print(f"开始对比文件夹 '{folder_gpu}' (基准) 和 '{folder_dcu}' (测试)...")
all_metrics = []
base_filenames = sorted(os.listdir(folder_gpu))
for filename in base_filenames:
if not filename.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp')):
continue
path1 = os.path.join(folder_gpu, filename)
path2 = os.path.join(folder_dcu, filename)
if not os.path.exists(path2):
print(f" [跳过] 在 '{folder_dcu}' 中未找到对应的文件: {filename}")
continue
results = compare_images(path1, path2)
if results:
print(f" - 对比 {filename}: "
f"MAE={results['MAE']:.4f}, "
f"PSNR={results['PSNR']:.2f}dB, "
f"SSIM={results['SSIM']:.4f}")
all_metrics.append({
'filename': filename,
'MAE': results['MAE'],
'PSNR': results['PSNR'],
'SSIM': results['SSIM']
})
# --- 计算并打印平均结果 ---
if not all_metrics:
print("\n未找到任何可以对比的图片对。请检查文件夹内容和文件名。")
else:
# 使用Numpy高效计算平均值
avg_mae = np.mean([m['MAE'] for m in all_metrics])
avg_psnr = np.mean([m['PSNR'] for m in all_metrics])
avg_ssim = np.mean([m['SSIM'] for m in all_metrics])
print("\n" + "="*50)
print("--- 批量对比平均结果 ---")
print(f"成功对比图片对数: {len(all_metrics)}")
print(f"平均绝对误差 (MAE): {avg_mae:.4f}")
print(f"平均峰值信噪比 (PSNR): {avg_psnr:.2f} dB")
print(f"平均结构相似性 (SSIM): {avg_ssim:.4f}")
print("="*50)
# --- 将详细结果写入CSV文件 ---
try:
with open(report_filename, 'w', newline='', encoding='utf-8') as csvfile:
fieldnames = ['filename', 'MAE', 'PSNR', 'SSIM']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(all_metrics)
# 写入平均值
writer.writerow({})
writer.writerow({'filename': 'Average', 'MAE': avg_mae, 'PSNR': avg_psnr, 'SSIM': avg_ssim})
print(f"\n详细报告已保存至: {report_filename}")
except Exception as e:
print(f"\n保存报告失败: {e}")
\ No newline at end of file
filename,MAE,PSNR,SSIM
Add_a_small_wooden_output_5.png,2.0897036,32.23572562876897,0.984223018079311
Change_the_word_output_2.png,0.48687163,39.33201774772982,0.9954169983939914
Replace_the_background_output_4.png,1.7055854,31.501655221325425,0.9824052945937866
Replace_the_woman_output_6.png,0.3701708,50.317291097024544,0.9975423187586948
Take_a_Breather_output_1.png,0.43572536,41.63346109329262,0.9963357851640264
,,,
Average,1.0176113,39.00403015762827,0.991184682997962
[
{
"input_image":"./input_image/Take_a_Breather.png",
"prompt":"Change the phrase 'Take a Breather' on the note to 'Relax and Recharge'"
},
{
"input_image":"./input_image/Change_the_word.png",
"prompt":"Change the word 'HEALTH INSURANCE' to '明天 会更好' on the Scrabble tiles."
},
{
"input_image":"./input_image/Replace_the_background.png",
"prompt":"Replace the background with a sunnybeach scene featuring fine sand,gentle waves, and a clear blue sky"
},
{
"input_image":"./input_image/Add_a_small_wooden.png",
"prompt":"Add a small wooden sign in the foreground in front of the penguins with the text 'Welcome to Penguin Beach"
},
{
"input_image":"./input_image/Replace_the_woman.png",
"prompt":"Replace the woman's polka-dot blouse with a light blue button-up shirt."
}
]
\ No newline at end of file
import os
import json
from PIL import Image
import torch
from diffusers import QwenImageEditPipeline
output_dir = "./output_images_A800"
os.makedirs(output_dir, exist_ok=True)
pipeline = QwenImageEditPipeline.from_pretrained("/home/zwq/model/Qwen-Image-Edit")
print("pipeline loaded")
pipeline.to(torch.bfloat16)
pipeline.to("cuda")
pipeline.set_progress_bar_config(disable=None)
json_file_path = "./infer.json"
try:
with open(json_file_path, 'r', encoding='utf-8') as f:
inference_data = json.load(f)
except FileNotFoundError:
print(f"Error: JSON file not found at {json_file_path}")
exit()
except json.JSONDecodeError:
print(f"Error: Could not decode JSON from {json_file_path}. Please check file format.")
exit()
print(f"Loaded {len(inference_data)} inference tasks from {json_file_path}")
for i, task in enumerate(inference_data):
input_image_path = task.get("input_image")
prompt = task.get("prompt")
if not input_image_path or not prompt:
print(f"Skipping task {i+1} due to missing 'input_image' or 'prompt'. Task data: {task}")
continue
try:
image = Image.open(input_image_path).convert("RGB")
print(f"\nProcessing task {i+1}:")
print(f" Input Image: {input_image_path}")
print(f" Prompt: {prompt}")
inputs = {
"image": image,
"prompt": prompt,
"generator": torch.manual_seed(0),
"true_cfg_scale": 4.0,
"negative_prompt": " ",
"num_inference_steps": 50,
}
with torch.inference_mode():
output = pipeline(**inputs)
output_image = output.images[0]
base_name = os.path.splitext(os.path.basename(input_image_path))[0]
output_image_name = f"{base_name}_output_{i+1}.png"
output_image_path = os.path.join(output_dir, output_image_name)
output_image.save(output_image_path)
print(f" Image saved at {os.path.abspath(output_image_path)}")
except FileNotFoundError:
print(f"Error: Input image not found at {input_image_path}. Skipping this task.")
except Exception as e:
print(f"An error occurred while processing task {i+1} (Image: {input_image_path}, Prompt: {prompt}): {e}")
print("\nAll inference tasks completed.")
\ 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