skypro1111 commited on
Commit
9e3acf7
·
verified ·
1 Parent(s): a2aa7c1

Create infer_onnx_hf.py

Browse files
Files changed (1) hide show
  1. onnx/infer_onnx_hf.py +147 -0
onnx/infer_onnx_hf.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import onnxruntime
2
+ import numpy as np
3
+ from transformers import AutoTokenizer
4
+ import time
5
+ import os
6
+ from huggingface_hub import hf_hub_download
7
+
8
+ model_name = "skypro1111/mbart-large-50-verbalization"
9
+
10
+
11
+ def download_model_from_hf(repo_id=model_name, model_dir="onnx_hf"):
12
+ """Download ONNX models from HuggingFace Hub."""
13
+ os.makedirs(model_dir, exist_ok=True)
14
+
15
+ files = ["onnx/encoder_model.onnx", "onnx/decoder_model.onnx", "onnx/decoder_model.onnx_data"]
16
+
17
+ for file in files:
18
+ hf_hub_download(
19
+ repo_id=repo_id,
20
+ filename=file,
21
+ local_dir=model_dir
22
+ )
23
+
24
+ return files
25
+
26
+ def create_onnx_session(model_path, use_gpu=True):
27
+ """Create an ONNX inference session."""
28
+ # Session options
29
+ session_options = onnxruntime.SessionOptions()
30
+ session_options.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_ENABLE_ALL
31
+ session_options.enable_mem_pattern = True
32
+ session_options.enable_mem_reuse = True
33
+ session_options.intra_op_num_threads = 8
34
+ session_options.log_severity_level = 1
35
+
36
+ cuda_provider_options = {
37
+ 'device_id': 0,
38
+ 'arena_extend_strategy': 'kSameAsRequested',
39
+ 'gpu_mem_limit': 0, # 0 means no limit
40
+ 'cudnn_conv_algo_search': 'DEFAULT',
41
+ 'do_copy_in_default_stream': True,
42
+ }
43
+
44
+ print(f"Available providers: {onnxruntime.get_available_providers()}")
45
+ if use_gpu and 'CUDAExecutionProvider' in onnxruntime.get_available_providers():
46
+ providers = [('CUDAExecutionProvider', cuda_provider_options)]
47
+ print("Using CUDA for inference")
48
+ else:
49
+ providers = ['CPUExecutionProvider']
50
+ print("Using CPU for inference")
51
+
52
+ session = onnxruntime.InferenceSession(
53
+ model_path,
54
+ providers=providers,
55
+ sess_options=session_options
56
+ )
57
+
58
+ return session
59
+
60
+ def generate_text(text, tokenizer, encoder_session, decoder_session, max_length=128):
61
+ """Generate text for a single input."""
62
+ # Prepare input
63
+ inputs = tokenizer(text, return_tensors="np", padding=True, truncation=True, max_length=512)
64
+ input_ids = inputs["input_ids"].astype(np.int64)
65
+ attention_mask = inputs["attention_mask"].astype(np.int64)
66
+
67
+ # Run encoder
68
+ encoder_outputs = encoder_session.run(
69
+ output_names=["last_hidden_state"],
70
+ input_feed={
71
+ "input_ids": input_ids,
72
+ "attention_mask": attention_mask,
73
+ }
74
+ )[0]
75
+
76
+ # Initialize decoder input
77
+ decoder_input_ids = np.array([[tokenizer.pad_token_id]], dtype=np.int64)
78
+
79
+ # Generate sequence
80
+ for _ in range(max_length):
81
+ # Run decoder
82
+ decoder_outputs = decoder_session.run(
83
+ output_names=["logits"],
84
+ input_feed={
85
+ "input_ids": decoder_input_ids,
86
+ "encoder_hidden_states": encoder_outputs,
87
+ "encoder_attention_mask": attention_mask,
88
+ }
89
+ )[0]
90
+
91
+ # Get next token
92
+ next_token = decoder_outputs[:, -1:].argmax(axis=-1)
93
+ decoder_input_ids = np.concatenate([decoder_input_ids, next_token], axis=-1)
94
+
95
+ # Check if sequence is complete
96
+ if tokenizer.eos_token_id in decoder_input_ids[0]:
97
+ break
98
+
99
+ # Decode sequence
100
+ output_text = tokenizer.decode(decoder_input_ids[0], skip_special_tokens=True)
101
+ return output_text
102
+
103
+ def main():
104
+ # Print available providers
105
+ print("Available providers:", onnxruntime.get_available_providers())
106
+
107
+ # Download models from HuggingFace
108
+ print("\nDownloading models from HuggingFace...")
109
+ encoder_path, decoder_path, _ = download_model_from_hf()
110
+
111
+ # Load tokenizer and models
112
+ print("\nLoading tokenizer...")
113
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
114
+ tokenizer.src_lang = "uk_UA"
115
+ tokenizer.tgt_lang = "uk_UA"
116
+
117
+ # Create ONNX sessions
118
+ print("\nLoading encoder...")
119
+ encoder_session = create_onnx_session(encoder_path)
120
+ print("\nLoading decoder...")
121
+ decoder_session = create_onnx_session(decoder_path)
122
+
123
+ # Test examples
124
+ test_inputs = [
125
+ "мій телефон 0979456822",
126
+ "квартира площею 11 тис кв м.",
127
+ "Пропонували хабар у 1 млрд грн.",
128
+ "1 2 3 4 5 6 7 8 9 10.",
129
+ "Крім того, парламентарій володіє шістьма ділянками землі (дві площею 25000 кв м, дві по 15000 кв м та дві по 10000 кв м) розташованими в Сосновій Балці Луганської області.",
130
+ "Підписуючи цей документ у 2003 році, голови Росії та України мали намір зміцнити співпрацю та сприяти розширенню двосторонніх відносин.",
131
+ "Очікується, що цей застосунок буде запущено 22.08.2025.",
132
+ "За інформацією від Державної служби з надзвичайних ситуацій станом на 7 ранку 15 липня.",
133
+ ]
134
+
135
+ print("\nWarming up...")
136
+ _ = generate_text(test_inputs[0], tokenizer, encoder_session, decoder_session)
137
+
138
+ print("\nRunning inference...")
139
+ for text in test_inputs:
140
+ print(f"\nInput: {text}")
141
+ t = time.time()
142
+ output = generate_text(text, tokenizer, encoder_session, decoder_session)
143
+ print(f"Output: {output}")
144
+ print(f"Time: {time.time() - t:.2f} seconds")
145
+
146
+ if __name__ == "__main__":
147
+ main()