Skip to content

Commit e41d1fe

Browse files
authored
Merge pull request #56 from MooreThreads/llm_wwx
add m3e_base,bge_reranker
2 parents 29af05d + ac8bf67 commit e41d1fe

File tree

8 files changed

+369
-0
lines changed

8 files changed

+369
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2022 staoxiao
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
0. Start docker
2+
启动命令可参考: [README.md](../../README.md)
3+
4+
1. Prerequisites
5+
```shell
6+
pip install -r requirements.txt
7+
8+
pip install -U huggingface_hub
9+
```
10+
2. export env
11+
```shell
12+
export HF_ENDPOINT=https://hf-mirror.com
13+
```
14+
15+
3. Test
16+
```shell
17+
python bge_reranker_large.py
18+
```
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
from FlagEmbedding import FlagReranker
2+
import time
3+
import numpy as np
4+
import concurrent.futures
5+
import random
6+
import string
7+
8+
# 生成长文本(1024 tokens约1500-1800字符)
9+
def generate_long_text(target_tokens=1024):
10+
words = []
11+
current_tokens = 0
12+
while current_tokens < target_tokens:
13+
word_len = random.randint(3, 10)
14+
words.append(''.join(random.choices(string.ascii_letters, k=word_len)))
15+
current_tokens += 1
16+
return " ".join(words)
17+
18+
def process_batch(reranker, batch_pairs):
19+
"""处理单个批次并返回结果和耗时"""
20+
start_time = time.perf_counter()
21+
scores = reranker.compute_score(batch_pairs)
22+
end_time = time.perf_counter()
23+
return scores, end_time - start_time
24+
25+
def main():
26+
# 加载模型(FP16精度 + MUSA设备加速)
27+
reranker = FlagReranker('BAAI/bge-reranker-large',
28+
use_fp16=True,
29+
device="musa")
30+
31+
# ===== 长文本优化:生成1024 tokens的输入 =====
32+
print("=== Generating 1024-token texts ===")
33+
long_query = generate_long_text(1024)
34+
long_passage = generate_long_text(1024)
35+
36+
# ===== 关键优化:添加模型预热(使用长文本)===== [1,6](@ref)
37+
print("=== Starting model warm-up with long texts ===")
38+
warmup_pairs = [[long_query, long_passage]] * 16
39+
for _ in range(5):
40+
reranker.compute_score(warmup_pairs)
41+
print("=== Warm-up completed ===\n")
42+
43+
# 单次长文本推理测试
44+
start_time = time.perf_counter()
45+
score = reranker.compute_score([long_query, long_passage])
46+
latency = (time.perf_counter() - start_time) * 1000
47+
print(f"Long text score: {str(score)} | Latency: {latency:.2f} ms")
48+
49+
# 准备批量数据(30个并行任务)
50+
batch_pairs_list = []
51+
for _ in range(30):
52+
pairs = []
53+
for _ in range(64): # 每个任务64个样本
54+
q = generate_long_text(1024) if random.random() > 0.5 else long_query
55+
p = generate_long_text(1024) if random.random() > 0.5 else long_passage
56+
pairs.append([q, p])
57+
batch_pairs_list.append(pairs)
58+
59+
# ===== 并行执行30个任务 =====
60+
print("\n=== Starting 30 parallel batch processing ===")
61+
total_tokens = sum(
62+
sum(len(q.split()) + len(p.split()) for q, p in pairs)
63+
for pairs in batch_pairs_list
64+
)
65+
batch_times = []
66+
start_time = time.perf_counter()
67+
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor: # 控制并发数
68+
futures = [executor.submit(process_batch, reranker, pairs) for pairs in batch_pairs_list]
69+
70+
batch_results = []
71+
for future in concurrent.futures.as_completed(futures):
72+
scores, batch_time = future.result()
73+
batch_results.append(scores)
74+
batch_times.append(batch_time)
75+
76+
total_time = time.perf_counter() - start_time
77+
78+
# 性能统计
79+
total_pairs = 30 * 64 # 30任务 * 每任务64对
80+
throughput_pairs = total_pairs / total_time
81+
throughput_tokens = total_tokens / total_time
82+
83+
avg_batch_time = sum(batch_times) / len(batch_times)
84+
max_batch_time = max(batch_times)
85+
min_batch_time = min(batch_times)
86+
87+
print("\n===== Performance Report =====")
88+
print(f"Total batches processed: {len(batch_results)}")
89+
print(f"Total pairs processed: {total_pairs}")
90+
print(f"Total tokens processed: {total_tokens}")
91+
print(f"Total processing time: {total_time:.2f} seconds")
92+
93+
print("\n--- Throughput ---")
94+
print(f"Throughput: {throughput_pairs:.2f} pairs/sec")
95+
print(f"Token throughput: {throughput_tokens:.2f} tokens/sec")
96+
97+
print("\n--- Latency ---")
98+
print(f"Average batch time: {avg_batch_time:.4f} sec")
99+
print(f"Max batch time: {max_batch_time:.4f} sec")
100+
print(f"Min batch time: {min_batch_time:.4f} sec")
101+
102+
print("=============================")
103+
104+
105+
106+
if __name__ == "__main__":
107+
main()
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
FlagEmbedding
2+
accelerate==1.0.1
3+
transformers==4.44.0
4+
peft
5+

