FireRedTeam commited on
Commit
614e9c1
·
verified ·
1 Parent(s): bdadfa2

Upload folder using huggingface_hub

Browse files
README.md CHANGED
@@ -1,3 +1,10 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: "apache-2.0"
3
+ ---
4
+ ### fireredchat-turn-detector
5
+
6
+ chinese_best_model_q8.onnx: FireRedChat turn-detector model (Chinese only)
7
+ multilingual_best_model_q8.onnx: FireRedChat turn-detector model (Chinese and English)
8
+
9
+ ### Acknowledgment
10
+ Base model: google-bert/bert-base-multilingual-cased (license: "apache-2.0")
chinese_best_model_q8.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e0738b2d2f8cf17ee75fc8ac8a36f2b0a9dcb29f288387df4ab7554f0c3f6317
3
+ size 178152957
inference_onnx.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import os
3
+ import json
4
+ import logging
5
+ from typing import List, Dict, Tuple, Optional
6
+
7
+ import time
8
+ import numpy as np
9
+ from tqdm import tqdm
10
+ import onnxruntime as ort
11
+ from transformers import AutoTokenizer
12
+
13
+ class StopJudgmentONNXInference:
14
+ def __init__(self, onnx_model_path: str, tokenizer_path: str, device: str = 'auto'):
15
+ """
16
+ 判停模型ONNX推理类
17
+
18
+ Args:
19
+ onnx_model_path: ONNX模型路径
20
+ tokenizer_path: tokenizer路径
21
+ device: 设备类型 ('auto', 'cuda', 'cpu')
22
+ """
23
+ self.onnx_model_path = onnx_model_path
24
+ self.tokenizer_path = tokenizer_path
25
+ self.setup_logging()
26
+ self.load_model_and_tokenizer()
27
+
28
+ def setup_logging(self):
29
+ """设置日志"""
30
+ logging.basicConfig(
31
+ level=logging.INFO,
32
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
33
+ )
34
+ self.logger = logging.getLogger(__name__)
35
+
36
+ def load_model_and_tokenizer(self):
37
+ """加载ONNX模型和tokenizer"""
38
+ # 加载tokenizer
39
+ try:
40
+ self.tokenizer = AutoTokenizer.from_pretrained(self.tokenizer_path, local_files_only=True)
41
+ self.logger.info("Tokenizer loaded successfully")
42
+ except Exception as e:
43
+ self.logger.error(f"Failed to load tokenizer: {e}")
44
+ raise
45
+
46
+ # 修复providers配置
47
+ providers = []
48
+
49
+ # 检查CUDA是否可用
50
+ available_providers = ort.get_available_providers()
51
+ if 'CUDAExecutionProvider' in available_providers:
52
+ providers.append('CUDAExecutionProvider')
53
+ self.logger.info("CUDA provider is available and will be used")
54
+
55
+ providers.append('CPUExecutionProvider') # 始终添加CPU作为备选
56
+
57
+ try:
58
+ self.ort_session = ort.InferenceSession(self.onnx_model_path, providers=providers)
59
+ self.logger.info(f"ONNX model loaded successfully with providers: {self.ort_session.get_providers()}")
60
+ except Exception as e:
61
+ self.logger.error(f"Failed to load ONNX model: {e}")
62
+ raise
63
+
64
+ # 获取输入输出信息
65
+ self.input_names = [input.name for input in self.ort_session.get_inputs()]
66
+ self.output_names = [output.name for output in self.ort_session.get_outputs()]
67
+
68
+ self.logger.info(f"Input names: {self.input_names}")
69
+ self.logger.info(f"Output names: {self.output_names}")
70
+
71
+ def preprocess_text(self, texts: List[str], max_length: int = 128) -> Dict[str, np.ndarray]:
72
+ """
73
+ 预处理文本数据
74
+
75
+ Args:
76
+ texts: 文本列表
77
+ max_length: 最大长度
78
+
79
+ Returns:
80
+ 包含input_ids和attention_mask的字典
81
+ """
82
+ encoding = self.tokenizer(
83
+ texts,
84
+ truncation=True,
85
+ padding='max_length',
86
+ max_length=max_length,
87
+ return_tensors='np' # 返回numpy数组
88
+ )
89
+
90
+ return {
91
+ 'input_ids': encoding['input_ids'].astype(np.int64),
92
+ 'attention_mask': encoding['attention_mask'].astype(np.int64)
93
+ }
94
+
95
+ def predict_single(self, text: str, max_length: int = 128) -> Tuple[int, float]:
96
+ """单个文本预测"""
97
+ inputs = self.preprocess_text([text], max_length)
98
+
99
+ # ONNX推理
100
+ ort_inputs = {
101
+ self.input_names[0]: inputs['input_ids'],
102
+ self.input_names[1]: inputs['attention_mask']
103
+ }
104
+
105
+ ort_outputs = self.ort_session.run(self.output_names, ort_inputs)
106
+ logits = ort_outputs[0]
107
+
108
+ # 计算概率和预测
109
+ probabilities = self.softmax(logits)
110
+ prediction = np.argmax(probabilities[0])
111
+ confidence = probabilities[0][prediction]
112
+
113
+ return int(prediction), float(confidence)
114
+
115
+ def predict_batch(self, texts: List[str], max_length: int = 128,
116
+ batch_size: int = 32) -> Tuple[List[int], List[float]]:
117
+ """批量预测"""
118
+ all_predictions = []
119
+ all_confidences = []
120
+
121
+ for i in tqdm(range(0, len(texts), batch_size), desc="ONNX Predicting"):
122
+ batch_texts = texts[i:i + batch_size]
123
+ inputs = self.preprocess_text(batch_texts, max_length)
124
+
125
+ # ONNX推理
126
+ ort_inputs = {
127
+ self.input_names[0]: inputs['input_ids'],
128
+ self.input_names[1]: inputs['attention_mask']
129
+ }
130
+
131
+ ort_outputs = self.ort_session.run(self.output_names, ort_inputs)
132
+ logits = ort_outputs[0]
133
+
134
+ # 计算概率和预测
135
+ probabilities = self.softmax(logits)
136
+ predictions = np.argmax(probabilities, axis=1)
137
+ confidences = [probabilities[j][pred] for j, pred in enumerate(predictions)]
138
+
139
+ all_predictions.extend(predictions.tolist())
140
+ all_confidences.extend(confidences)
141
+
142
+ return all_predictions, all_confidences
143
+
144
+ @staticmethod
145
+ def softmax(x):
146
+ """Softmax函数"""
147
+ exp_x = np.exp(x - np.max(x, axis=1, keepdims=True))
148
+ return exp_x / np.sum(exp_x, axis=1, keepdims=True)
149
+
150
+ def main():
151
+ """主函数"""
152
+ if len(sys.argv) < 3:
153
+ print("Usage: python validate_onnx.py <tokenizer_path> <onnx_model_path> [test_sentence]")
154
+ sys.exit(1)
155
+
156
+ tokenizer_path = sys.argv[1]
157
+ onnx_model_path = sys.argv[2]
158
+ test_sentence = sys.argv[3] if len(sys.argv) > 3 else "欢迎测试本判停模型有修正建议请随时提出"
159
+
160
+ print("\n ONNX Model Inference...")
161
+ onnx_inferencer = StopJudgmentONNXInference(onnx_model_path, tokenizer_path)
162
+ prediction, confidence = onnx_inferencer.predict_single(
163
+ test_sentence, max_length=128
164
+ )
165
+ print(prediction, confidence)
166
+
167
+ if __name__ == "__main__":
168
+ main()
multilingual_best_model_q8.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:285cafedb0263b065d83964ecc728b795bb281688b0d6525f6c7ca6cb1f756df
3
+ size 178152959
run_chinese.sh ADDED
@@ -0,0 +1 @@
 
 
1
+ python inference_onnx.py tokenizer chinese_best_model_q8.onnx $1
run_multilingual.sh ADDED
@@ -0,0 +1 @@
 
 
1
+ python inference_onnx.py tokenizer multilingual_best_model_q8.onnx $1
tokenizer/config.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "pretrained_models/bert-base-multilingual-cased",
3
+ "architectures": [
4
+ "BertModel"
5
+ ],
6
+ "attention_probs_dropout_prob": 0.1,
7
+ "classifier_dropout": null,
8
+ "directionality": "bidi",
9
+ "hidden_act": "gelu",
10
+ "hidden_dropout_prob": 0.1,
11
+ "hidden_size": 768,
12
+ "initializer_range": 0.02,
13
+ "intermediate_size": 3072,
14
+ "layer_norm_eps": 1e-12,
15
+ "max_position_embeddings": 512,
16
+ "model_type": "bert",
17
+ "num_attention_heads": 12,
18
+ "num_hidden_layers": 12,
19
+ "pad_token_id": 0,
20
+ "pooler_fc_size": 768,
21
+ "pooler_num_attention_heads": 12,
22
+ "pooler_num_fc_layers": 3,
23
+ "pooler_size_per_head": 128,
24
+ "pooler_type": "first_token_transform",
25
+ "position_embedding_type": "absolute",
26
+ "torch_dtype": "float32",
27
+ "transformers_version": "4.40.0",
28
+ "type_vocab_size": 2,
29
+ "use_cache": true,
30
+ "vocab_size": 119547
31
+ }
tokenizer/special_tokens_map.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "[CLS]",
3
+ "mask_token": "[MASK]",
4
+ "pad_token": "[PAD]",
5
+ "sep_token": "[SEP]",
6
+ "unk_token": "[UNK]"
7
+ }
tokenizer/tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer/tokenizer_config.json ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "[PAD]",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "100": {
12
+ "content": "[UNK]",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "101": {
20
+ "content": "[CLS]",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "102": {
28
+ "content": "[SEP]",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "103": {
36
+ "content": "[MASK]",
37
+ "lstrip": false,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "clean_up_tokenization_spaces": true,
45
+ "cls_token": "[CLS]",
46
+ "do_lower_case": false,
47
+ "mask_token": "[MASK]",
48
+ "model_max_length": 512,
49
+ "pad_token": "[PAD]",
50
+ "sep_token": "[SEP]",
51
+ "strip_accents": null,
52
+ "tokenize_chinese_chars": true,
53
+ "tokenizer_class": "BertTokenizer",
54
+ "unk_token": "[UNK]"
55
+ }
tokenizer/vocab.txt ADDED
The diff for this file is too large to render. See raw diff