Add sample code

#4
by Xenova HF Staff - opened
Files changed (1) hide show
  1. README.md +349 -0
README.md CHANGED
@@ -44,6 +44,355 @@ The Ministral 3 3B Instruct model offers the following capabilities:
44
  - **Apache 2.0 License**: Open-source license allowing usage and modification for both commercial and non-commercial purposes.
45
  - **Large Context Window**: Supports a 256k context window.
46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  ## License
48
 
49
  This model is licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0.txt).
 
44
  - **Apache 2.0 License**: Open-source license allowing usage and modification for both commercial and non-commercial purposes.
45
  - **Large Context Window**: Supports a 256k context window.
46
 
47
+
48
+ ## Usage
49
+
50
+
51
+ ### Transformers.js
52
+
53
+ #### Online WebGPU Demo
54
+
55
+ You can test out the model directly in your browser using our online WebGPU demo: https://huggingface.co/spaces/mistralai/Ministral_3B_WebGPU.
56
+
57
+ <video src="https://cdn-uploads.huggingface.co/production/uploads/61b253b7ac5ecaae3d1efe0c/LA0XUsH9pFZaphbfF-HGm.mp4" controls autoplay muted></video>
58
+
59
+ #### JavaScript
60
+
61
+ If you haven't already, you can install the [Transformers.js](https://huggingface.co/docs/transformers.js) JavaScript library from [NPM](https://www.npmjs.com/package/@huggingface/transformers) using:
62
+ ```bash
63
+ npm i @huggingface/transformers
64
+ ```
65
+
66
+ You can then run the model as follows:
67
+ ```js
68
+ import {
69
+ AutoProcessor,
70
+ AutoModelForImageTextToText,
71
+ load_image,
72
+ TextStreamer,
73
+ } from "@huggingface/transformers";
74
+
75
+ // Load processor and model
76
+ const model_id = "mistralai/Ministral-3-3B-Instruct-2512-ONNX";
77
+ const processor = await AutoProcessor.from_pretrained(model_id);
78
+ const model = await AutoModelForImageTextToText.from_pretrained(model_id, {
79
+ device: "webgpu",
80
+ });
81
+
82
+ // Prepare inputs
83
+ const messages = [
84
+ {
85
+ role: "user",
86
+ content: [
87
+ { type: "image" },
88
+ {
89
+ type: "text",
90
+ text: "What action do you think I should take in this situation? List all the possible actions and explain why you think they are good or bad.",
91
+ },
92
+ ],
93
+ },
94
+ ]
95
+ const prompt = processor.apply_chat_template(messages);
96
+ const url = "https://static.wikia.nocookie.net/essentialsdocs/images/7/70/Battle.png/revision/latest?cb=20220523172438";
97
+ const image = await load_image(url);
98
+ const inputs = await processor(image, prompt, { add_special_tokens: false });
99
+
100
+ // Generate response
101
+ const outputs = await model.generate({
102
+ ...inputs,
103
+ max_new_tokens: 2048,
104
+ streamer: new TextStreamer(processor.tokenizer, {
105
+ skip_prompt: true,
106
+ // callback_function: (text) => { /* Do something with the streamed output */ },
107
+ }),
108
+ });
109
+
110
+ // Decode output
111
+ const decoded = processor.batch_decode(
112
+ outputs.slice(null, [inputs.input_ids.dims.at(-1), null]),
113
+ { skip_special_tokens: true },
114
+ );
115
+ console.log(decoded[0]);
116
+ ```
117
+
118
+ <details>
119
+
120
+ <summary>See example output</summary>
121
+
122
+ ```
123
+ In this Pokémon game screenshot, you have several potential actions to consider, depending on the situation and your strategy. Here are the possible actions and their implications:
124
+
125
+ ---
126
+
127
+ ### **1. FIGHT**
128
+ **Description:** Use the Pikachu in your possession to attack the Pidgey.
129
+
130
+ #### **Pros:**
131
+ - **Potential to defeat Pidgey:** If Pikachu has strong moves (e.g., Thunderbolt, Electric Move) and Pidgey is weak to Electric-type attacks, this could be a strong choice.
132
+ - **Experience Gain:** Winning battles typically rewards you with experience points (XP) and sometimes drops Pidgey as a captured Pokémon.
133
+ - **Training Opportunity:** Helps you level up Pikachu, which can improve its stats and access new moves.
134
+
135
+ #### **Cons:**
136
+ - **Risk of Losing Pikachu:** If Pikachu is already at a low HP (e.g., 83/83 is not bad, but if it's lower), a loss could be detrimental.
137
+ - **Move Selection Matters:** If Pikachu doesn’t have a strong move against Pidgey, you might lose the battle unnecessarily.
138
+ - **Stamina Cost:** Battles can consume stamina if you're on a timer-based system (e.g., Pokémon Red/Blue).
139
+
140
+ ---
141
+
142
+ ### **2. RUN**
143
+ **Description:** Use the "Run" option to escape the battle.
144
+
145
+ #### **Pros:**
146
+ - **Avoids Risk:** If you're unsure about Pikachu’s moves or HP, running could save you from a potentially bad outcome.
147
+ - **Preserves Resources:** Running avoids losing Pikachu’s HP, which could be useful if you're running low.
148
+ - **Flexibility:** Allows you to explore or use other Pokémon later.
149
+
150
+ #### **Cons:**
151
+ - **No XP Gain:** Running means you won’t earn XP for defeating Pidgey.
152
+ - **Potential Consequences:** If you run too often, you might miss out on capturing Pidgey or gaining experience.
153
+ - **No Training:** Pikachu won’t level up or gain new moves if you avoid battles.
154
+
155
+ ---
156
+
157
+ ### **3. POKEMON (Select Another Pokémon)**
158
+ **Description:** If you have another Pokémon in your party, you could switch to it.
159
+
160
+ #### **Pros:**
161
+ - **Better Move Selection:** If you have a stronger Pokémon (e.g., a Fire-type or Ground-type) that can handle Pidgey, switching could be beneficial.
162
+ - **Balanced Strategy:** Helps you manage your team better.
163
+ - **Avoids Weaknesses:** If Pikachu is weak to something Pidgey might use, switching could prevent a loss.
164
+
165
+ #### **Cons:**
166
+ - **No Immediate XP Gain:** Switching doesn’t defeat Pidgey, so you won’t earn XP.
167
+ - **Stamina Cost:** Switching might still consume stamina if you're on a timer.
168
+ - **Potential to Lose Pikachu:** If you switch and Pikachu is already at a low HP, you might lose it.
169
+
170
+ ---
171
+
172
+ ### **Best Strategy Based on the Image:**
173
+ - **If you want to capture Pidgey:** Fighting is the best option, as it rewards you with experience and potentially captures Pidgey.
174
+ - **If you're unsure about Pikachu’s moves:** Running could be safer, but you might miss out on XP.
175
+ - **If you have another Pokémon:** Switching could be a good idea if you have a stronger option.
176
+
177
+ Would you like to know what moves Pikachu might have, or do you have another Pokémon in your party? That could help decide the best action!
178
+ ```
179
+
180
+ </details>
181
+
182
+
183
+ ### ONNXRuntime
184
+
185
+ ```py
186
+ from transformers import AutoConfig, AutoProcessor
187
+ import onnxruntime
188
+ import numpy as np
189
+ from huggingface_hub import hf_hub_download
190
+
191
+ # 1. Load config, processor, and model
192
+ model_id = "mistralai/Ministral-3-3B-Instruct-2512-ONNX"
193
+ config = AutoConfig.from_pretrained(model_id)
194
+ processor = AutoProcessor.from_pretrained(model_id)
195
+
196
+ vision_model_path = hf_hub_download(model_id, "vision_encoder_q4.onnx", subfolder="onnx") # Download vision graph
197
+ hf_hub_download(model_id, "vision_encoder_q4.onnx_data", subfolder="onnx") # Download vision weights
198
+ embed_model_path = hf_hub_download(model_id, "embed_tokens_fp16.onnx", subfolder="onnx") # Download embed_tokens graph
199
+ hf_hub_download(model_id, "embed_tokens_fp16.onnx_data", subfolder="onnx") # Download embed_tokens weights
200
+ decoder_model_path = hf_hub_download(model_id, "decoder_model_merged_q4.onnx", subfolder="onnx") # Download decoder graph
201
+ hf_hub_download(model_id, "decoder_model_merged_q4.onnx_data", subfolder="onnx") # Download decoder weights (1/2)
202
+ hf_hub_download(model_id, "decoder_model_merged_q4.onnx_data_1", subfolder="onnx") # Download decoder weights (2/2)
203
+
204
+ ## Load sessions
205
+ providers = ['CPUExecutionProvider']
206
+ vision_session = onnxruntime.InferenceSession(vision_model_path, providers=providers)
207
+ embed_session = onnxruntime.InferenceSession(embed_model_path, providers=providers)
208
+ decoder_session = onnxruntime.InferenceSession(decoder_model_path, providers=providers)
209
+
210
+ ## Set config values
211
+ text_config = config.text_config
212
+ num_key_value_heads = text_config.num_key_value_heads
213
+ head_dim = text_config.head_dim
214
+ num_hidden_layers = text_config.num_hidden_layers
215
+ eos_token_id = text_config.eos_token_id
216
+ image_token_index = config.image_token_index
217
+
218
+ # 2. Prepare inputs
219
+ image_url = "https://static.wikia.nocookie.net/essentialsdocs/images/7/70/Battle.png/revision/latest?cb=20220523172438"
220
+ messages = [
221
+ {
222
+ "role": "user",
223
+ "content": [
224
+ {
225
+ "type": "text",
226
+ "text": "What action do you think I should take in this situation? List all the possible actions and explain why you think they are good or bad.",
227
+ },
228
+ {"type": "image", "url": image_url},
229
+ ],
230
+ },
231
+ ]
232
+ inputs = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt")
233
+
234
+ input_ids = inputs['input_ids'].numpy()
235
+ attention_mask = inputs['attention_mask'].numpy()
236
+ pixel_values = inputs['pixel_values'].numpy()
237
+ batch_size = input_ids.shape[0]
238
+ past_key_values = {
239
+ f'past_key_values.{layer}.{kv}': np.zeros([batch_size, num_key_value_heads, 0, head_dim], dtype=np.float32)
240
+ for layer in range(num_hidden_layers)
241
+ for kv in ('key', 'value')
242
+ }
243
+ position_ids = np.tile(np.arange(0, input_ids.shape[-1]), (batch_size, 1))
244
+
245
+ # 3. Generation loop
246
+ max_new_tokens = 1024
247
+ generated_tokens = np.array([[]], dtype=np.int64)
248
+ image_features = None
249
+ for i in range(max_new_tokens):
250
+ inputs_embeds = embed_session.run(None, {'input_ids': input_ids})[0]
251
+
252
+ if image_features is None:
253
+ ## Only compute vision features if not already computed
254
+ image_features = vision_session.run(None, dict(
255
+ pixel_values=pixel_values,
256
+ ))[0]
257
+
258
+ ## Merge text and vision embeddings
259
+ inputs_embeds[input_ids == image_token_index] = image_features.reshape(-1, image_features.shape[-1])
260
+
261
+ logits, *present_key_values = decoder_session.run(None, dict(
262
+ inputs_embeds=inputs_embeds,
263
+ attention_mask=attention_mask,
264
+ position_ids=position_ids,
265
+ **past_key_values,
266
+ ))
267
+
268
+ ## Update values for next generation loop
269
+ input_ids = logits[:, -1].argmax(-1, keepdims=True)
270
+ attention_mask = np.concatenate([attention_mask, np.ones((batch_size, 1), dtype=attention_mask.dtype)], axis=-1)
271
+ position_ids = position_ids[:, -1:] + 1
272
+ for j, key in enumerate(past_key_values):
273
+ past_key_values[key] = present_key_values[j]
274
+
275
+ generated_tokens = np.concatenate([generated_tokens, input_ids], axis=-1)
276
+ if (input_ids == eos_token_id).all():
277
+ break
278
+
279
+ ## (Optional) Streaming
280
+ print(processor.decode(input_ids[0]), end='', flush=True)
281
+ print()
282
+
283
+ # 4. Output result
284
+ print(processor.batch_decode(generated_tokens, skip_special_tokens=True)[0])
285
+ ```
286
+
287
+ <details>
288
+ <summary>See example output</summary>
289
+
290
+ ```
291
+ In this *Pokémon* game screenshot, you are presented with a battle scenario between **Pidgey** and **Pikachu**. Here are the possible actions along with an analysis of their potential outcomes:
292
+
293
+ ---
294
+
295
+ ### **1. FIGHT**
296
+ **Explanation:**
297
+ - You choose to engage in battle.
298
+ - Pidgey is a **Level 17** Pokémon with basic stats, while Pikachu is a **Level 42** Pokémon with significantly higher HP, Attack, and overall power.
299
+ - **Pros:**
300
+ - Pikachu is stronger and likely to win if it lands a hit.
301
+ - Pidgey may be able to land a few moves before being overwhelmed.
302
+ - **Cons:**
303
+ - Pidgey is likely to lose quickly due to its lower stats and experience.
304
+ - Pikachu may have a high chance of winning in one or two turns.
305
+
306
+ ---
307
+
308
+ ### **2. BAG**
309
+ **Explanation:**
310
+ - You choose to **Bag** Pikachu.
311
+ - **Pros:**
312
+ - You can keep Pikachu in your bag for later use.
313
+ - If you need to switch Pokémon or use Pikachu in another battle, this is a viable option.
314
+ - **Cons:**
315
+ - You miss out on the opportunity to potentially defeat Pidgey and gain experience.
316
+ - If Pidgey is a rare or special Pokémon, bagging it might not be ideal.
317
+
318
+ ---
319
+
320
+ ### **3. RUN**
321
+ **Explanation:**
322
+ - You choose to **Run** (escape the battle).
323
+ - **Pros:**
324
+ - You avoid losing HP and experience points.
325
+ - You can continue your journey without facing a weaker opponent.
326
+ - **Cons:**
327
+ - You might miss out on a chance to level up Pikachu or gain experience.
328
+ - If you are in a competitive setting, running might not be the best strategy.
329
+
330
+ ---
331
+
332
+ ### **Summary of Best Options:**
333
+ - **If you want to continue the game and gain experience:**
334
+ - **Fight** Pikachu, but be prepared for a potentially quick loss.
335
+ - **If you want to save Pikachu for later:**
336
+ - **Bag** Pikachu and continue your journey.
337
+ - **If you want to avoid unnecessary battles:**
338
+ - **Run** away from the battle.
339
+
340
+ Since Pikachu is significantly stronger, **Fighting** is the most straightforward choice, but you might want to consider **Bagging** Pikachu if you want to keep it for later battles. If you're not in a rush, **Running** is also a viable option.
341
+ In this *Pokémon* game screenshot, you are presented with a battle scenario between **Pidgey** and **Pikachu**. Here are the possible actions along with an analysis of their potential outcomes:
342
+
343
+ ---
344
+
345
+ ### **1. FIGHT**
346
+ **Explanation:**
347
+ - You choose to engage in battle.
348
+ - Pidgey is a **Level 17** Pokémon with basic stats, while Pikachu is a **Level 42** Pokémon with significantly higher HP, Attack, and overall power.
349
+ - **Pros:**
350
+ - Pikachu is stronger and likely to win if it lands a hit.
351
+ - Pidgey may be able to land a few moves before being overwhelmed.
352
+ - **Cons:**
353
+ - Pidgey is likely to lose quickly due to its lower stats and experience.
354
+ - Pikachu may have a high chance of winning in one or two turns.
355
+
356
+ ---
357
+
358
+ ### **2. BAG**
359
+ **Explanation:**
360
+ - You choose to **Bag** Pikachu.
361
+ - **Pros:**
362
+ - You can keep Pikachu in your bag for later use.
363
+ - If you need to switch Pokémon or use Pikachu in another battle, this is a viable option.
364
+ - **Cons:**
365
+ - You miss out on the opportunity to potentially defeat Pidgey and gain experience.
366
+ - If Pidgey is a rare or special Pokémon, bagging it might not be ideal.
367
+
368
+ ---
369
+
370
+ ### **3. RUN**
371
+ **Explanation:**
372
+ - You choose to **Run** (escape the battle).
373
+ - **Pros:**
374
+ - You avoid losing HP and experience points.
375
+ - You can continue your journey without facing a weaker opponent.
376
+ - **Cons:**
377
+ - You might miss out on a chance to level up Pikachu or gain experience.
378
+ - If you are in a competitive setting, running might not be the best strategy.
379
+
380
+ ---
381
+
382
+ ### **Summary of Best Options:**
383
+ - **If you want to continue the game and gain experience:**
384
+ - **Fight** Pikachu, but be prepared for a potentially quick loss.
385
+ - **If you want to save Pikachu for later:**
386
+ - **Bag** Pikachu and continue your journey.
387
+ - **If you want to avoid unnecessary battles:**
388
+ - **Run** away from the battle.
389
+
390
+ Since Pikachu is significantly stronger, **Fighting** is the most straightforward choice, but you might want to consider **Bagging** Pikachu if you want to keep it for later battles. If you're not in a rush, **Running** is also a viable option.
391
+ ```
392
+
393
+ </details>
394
+
395
+
396
  ## License
397
 
398
  This model is licensed under the [Apache 2.0 License](https://www.apache.org/licenses/LICENSE-2.0.txt).