pytorch/Embedding/m3e_base/LICENSE

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
Licensed under the Apache License 2.0
2+
3+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
4+
5+
1. Definitions.
6+
“License” shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
7+
8+
“Licensor” shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
9+
10+
“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.
11+
12+
“You” (or “Your”) shall mean an individual or Legal Entity exercising permissions granted by this License.
13+
14+
“Source” form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
15+
16+
“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.
17+
18+
“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).
19+
20+
“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.
21+
22+
“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.”
23+
24+
“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.
25+
26+
2. Grant of Copyright License.
27+
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.
28+
29+
3. Grant of Patent License.
30+
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.
31+
32+
4. Redistribution.
33+
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:
34+
35+
You must give any other recipients of the Work or Derivative Works a copy of this License; and
36+
You must cause any modified files to carry prominent notices stating that You changed the files; and
37+
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
38+
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.
39+
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.
40+
41+
5. Submission of Contributions.
42+
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.
43+
44+
6. Trademarks.
45+
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.
46+
47+
7. Disclaimer of Warranty.
48+
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.
49+
50+
8. Limitation of Liability.
51+
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.
52+
53+
9. Accepting Warranty or Additional Liability.
54+
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.
55+
56+
END OF TERMS AND CONDITIONS
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
0. Start docker
2+
启动命令可参考: [README.md](../../README.md)
3+
4+
1. Prerequisites
5+
```shell
6+
pip install -r requirements.txt
7+
8+
pip install -U huggingface_hub
9+
```
10+
2. export env
11+
```shell
12+
export HF_ENDPOINT=https://hf-mirror.com
13+
```
14+
15+
3. Test
16+
```shell
17+
python perf_m3e_base.py
18+
```
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
import time
2+
import concurrent.futures
3+
import numpy as np
4+
import torch
5+
import torch_musa
6+
from sentence_transformers import SentenceTransformer
7+
from tqdm import tqdm
8+
9+
# 生成长文本(1024 tokens约1500-1800字符)
10+
def generate_long_text(target_tokens=1024):
11+
"""生成符合目标token长度的随机文本"""
12+
import random
13+
import string
14+
15+
words = []
16+
current_tokens = 0
17+
while current_tokens < target_tokens:
18+
word_len = random.randint(3, 10)
19+
words.append(''.join(random.choices(string.ascii_letters, k=word_len)))
20+
current_tokens += 1
21+
return " ".join(words)
22+
23+
def process_batch(model, sentences, batch_size=32):
24+
"""处理单个批次并返回结果和耗时"""
25+
start_time = time.perf_counter()
26+
embeddings = model.encode(
27+
sentences,
28+
batch_size=batch_size,
29+
convert_to_numpy=True,
30+
show_progress_bar=False
31+
)
32+
end_time = time.perf_counter()
33+
return embeddings, end_time - start_time
34+
35+
def count_tokens(texts):
36+
"""近似计算token数量(实际应使用tokenizer)"""
37+
return sum(len(text.split()) for text in texts)
38+
39+
def main():
40+
# 初始化模型(使用MUSA设备加速)
41+
model = SentenceTransformer('moka-ai/m3e-base', device='musa')
42+
43+
# ===== 长文本优化:生成1024 tokens的输入 =====
44+
print("=== Generating 1024-token texts ===")
45+
long_text = generate_long_text(1024)
46+
47+
# ===== 关键优化:添加长文本模型预热 =====
48+
print("\n=== Starting model warm-up with long texts ===")
49+
warmup_sentences = [long_text] * 5 # 使用长文本预热
50+
for _ in range(10):
51+
model.encode(
52+
warmup_sentences,
53+
batch_size=32,
54+
convert_to_numpy=True,
55+
show_progress_bar=False
56+
)
57+
print("=== Warm-up completed ===\n")
58+
59+
# ===== 准备30个并行任务 =====
60+
num_tasks = 30
61+
batch_size = 32
62+
batches = []
63+
64+
# 生成30个批次的输入数据(每个批次包含batch_size个句子)
65+
for _ in range(num_tasks):
66+
sentences_batch = []
67+
for _ in range(batch_size):
68+
# 50%概率使用长文本,50%生成新文本
69+
if np.random.rand() > 0.5:
70+
sentences_batch.append(long_text)
71+
else:
72+
sentences_batch.append(generate_long_text(1024))
73+
batches.append(sentences_batch)
74+
75+
# 计算总token数
76+
total_tokens = sum(count_tokens(batch) for batch in batches)
77+
total_sentences = num_tasks * batch_size
78+
79+
# ===== 并行执行30个任务 =====
80+
print(f"=== Starting {num_tasks} parallel batch processing ===")
81+
start_time = time.perf_counter()
82+
83+
# 记录GPU初始状态
84+
initial_mem = torch_musa.memory_allocated()
85+
86+
# 使用线程池并行处理
87+
batch_results = []
88+
batch_times = []
89+
90+
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as executor:
91+
futures = [executor.submit(process_batch, model, batch, batch_size)
92+
for batch in batches]
93+
94+
# 使用tqdm显示进度条
95+
for future in tqdm(concurrent.futures.as_completed(futures),
96+
total=len(futures), desc="Processing batches"):
97+
embeddings, batch_time = future.result()
98+
batch_results.append(embeddings)
99+
batch_times.append(batch_time)
100+
101+
end_time = time.perf_counter()
102+
total_time = end_time - start_time
103+
104+
# ===== 性能指标计算 =====
105+
# 1. 吞吐量指标
106+
throughput_batches = len(batch_results) / total_time
107+
throughput_sentences = total_sentences / total_time
108+
throughput_tokens = total_tokens / total_time
109+
110+
# 2. 延迟指标
111+
avg_batch_time = sum(batch_times) / len(batch_times)
112+
max_batch_time = max(batch_times)
113+
min_batch_time = min(batch_times)
114+
115+
116+
# ===== 性能报告 =====
117+
print("\n===== Performance Report =====")
118+
print(f"Total batches processed: {len(batch_results)}")
119+
print(f"Total sentences processed: {total_sentences}")
120+
print(f"Total tokens processed: {total_tokens}")
121+
print(f"Total processing time: {total_time:.2f} seconds")
122+
123+
print("\n--- Throughput ---")
124+
print(f"Throughput (batches/sec): {throughput_batches:.2f}")
125+
print(f"Throughput (sentences/sec): {throughput_sentences:.2f}")
126+
print(f"Throughput (tokens/sec): {throughput_tokens:.2f}")
127+
128+
print("\n--- Latency ---")
129+
print(f"Average batch time: {avg_batch_time:.4f} sec")
130+
print(f"Max batch time: {max_batch_time:.4f} sec")
131+
print(f"Min batch time: {min_batch_time:.4f} sec")
132+
133+
print("=============================")
134+
135+
# 打印第一个批次的第一个句子嵌入示例
136+
print("\nSample embedding (first sentence of first batch):")
137+
print(batch_results[0][0][:10]) # 只打印前10维
138+
139+
if __name__ == "__main__":
140+
main()
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
accelerate==1.0.1
2+
transformers==4.44.0
3+
peft
4+

0 commit comments

Comments
 (0)