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7 |
+
### ONNXRuntime
|
| 8 |
+
|
| 9 |
+
```py
|
| 10 |
+
from transformers import AutoConfig, AutoTokenizer
|
| 11 |
+
import onnxruntime
|
| 12 |
+
import numpy as np
|
| 13 |
+
|
| 14 |
+
# 1. Load config, processor, and model
|
| 15 |
+
path_to_model = "./gemma-3-1b-it-ONNX"
|
| 16 |
+
config = AutoConfig.from_pretrained(path_to_model)
|
| 17 |
+
tokenizer = AutoTokenizer.from_pretrained(path_to_model)
|
| 18 |
+
decoder_session = onnxruntime.InferenceSession(f"{path_to_model}/onnx/model.onnx")
|
| 19 |
+
|
| 20 |
+
## Set config values
|
| 21 |
+
num_key_value_heads = config.num_key_value_heads
|
| 22 |
+
head_dim = config.head_dim
|
| 23 |
+
num_hidden_layers = config.num_hidden_layers
|
| 24 |
+
eos_token_id = 106 # 106 is for <end_of_turn>
|
| 25 |
+
|
| 26 |
+
# 2. Prepare inputs
|
| 27 |
+
## Create input messages
|
| 28 |
+
messages = [
|
| 29 |
+
{ "role": "system", "content": "You are a helpful assistant." },
|
| 30 |
+
{ "role": "user", "content": "Write me a poem about Machine Learning." },
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
## Apply tokenizer
|
| 34 |
+
inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="np")
|
| 35 |
+
|
| 36 |
+
## Prepare decoder inputs
|
| 37 |
+
batch_size = inputs['input_ids'].shape[0]
|
| 38 |
+
past_key_values = {
|
| 39 |
+
f'past_key_values.{layer}.{kv}': np.zeros([batch_size, num_key_value_heads, 0, head_dim], dtype=np.float32)
|
| 40 |
+
for layer in range(num_hidden_layers)
|
| 41 |
+
for kv in ('key', 'value')
|
| 42 |
+
}
|
| 43 |
+
input_ids = inputs['input_ids']
|
| 44 |
+
attention_mask = inputs['attention_mask']
|
| 45 |
+
position_ids = np.cumsum(inputs['attention_mask'], axis=-1) + 1
|
| 46 |
+
|
| 47 |
+
# 3. Generation loop
|
| 48 |
+
max_new_tokens = 1024
|
| 49 |
+
generated_tokens = np.array([[]], dtype=np.int64)
|
| 50 |
+
for i in range(max_new_tokens):
|
| 51 |
+
logits, *present_key_values = decoder_session.run(None, dict(
|
| 52 |
+
input_ids=input_ids,
|
| 53 |
+
attention_mask=attention_mask,
|
| 54 |
+
position_ids=position_ids,
|
| 55 |
+
**past_key_values,
|
| 56 |
+
))
|
| 57 |
+
|
| 58 |
+
## Update values for next generation loop
|
| 59 |
+
input_ids = logits[:, -1].argmax(-1, keepdims=True)
|
| 60 |
+
attention_mask = np.ones_like(input_ids)
|
| 61 |
+
position_ids = position_ids[:, -1:] + 1
|
| 62 |
+
for j, key in enumerate(past_key_values):
|
| 63 |
+
past_key_values[key] = present_key_values[j]
|
| 64 |
+
|
| 65 |
+
generated_tokens = np.concatenate([generated_tokens, input_ids], axis=-1)
|
| 66 |
+
if (input_ids == eos_token_id).all():
|
| 67 |
+
break
|
| 68 |
+
|
| 69 |
+
## (Optional) Streaming
|
| 70 |
+
print(tokenizer.decode(input_ids[0]), end='', flush=True)
|
| 71 |
+
print()
|
| 72 |
+
|
| 73 |
+
# 4. Output result
|
| 74 |
+
print(tokenizer.batch_decode(generated_tokens))
|
| 75 |
+
```
|
| 76 |
+
|
| 77 |
+
<details>
|
| 78 |
+
<summary>See example output</summary>
|
| 79 |
+
|
| 80 |
+
```
|
| 81 |
+
Okay, here’s a poem about Machine Learning, aiming for a balance of technical and evocative language:
|
| 82 |
+
|
| 83 |
+
**The Silent Learner**
|
| 84 |
+
|
| 85 |
+
The data streams, a boundless flow,
|
| 86 |
+
A river vast, where patterns grow.
|
| 87 |
+
No human hand to guide the way,
|
| 88 |
+
Just algorithms, come what may.
|
| 89 |
+
|
| 90 |
+
Machine Learning, a subtle art,
|
| 91 |
+
To teach a system, a brand new start.
|
| 92 |
+
With weights and biases, finely tuned,
|
| 93 |
+
It seeks the truth, beneath the moon.
|
| 94 |
+
|
| 95 |
+
It learns from errors, big and small,
|
| 96 |
+
Adjusting swiftly, standing tall.
|
| 97 |
+
From pixels bright to voices clear,
|
| 98 |
+
It builds a model, banishing fear.
|
| 99 |
+
|
| 100 |
+
Of blind prediction, cold and stark,
|
| 101 |
+
It finds the meaning, leaves its mark.
|
| 102 |
+
A network deep, a complex grace,
|
| 103 |
+
Discovering insights, time and space.
|
| 104 |
+
|
| 105 |
+
It sees the trends, the subtle hue,
|
| 106 |
+
Predicting futures, fresh and new.
|
| 107 |
+
A silent learner, ever keen,
|
| 108 |
+
A digital mind, unseen, serene.
|
| 109 |
+
|
| 110 |
+
So let the code begin to gleam,
|
| 111 |
+
A blossoming of a learning dream.
|
| 112 |
+
Machine Learning, a wondrous sight,
|
| 113 |
+
Shaping the future, shining bright.
|
| 114 |
+
|
| 115 |
+
---
|
| 116 |
+
|
| 117 |
+
Would you like me to:
|
| 118 |
+
|
| 119 |
+
* Adjust the tone or style? (e.g., more technical, more metaphorical)
|
| 120 |
+
* Focus on a specific aspect of ML (e.g., neural networks, data analysis)?
|
| 121 |
+
* Create a different length or format?
|
| 122 |
+
```
|
| 123 |
+
|
| 124 |
+
</details>
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
### Transformers.js
|
| 129 |
+
```js
|
| 130 |
+
import { pipeline } from "@huggingface/transformers";
|
| 131 |
+
|
| 132 |
+
// Create a text generation pipeline
|
| 133 |
+
const generator = await pipeline(
|
| 134 |
+
"text-generation",
|
| 135 |
+
"onnx-community/gemma-3-1b-it-ONNX",
|
| 136 |
+
{ dtype: "q4" },
|
| 137 |
+
);
|
| 138 |
+
|
| 139 |
+
// Define the list of messages
|
| 140 |
+
const messages = [
|
| 141 |
+
{ role: "system", content: "You are a helpful assistant." },
|
| 142 |
+
{ role: "user", content: "Write me a poem about Machine Learning." },
|
| 143 |
+
];
|
| 144 |
+
|
| 145 |
+
// Generate a response
|
| 146 |
+
const output = await generator(messages, { max_new_tokens: 512, do_sample: false });
|
| 147 |
+
console.log(output[0].generated_text.at(-1).content);
|
| 148 |
+
```
|
| 149 |
+
|