Upload 8 files
Browse files- README.md +64 -3
- config.json +24 -0
- special_tokens_map.json +7 -0
- tf_model.h5 +3 -0
- to_onnx.py +176 -0
- tokenizer.json +0 -0
- tokenizer_config.json +56 -0
- vocab.txt +0 -0
README.md
CHANGED
@@ -1,3 +1,64 @@
|
|
1 |
-
---
|
2 |
-
|
3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
library_name: transformers
|
3 |
+
license: apache-2.0
|
4 |
+
base_model: distilbert/distilbert-base-cased-distilled-squad
|
5 |
+
tags:
|
6 |
+
- generated_from_keras_callback
|
7 |
+
model-index:
|
8 |
+
- name: Docty/question_and_answer
|
9 |
+
results: []
|
10 |
+
---
|
11 |
+
|
12 |
+
<!-- This model card has been generated automatically according to the information Keras had access to. You should
|
13 |
+
probably proofread and complete it, then remove this comment. -->
|
14 |
+
|
15 |
+
# Docty/question_and_answer
|
16 |
+
|
17 |
+
This model is a fine-tuned version of [distilbert/distilbert-base-cased-distilled-squad](https://huggingface.co/distilbert/distilbert-base-cased-distilled-squad) on an unknown dataset.
|
18 |
+
It achieves the following results on the evaluation set:
|
19 |
+
- Train Loss: 0.4095
|
20 |
+
- Validation Loss: 0.6306
|
21 |
+
- Epoch: 9
|
22 |
+
|
23 |
+
## Model description
|
24 |
+
|
25 |
+
More information needed
|
26 |
+
|
27 |
+
## Intended uses & limitations
|
28 |
+
|
29 |
+
More information needed
|
30 |
+
|
31 |
+
## Training and evaluation data
|
32 |
+
|
33 |
+
More information needed
|
34 |
+
|
35 |
+
## Training procedure
|
36 |
+
|
37 |
+
### Training hyperparameters
|
38 |
+
|
39 |
+
The following hyperparameters were used during training:
|
40 |
+
- optimizer: {'name': 'Adam', 'weight_decay': None, 'clipnorm': None, 'global_clipnorm': None, 'clipvalue': None, 'use_ema': False, 'ema_momentum': 0.99, 'ema_overwrite_frequency': None, 'jit_compile': True, 'is_legacy_optimizer': False, 'learning_rate': {'module': 'keras.optimizers.schedules', 'class_name': 'PolynomialDecay', 'config': {'initial_learning_rate': 2e-05, 'decay_steps': 200, 'end_learning_rate': 0.0, 'power': 1.0, 'cycle': False, 'name': None}, 'registered_name': None}, 'beta_1': 0.9, 'beta_2': 0.999, 'epsilon': 1e-08, 'amsgrad': False}
|
41 |
+
- training_precision: float32
|
42 |
+
|
43 |
+
### Training results
|
44 |
+
|
45 |
+
| Train Loss | Validation Loss | Epoch |
|
46 |
+
|:----------:|:---------------:|:-----:|
|
47 |
+
| 1.2112 | 0.6667 | 0 |
|
48 |
+
| 0.5043 | 0.6306 | 1 |
|
49 |
+
| 0.4089 | 0.6306 | 2 |
|
50 |
+
| 0.4124 | 0.6306 | 3 |
|
51 |
+
| 0.4204 | 0.6306 | 4 |
|
52 |
+
| 0.4269 | 0.6306 | 5 |
|
53 |
+
| 0.4218 | 0.6306 | 6 |
|
54 |
+
| 0.4031 | 0.6306 | 7 |
|
55 |
+
| 0.4117 | 0.6306 | 8 |
|
56 |
+
| 0.4095 | 0.6306 | 9 |
|
57 |
+
|
58 |
+
|
59 |
+
### Framework versions
|
60 |
+
|
61 |
+
- Transformers 4.47.0
|
62 |
+
- TensorFlow 2.17.1
|
63 |
+
- Datasets 3.2.0
|
64 |
+
- Tokenizers 0.21.0
|
config.json
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "distilbert/distilbert-base-cased-distilled-squad",
|
3 |
+
"activation": "gelu",
|
4 |
+
"architectures": [
|
5 |
+
"DistilBertForQuestionAnswering"
|
6 |
+
],
|
7 |
+
"attention_dropout": 0.1,
|
8 |
+
"dim": 768,
|
9 |
+
"dropout": 0.1,
|
10 |
+
"hidden_dim": 3072,
|
11 |
+
"initializer_range": 0.02,
|
12 |
+
"max_position_embeddings": 512,
|
13 |
+
"model_type": "distilbert",
|
14 |
+
"n_heads": 12,
|
15 |
+
"n_layers": 6,
|
16 |
+
"output_past": true,
|
17 |
+
"pad_token_id": 0,
|
18 |
+
"qa_dropout": 0.1,
|
19 |
+
"seq_classif_dropout": 0.2,
|
20 |
+
"sinusoidal_pos_embds": true,
|
21 |
+
"tie_weights_": true,
|
22 |
+
"transformers_version": "4.47.0",
|
23 |
+
"vocab_size": 28996
|
24 |
+
}
|
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 |
+
}
|
tf_model.h5
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:0e28afe23658cb018f3507106a07f29025ace312df02a44059a4162eed29847f
|
3 |
+
size 260895720
|
to_onnx.py
ADDED
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from transformers import AutoTokenizer, AutoConfig, DistilBertForQuestionAnswering # Correct import
|
3 |
+
import onnx
|
4 |
+
from onnxruntime.quantization import quantize_dynamic, QuantType
|
5 |
+
import os
|
6 |
+
import logging
|
7 |
+
from typing import Optional, Dict, Any
|
8 |
+
|
9 |
+
class ONNXModelConverter:
|
10 |
+
def __init__(self, model_name: str, output_dir: str):
|
11 |
+
self.model_name = model_name
|
12 |
+
self.output_dir = output_dir
|
13 |
+
self.setup_logging()
|
14 |
+
|
15 |
+
os.makedirs(output_dir, exist_ok=True)
|
16 |
+
|
17 |
+
self.logger.info(f"Loading tokenizer {model_name}...")
|
18 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
|
19 |
+
|
20 |
+
self.logger.info(f"Loading model config {model_name}...")
|
21 |
+
config = AutoConfig.from_pretrained(model_name, trust_remote_code=True)
|
22 |
+
|
23 |
+
self.logger.info(f"Loading model {model_name}...")
|
24 |
+
try:
|
25 |
+
self.model = DistilBertForQuestionAnswering.from_pretrained(
|
26 |
+
model_name,
|
27 |
+
config=config,
|
28 |
+
trust_remote_code=True,
|
29 |
+
torch_dtype=torch.float32 # Keep this for consistency, though it might not be strictly necessary
|
30 |
+
)
|
31 |
+
except Exception as e: # Catch the exception if pytorch weights are not found
|
32 |
+
self.logger.info(f"Trying to load tensorflow weights")
|
33 |
+
try:
|
34 |
+
self.model = DistilBertForQuestionAnswering.from_pretrained(
|
35 |
+
model_name,
|
36 |
+
config=config,
|
37 |
+
trust_remote_code=True,
|
38 |
+
from_tf=True # Load from TensorFlow weights
|
39 |
+
)
|
40 |
+
except Exception as e:
|
41 |
+
self.logger.error(f"Failed to load the model: {e}")
|
42 |
+
raise # Re-raise the exception after logging
|
43 |
+
|
44 |
+
self.model.eval()
|
45 |
+
|
46 |
+
def setup_logging(self):
|
47 |
+
self.logger = logging.getLogger(__name__)
|
48 |
+
self.logger.setLevel(logging.INFO)
|
49 |
+
handler = logging.StreamHandler()
|
50 |
+
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
|
51 |
+
handler.setFormatter(formatter)
|
52 |
+
self.logger.addHandler(handler)
|
53 |
+
|
54 |
+
def prepare_dummy_inputs(self):
|
55 |
+
dummy_input = self.tokenizer(
|
56 |
+
"Hello, how are you?",
|
57 |
+
return_tensors="pt",
|
58 |
+
padding=True,
|
59 |
+
truncation=True,
|
60 |
+
max_length=128
|
61 |
+
)
|
62 |
+
dummy_input.pop('token_type_ids', None)
|
63 |
+
return {
|
64 |
+
'input_ids': dummy_input['input_ids'],
|
65 |
+
'attention_mask': dummy_input['attention_mask'],
|
66 |
+
}
|
67 |
+
|
68 |
+
def export_to_onnx(self):
|
69 |
+
output_path = os.path.join(self.output_dir, "model.onnx")
|
70 |
+
inputs = self.prepare_dummy_inputs()
|
71 |
+
|
72 |
+
dynamic_axes = {
|
73 |
+
'input_ids': {0: 'batch_size', 1: 'sequence_length'},
|
74 |
+
'attention_mask': {0: 'batch_size', 1: 'sequence_length'},
|
75 |
+
'start_logits': {0: 'batch_size', 1: 'sequence_length'},
|
76 |
+
'end_logits': {0: 'batch_size', 1: 'sequence_length'},
|
77 |
+
}
|
78 |
+
|
79 |
+
class ModelWrapper(torch.nn.Module):
|
80 |
+
def __init__(self, model):
|
81 |
+
super().__init__()
|
82 |
+
self.model = model
|
83 |
+
|
84 |
+
def forward(self, input_ids, attention_mask):
|
85 |
+
outputs = self.model(input_ids=input_ids, attention_mask=attention_mask)
|
86 |
+
return outputs.start_logits, outputs.end_logits
|
87 |
+
|
88 |
+
wrapped_model = ModelWrapper(self.model)
|
89 |
+
|
90 |
+
try:
|
91 |
+
torch.onnx.export(
|
92 |
+
wrapped_model,
|
93 |
+
(inputs['input_ids'], inputs['attention_mask']),
|
94 |
+
output_path,
|
95 |
+
export_params=True,
|
96 |
+
opset_version=14, # Or a suitable version
|
97 |
+
do_constant_folding=True,
|
98 |
+
input_names=['input_ids', 'attention_mask'],
|
99 |
+
output_names=['start_logits', 'end_logits'],
|
100 |
+
dynamic_axes=dynamic_axes,
|
101 |
+
verbose=False
|
102 |
+
)
|
103 |
+
self.logger.info(f"Model exported to {output_path}")
|
104 |
+
return output_path
|
105 |
+
except Exception as e:
|
106 |
+
self.logger.error(f"ONNX export failed: {str(e)}")
|
107 |
+
raise
|
108 |
+
|
109 |
+
def verify_model(self, model_path: str):
|
110 |
+
try:
|
111 |
+
onnx_model = onnx.load(model_path)
|
112 |
+
onnx.checker.check_model(onnx_model)
|
113 |
+
self.logger.info("ONNX model verification successful")
|
114 |
+
return True
|
115 |
+
except Exception as e:
|
116 |
+
self.logger.error(f"Model verification failed: {str(e)}")
|
117 |
+
return False
|
118 |
+
|
119 |
+
def quantize_model(self, model_path: str):
|
120 |
+
weight_types = {'int4':QuantType.QInt4, 'int8':QuantType.QInt8, 'uint4':QuantType.QUInt4, 'uint8':QuantType.QUInt8, 'uint16':QuantType.QUInt16, 'int16':QuantType.QInt16}
|
121 |
+
all_quantized_paths = []
|
122 |
+
for weight_type in weight_types.keys():
|
123 |
+
quantized_path = os.path.join(self.output_dir, "model_" + weight_type + ".onnx")
|
124 |
+
|
125 |
+
try:
|
126 |
+
quantize_dynamic(
|
127 |
+
model_path,
|
128 |
+
quantized_path,
|
129 |
+
weight_type=weight_types[weight_type]
|
130 |
+
)
|
131 |
+
self.logger.info(f"Model quantized ({weight_type}) and saved to {quantized_path}")
|
132 |
+
all_quantized_paths.append(quantized_path)
|
133 |
+
except Exception as e:
|
134 |
+
self.logger.error(f"Quantization ({weight_type}) failed: {str(e)}")
|
135 |
+
raise
|
136 |
+
|
137 |
+
return all_quantized_paths
|
138 |
+
|
139 |
+
def convert(self):
|
140 |
+
try:
|
141 |
+
onnx_path = self.export_to_onnx()
|
142 |
+
|
143 |
+
if self.verify_model(onnx_path):
|
144 |
+
quantized_paths = self.quantize_model(onnx_path)
|
145 |
+
|
146 |
+
tokenizer_path = os.path.join(self.output_dir, "tokenizer")
|
147 |
+
self.tokenizer.save_pretrained(tokenizer_path)
|
148 |
+
self.logger.info(f"Tokenizer saved to {tokenizer_path}")
|
149 |
+
|
150 |
+
return {
|
151 |
+
'onnx_model': onnx_path,
|
152 |
+
'quantized_models': quantized_paths,
|
153 |
+
'tokenizer': tokenizer_path
|
154 |
+
}
|
155 |
+
else:
|
156 |
+
raise Exception("Model verification failed")
|
157 |
+
|
158 |
+
except Exception as e:
|
159 |
+
self.logger.error(f"Conversion process failed: {str(e)}")
|
160 |
+
raise
|
161 |
+
|
162 |
+
if __name__ == "__main__":
|
163 |
+
MODEL_NAME = "Docty/question_and_answer" # Or any other suitable model
|
164 |
+
OUTPUT_DIR = "onnx"
|
165 |
+
|
166 |
+
try:
|
167 |
+
converter = ONNXModelConverter(MODEL_NAME, OUTPUT_DIR)
|
168 |
+
results = converter.convert()
|
169 |
+
|
170 |
+
print("\nConversion completed successfully!")
|
171 |
+
print(f"ONNX model path: {results['onnx_model']}")
|
172 |
+
print(f"Quantized model paths: {results['quantized_models']}")
|
173 |
+
print(f"Tokenizer path: {results['tokenizer']}")
|
174 |
+
|
175 |
+
except Exception as e:
|
176 |
+
print(f"Conversion failed: {str(e)}")
|
tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
tokenizer_config.json
ADDED
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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": false,
|
45 |
+
"cls_token": "[CLS]",
|
46 |
+
"do_lower_case": false,
|
47 |
+
"extra_special_tokens": {},
|
48 |
+
"mask_token": "[MASK]",
|
49 |
+
"model_max_length": 512,
|
50 |
+
"pad_token": "[PAD]",
|
51 |
+
"sep_token": "[SEP]",
|
52 |
+
"strip_accents": null,
|
53 |
+
"tokenize_chinese_chars": true,
|
54 |
+
"tokenizer_class": "DistilBertTokenizer",
|
55 |
+
"unk_token": "[UNK]"
|
56 |
+
}
|
vocab.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|