Views
No views yet
1from transformers import AutoConfig, AutoProcessor, GenerationConfig
2import onnxruntime as ort
3import numpy as np
4from huggingface_hub import snapshot_download
5
6# 1. Load config, processor, and model
7model_id = "onnx-community/LightOnOCR-2-1B-ONNX"
8config = AutoConfig.from_pretrained(model_id)
9processor = AutoProcessor.from_pretrained(model_id)
10generation_config = GenerationConfig.from_pretrained(model_id)
11
12vision_model = "onnx/vision_encoder_q4.onnx"
13embed_model = "onnx/embed_tokens_q4.onnx"
14decoder_model = "onnx/decoder_model_merged_q4.onnx"
15
16folder_path = snapshot_download(
17 repo_id=model_id,
18 allow_patterns=[f"{vision_model}*", f"{embed_model}*", f"{decoder_model}*"],
19)
20vision_model_path = f"{folder_path}/{vision_model}"
21embed_model_path = f"{folder_path}/{embed_model}"
22decoder_model_path = f"{folder_path}/{decoder_model}"
23
24## Load sessions
25providers = ['CPUExecutionProvider']
26vision_session = ort.InferenceSession(vision_model_path, providers=providers)
27embed_session = ort.InferenceSession(embed_model_path, providers=providers)
28decoder_session = ort.InferenceSession(decoder_model_path, providers=providers)
29
30## Set config values
31text_config = config.text_config
32hidden_size = text_config.hidden_size
33
34num_key_value_heads = text_config.num_key_value_heads
35head_dim = text_config.head_dim
36num_hidden_layers = text_config.num_hidden_layers
37eos_token_id = generation_config.eos_token_id
38image_token_id = config.image_token_id
39
40# 2. Prepare inputs
41url = "https://huggingface.co/datasets/hf-internal-testing/fixtures_ocr/resolve/main/SROIE-receipt.jpeg"
42messages = [{"role": "user", "content": [{"type": "image", "url": url}]}]
43inputs = processor.apply_chat_template(
44 messages,
45 add_generation_prompt=True,
46 return_tensors="pt",
47 return_dict=True,
48 tokenize=True,
49)
50
51input_ids = inputs['input_ids'].numpy()
52attention_mask = inputs['attention_mask'].numpy()
53has_vision_inputs = 'pixel_values' in inputs
54pixel_values = inputs['pixel_values'].numpy() if has_vision_inputs else None
55
56batch_size = input_ids.shape[0]
57past_cache_values = {}
58for i in range(num_hidden_layers):
59 for kv in ('key', 'value'):
60 past_cache_values[f'past_key_values.{i}.{kv}'] = np.zeros([batch_size, num_key_value_heads, 0, head_dim], dtype=np.float32)
61
62# 3. Generation loop
63max_new_tokens = 1024
64generated_tokens = np.array([[]], dtype=np.int64)
65image_features = None
66for i in range(max_new_tokens):
67 inputs_embeds = embed_session.run(None, {'input_ids': input_ids})[0]
68
69 if has_vision_inputs and image_features is None:
70 ## Only compute vision features if not already computed
71 image_features = vision_session.run(None, dict(
72 pixel_values=pixel_values,
73 ))[0]
74
75 ## Merge text and vision embeddings
76 inputs_embeds[input_ids == image_token_id] = image_features.reshape(-1, image_features.shape[-1])
77
78 logits, *present_cache_values = decoder_session.run(None, dict(
79 inputs_embeds=inputs_embeds,
80 attention_mask=attention_mask,
81 **past_cache_values,
82 ))
83
84 ## Update values for next generation loop
85 input_ids = logits[:, -1].argmax(-1, keepdims=True)
86 attention_mask = np.concatenate([attention_mask, np.ones((batch_size, 1), dtype=attention_mask.dtype)], axis=-1)
87 for j, key in enumerate(past_cache_values):
88 past_cache_values[key] = present_cache_values[j]
89
90 generated_tokens = np.concatenate([generated_tokens, input_ids], axis=-1)
91 if np.isin(input_ids, eos_token_id).any():
92 break
93
94 ## (Optional) Streaming
95 print(processor.decode(input_ids[0], skip_special_tokens=False), end='', flush=True)
96print()
97
98# 4. Output result
99print(processor.batch_decode(generated_tokens, skip_special_tokens=True)[0])Document No : TD01167104
Date : 25/12/2018 8:13:39 PM
Cashier : MANIS
Member :
# CASH BILL
<table>
<thead>
<tr>
<th>CODE/DESC</th>
<th>PRICE</th>
<th>Disc</th>
<th>AMOUNT</th>
</tr>
<tr>
<th>QTY</th>
<th>RM</th>
<th></th>
<th>RM</th>
</tr>
</thead>
<tbody>
<tr>
<td>9556939040118</td>
<td>KF MODELLING CLAY KIDDY FISH</td>
<td></td>
<td></td>
</tr>
<tr>
<td>1 PC *</td>
<td>9.000</td>
<td>0.00</td>
<td>9.00</td>
</tr>
<tr>
<td colspan="3">Total :</td>
<td>9.00</td>
</tr>
<tr>
<td colspan="3">Rounding Adjustment :</td>
<td>0.00</td>
</tr>
<tr>
<td colspan="3">Rounded Total (RM):</td>
<td>9.00</td>
</tr>
</tbody>
</table>