Commit e3810de3 authored by zhangwq5's avatar zhangwq5
Browse files

first commit

parent 9114d40e
# 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.
# 仓库目录结构
* 除预训练模型外其他文件总大小尽量不要超过50M
```
Project
├── dataset
│   ├── label_1
│    ├── xxx.png
│    ├── xxx.png
│ └── ...
│   └── label_2
│    ├── xxx.png
│    ├── xxx.png
│ └── ...
├── model
│   ├── xxx.pth #预训练模型
│   ├── xxx.onnx #对应的onnx模型
│ └── xxx.mxr #对应的migraphx离线推理模型
├── doc
│   ├── icon.png
│   ├── xxx.png
│ └── xxx.png
├── README.md
├── requirement.txt
├── model.properties
├── code_file1.py
├── code_file2.py
├── code_file3.py
├── dirs
│   ├── code_file4.py
│   ├── code_file5.py
└── └── code_file6.py
```
* icon.png:模型的图标文件,上传者需放至项目根目录供前端读取,所需算法类别图标可到 飞书->云文档->云盘->icon 查找,当前没有所需算法类别图标则提交设计申请即可。
![icon](./icon.png)
* README.md:参照下图,`十二大标题`为必选项,二级标题以下的标题或内容根据自己的项目灵活增删。
![img](./doc/readme.png)
* requirement.txt:模型依赖统一写到此文件,与深度学习相关的库请注释,以免安装为nv库。
```
说明:数据基本由公司网盘储存并提供url下载或直接读取,数据信息介绍由超算互联网商城提供,内部无数据时提供官网下载地址。
```
* 需要提供迷你数据集以供使用者快速上手项目。
* model.properties:`五大属性`固定模板如下:
```
# 模型唯一标识
modelCode=Project ID
# 模型名称
modelName=模型名称(同项目名称:模型名_深度学习框架)
# 模型描述
modelDescription=简要描述此模型(尽量50字以内)
# 应用场景
appScenario=推理,训练,OCR,政府,交通,零售,金融,医疗(首先描述推理、训练信息,然后描述算法类别信息,最后描述应用行业信息,多个标签用英文逗号隔开。)
# 框架类型
frameType=paddle(说明使用的算法框架, 多个标签用英文逗号隔开。)
```
* 增加LICENSE(必要),源github无LICENSE则在LICENSE里填:None LICENSE Currently;CONTRIBUTORS.md根据源github有无提供(非必要)。
\ No newline at end of file
# Multilingual E5
## 论文
`Multilingual E5 Text Embeddings: A Technical Report`
- https://arxiv.org/abs/2402.05672
## 模型结构
多语言E5模型基于多语言MiniLM和XLM-RoBERTa,通过对比预训练和监督微调构建,支持小、基础、大型和指令调整变体,适用于多语言信息检索和语义相似性任务。
<div align=center>
<img src="./doc/xxx.png"/>
</div>
## 算法原理
多语言E5模型采用两阶段训练:首先通过InfoNCE对比损失在约10亿多语言文本对上进行弱监督预训练,学习语义表示;随后在约160万高品质标注数据上进行监督微调,结合硬负样本挖掘和跨编码器知识蒸馏,优化嵌入空间的语义相似性和多语言检索性能。
<div align=center>
<img src="./doc/xxx.png"/>
</div>
## 环境配置
### 硬件需求
DCU型号:K100_AI,节点数量:1台,卡数:4张。
### 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/multilingual-e5-large_pytorch
pip install transformers>=4.51.0
pip install sentence-transformers>=4.1.0
```
### Dockerfile(方法二)
此处提供dockerfile的使用方法
```
docker build --no-cache -t xxx:latest .
docker run xxx
```
### Anaconda(方法三)
此处提供本地配置、编译的详细步骤,例如:
关于本项目DCU显卡所需的特殊深度学习库可从[光合](https://developer.sourcefind.cn/tool/)开发者社区下载安装。
```bash
DTK: 25.04
python: 3.10
vllm: 0.8.5
torch: 2.4.1+das.opt2.dtk2504
deepspeed: 0.14.2+das.opt2.dtk2504
```
`Tips:以上dtk驱动、python、paddle等DCU相关工具版本需要严格一一对应`
其它非深度学习库安装方式如下:
```bash
pip install transformers>=4.51.0
pip install sentence-transformers>=2.7.0
```
## 数据集
`此处填写公开数据集名称`
- 此处填写公开数据集在公司内部的下载地址(数据集存放中心为:[SCNet AIDatasets](http://111.11.100.223:58001/ui/aihub/datasets) (非必须),模型用到的各公开数据集请分别填上具体地址。),过小权重文件可打包到项目里。
- 此处填写公开数据集官网下载地址(必须)。
此处提供数据预处理脚本的使用方法
```
python xxx.py
```
项目中已提供用于试验训练的迷你数据集,训练数据目录结构如下,用于正常训练的完整数据集请按此目录结构进行制备:
```
── dataset
│   ├── label_1
│    ├── xxx.png
│    ├── xxx.png
│ └── ...
│   └── label_2
│    ├── xxx.png
│    ├── xxx.png
│ └── ...
```
## 训练
一般情况下,ModelZoo上的项目提供单机训练的启动方法即可,单机多卡、单机单卡至少提供其一训练方法。
### 单机多卡
```
sh xxx.sh # 或python xxx.py
```
### 单机单卡
```
sh xxx.sh 或python xxx.py
```
## 推理
### vllm推理方法
```
python ./infer/infer_vllm.py --model /path/your_model_path/
```
## result
```
提示: '你好,我的名字是' | 嵌入: [0.018951416015625, -0.0121612548828125, -0.042022705078125, -0.03936767578125, 0.007015228271484375, -0.040130615234375, -0.0189361572265625, 0.04925537109375, 0.037322998046875, -0.01776123046875, 0.035614013671875, 0.01861572265625, -0.048248291015625, -0.015716552734375, -0.032745361328125, -0.01061248779296875, ...] (大小=1024)
提示: '美国总统是' | 嵌入: [0.034271240234375, 0.0015573501586914062, -0.04266357421875, -0.0291290283203125, 0.01983642578125, -0.0435791015625, 0.02117919921875, 0.0745849609375, 0.062255859375, -0.002933502197265625, 0.0333251953125, 0.037200927734375, -0.0291748046875, -0.034210205078125, -0.01837158203125, -0.02392578125, ...] (大小=1024)
提示: '法国的首都是' | 嵌入: [0.051971435546875, 0.0068359375, -0.021087646484375, -0.0528564453125, 0.0175018310546875, -0.0198211669921875, 0.0147552490234375, 0.051300048828125, 0.057861328125, -0.017242431640625, 0.0195159912109375, 0.0260162353515625, -0.0477294921875, -0.0278167724609375, -0.04351806640625, -0.0135498046875, ...] (大小=1024)
提示: '人工智能的未来是' | 嵌入: [0.016876220703125, 0.0059814453125, -0.0308074951171875, -0.05712890625, 0.01332855224609375, -0.00024700164794921875, -0.00913238525390625, 0.08123779296875, 0.049835205078125, -0.026123046875, 0.039398193359375, -0.00975799560546875, -0.0128326416015625, -0.021697998046875, -0.033447265625, -0.0147857666015625, ...] (大小=1024)
所有嵌入已保存到: ./infer/embeddings_A800.npy
```
### 精度
```
# 运行acc.py之前,请分别在DCU和GPU上运行infer_vllm.py,得到各自的embedding数据
python ./infer/acc.py --gpu_embeddings /path/embeddings_A800.npy --dcu_embeddings /path/embeddings_dcu.npy
```
结果
```
abs_diff:[[1.52587891e-05 1.52587891e-05 3.05175781e-05 ... 2.67028809e-05
1.22070312e-04 1.06811523e-04]
[3.05175781e-05 1.33514404e-05 6.10351562e-05 ... 2.28881836e-05
1.22070312e-04 3.05175781e-05]
[3.05175781e-05 3.43322754e-05 9.15527344e-05 ... 0.00000000e+00
3.05175781e-05 1.22070312e-04]
[1.52587891e-05 3.05175781e-05 0.00000000e+00 ... 5.34057617e-05
7.62939453e-05 3.81469727e-05]]
mean_abs_diff:[3.93284135e-05 4.01343568e-05 3.79525591e-05 5.03971823e-05]
```
DCU与GPU精度一致,推理框架:vllm。
## 应用场景
### 算法类别
`文本理解`
### 热点应用行业
`制造,零售,互联网`
## 预训练权重
- [multilingual-e5-large](https://huggingface.co/intfloat/multilingual-e5-large)
## 源码仓库及问题反馈
-
## 参考资料
- https://github.com/microsoft/unilm/tree/master/e5
icon.png

2.27 KB

import numpy as np
import argparse
import os
def parse_args():
parser = argparse.ArgumentParser(description='Compare two embedding files and calculate absolute differences.')
parser.add_argument('--gpu_embeddings', type=str, required=True,
help='Path to the GPU embeddings file (.npy)')
parser.add_argument('--dcu_embeddings', type=str, required=True,
help='Path to the DCU embeddings file (.npy)')
return parser.parse_args()
def main(args):
script_dir = os.path.dirname(os.path.abspath(__file__))
embeddings_1 = np.load(args.gpu_embeddings)
embeddings_2 = np.load(args.dcu_embeddings)
if embeddings_1.shape != embeddings_2.shape:
raise ValueError("两个嵌入文件的形状不匹配!")
abs_diff = np.abs(embeddings_1 - embeddings_2)
mean_abs_diff = np.mean(abs_diff, axis=1)
print(f"abs_diff:\n{abs_diff}")
print(f"mean_abs_diff:\n{mean_abs_diff}")
if __name__ == "__main__":
args = parse_args()
main(args)
\ No newline at end of file
from sentence_transformers import SentenceTransformer
model = SentenceTransformer('/home/zwq2/model/models/multilingual-e5-large/multilingual-e5-large')
input_texts = [
'query: how much protein should a female eat',
'query: 南瓜的家常做法',
"passage: As a general guideline, the CDC's average requirement of protein for women ages 19 to 70 i s 46 grams per day. But, as you can see from this chart, you'll need to increase that if you're expecting or traini ng for a marathon. Check out the chart below to see how much protein you should be eating each day.",
"passage: 1.清炒南瓜丝 原料:嫩南瓜半个 调料:葱、盐、白糖、鸡精 做法: 1、南瓜用刀薄薄的削去表面一层皮 ,用勺子刮去瓤 2、擦成细丝(没有擦菜板就用刀慢慢切成细丝) 3、锅烧热放油,入葱花煸出香味 4、入南瓜丝快速翻炒一分钟左右, 放盐、一点白糖和鸡精调味出锅 2.香葱炒南瓜 原料:南瓜1只 调料:香葱、蒜末、橄榄油、盐 做法: 1、将南瓜去皮,切成片 2、油 锅8成热后,将蒜末放入爆香 3、爆香后,将南瓜片放入,翻炒 4、在翻炒的同时,可以不时地往锅里加水,但不要太多 5、放入盐,炒匀 6、南瓜差不多软和绵了之后,就可以关火 7、撒入香葱,即可出锅"
]
embeddings = model.encode(input_texts, normalize_embeddings=True)
print(f"embeddings:{embeddings}")
\ No newline at end of file
# SPDX-License-Identifier: Apache-2.0
from argparse import Namespace
import os
import numpy as np
from vllm import LLM, EngineArgs
from vllm.utils import FlexibleArgumentParser
def main(args: Namespace):
prompts = [
"你好,我的名字是",
"美国总统是",
"法国的首都是",
"人工智能的未来是",
]
model = LLM(**vars(args))
outputs = model.embed(prompts)
script_dir = os.path.dirname(os.path.abspath(__file__))
embeddings = [output.outputs.embedding for output in outputs]
output_path = os.path.join(script_dir, 'embeddings_A800.npy')
np.save(output_path, np.array(embeddings))
for i, (prompt, output) in enumerate(zip(prompts, outputs)):
embeds = output.outputs.embedding
embeds_trimmed = ((str(embeds[:16])[:-1] +
", ...]") if len(embeds) > 16 else embeds)
print(f"提示: {prompt!r} | "
f"嵌入: {embeds_trimmed} (大小={len(embeds)})")
print(f"所有嵌入已保存到: {output_path}")
if __name__ == "__main__":
parser = FlexibleArgumentParser()
parser = EngineArgs.add_cli_args(parser)
parser.set_defaults(model="/home/zwq/model/models/multilingual-e5-large/multilingual-e5-large",
task="embed",
enforce_eager=True)
args = parser.parse_args()
main(args)
\ No newline at end of file
# 模型唯一标识
modelCode = 1637
# 模型名称
modelName=multilingual-e5-large_pytorch
# 模型描述
modelDescription=multilingual-e5-large模型是开源的文本嵌入模型,基于多语言MiniLM和XLM-RoBERTa构建,专门为文本嵌入任务而设计。
# 应用场景
appScenario=推理,文本理解,制造,广媒,家居,教育
# 框架类型
frameType=pytorch
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