Views
No views yet
[!Tip] This model was contributed by Xenova from Hugging Face. We sincerely appreciate the integration and community collaboration. While preliminary functionality checks have been performed, comprehensive testing has not yet been completed. We recommend you to proceed with caution and conducting your own evaluations for specific use cases. If any issues arise, open a PR/Issue here and we will try to address them promptly.
npm i @huggingface/transformers1import {
2 AutoProcessor,
3 AutoModelForImageTextToText,
4 load_image,
5 TextStreamer,
6} from "@huggingface/transformers";
7
8// Load processor and model
9const model_id = "mistralai/Ministral-3-3B-Instruct-2512-ONNX";
10const processor = await AutoProcessor.from_pretrained(model_id);
11const model = await AutoModelForImageTextToText.from_pretrained(model_id, {
12 device: "webgpu",
13});
14
15// Prepare inputs
16const messages = [
17 {
18 role: "user",
19 content: [
20 { type: "image" },
21 {
22 type: "text",
23 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.",
24 },
25 ],
26 },
27]
28const prompt = processor.apply_chat_template(messages);
29const url = "https://static.wikia.nocookie.net/essentialsdocs/images/7/70/Battle.png/revision/latest?cb=20220523172438";
30const image = await load_image(url);
31const inputs = await processor(image, prompt, { add_special_tokens: false });
32
33// Generate response
34const outputs = await model.generate({
35 ...inputs,
36 max_new_tokens: 2048,
37 streamer: new TextStreamer(processor.tokenizer, {
38 skip_prompt: true,
39 // callback_function: (text) => { /* Do something with the streamed output */ },
40 }),
41});
42
43// Decode output
44const decoded = processor.batch_decode(
45 outputs.slice(null, [inputs.input_ids.dims.at(-1), null]),
46 { skip_special_tokens: true },
47);
48console.log(decoded[0]);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:
---
### **1. FIGHT**
**Description:** Use the Pikachu in your possession to attack the Pidgey.
#### **Pros:**
- **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.
- **Experience Gain:** Winning battles typically rewards you with experience points (XP) and sometimes drops Pidgey as a captured Pokémon.
- **Training Opportunity:** Helps you level up Pikachu, which can improve its stats and access new moves.
#### **Cons:**
- **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.
- **Move Selection Matters:** If Pikachu doesn’t have a strong move against Pidgey, you might lose the battle unnecessarily.
- **Stamina Cost:** Battles can consume stamina if you're on a timer-based system (e.g., Pokémon Red/Blue).
---
### **2. RUN**
**Description:** Use the "Run" option to escape the battle.
#### **Pros:**
- **Avoids Risk:** If you're unsure about Pikachu’s moves or HP, running could save you from a potentially bad outcome.
- **Preserves Resources:** Running avoids losing Pikachu’s HP, which could be useful if you're running low.
- **Flexibility:** Allows you to explore or use other Pokémon later.
#### **Cons:**
- **No XP Gain:** Running means you won’t earn XP for defeating Pidgey.
- **Potential Consequences:** If you run too often, you might miss out on capturing Pidgey or gaining experience.
- **No Training:** Pikachu won’t level up or gain new moves if you avoid battles.
---
### **3. POKEMON (Select Another Pokémon)**
**Description:** If you have another Pokémon in your party, you could switch to it.
#### **Pros:**
- **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.
- **Balanced Strategy:** Helps you manage your team better.
- **Avoids Weaknesses:** If Pikachu is weak to something Pidgey might use, switching could prevent a loss.
#### **Cons:**
- **No Immediate XP Gain:** Switching doesn’t defeat Pidgey, so you won’t earn XP.
- **Stamina Cost:** Switching might still consume stamina if you're on a timer.
- **Potential to Lose Pikachu:** If you switch and Pikachu is already at a low HP, you might lose it.
---
### **Best Strategy Based on the Image:**
- **If you want to capture Pidgey:** Fighting is the best option, as it rewards you with experience and potentially captures Pidgey.
- **If you're unsure about Pikachu’s moves:** Running could be safer, but you might miss out on XP.
- **If you have another Pokémon:** Switching could be a good idea if you have a stronger option.
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!1from transformers import AutoConfig, AutoProcessor
2import onnxruntime
3import numpy as np
4from huggingface_hub import hf_hub_download
5
6# 1. Load config, processor, and model
7model_id = "mistralai/Ministral-3-3B-Instruct-2512-ONNX"
8config = AutoConfig.from_pretrained(model_id)
9processor = AutoProcessor.from_pretrained(model_id)
10
11vision_model_path = hf_hub_download(model_id, "vision_encoder_q4.onnx", subfolder="onnx") # Download vision graph
12hf_hub_download(model_id, "vision_encoder_q4.onnx_data", subfolder="onnx") # Download vision weights
13embed_model_path = hf_hub_download(model_id, "embed_tokens_fp16.onnx", subfolder="onnx") # Download embed_tokens graph
14hf_hub_download(model_id, "embed_tokens_fp16.onnx_data", subfolder="onnx") # Download embed_tokens weights
15decoder_model_path = hf_hub_download(model_id, "decoder_model_merged_q4.onnx", subfolder="onnx") # Download decoder graph
16hf_hub_download(model_id, "decoder_model_merged_q4.onnx_data", subfolder="onnx") # Download decoder weights (1/2)
17hf_hub_download(model_id, "decoder_model_merged_q4.onnx_data_1", subfolder="onnx") # Download decoder weights (2/2)
18
19## Load sessions
20providers = ['CPUExecutionProvider']
21vision_session = onnxruntime.InferenceSession(vision_model_path, providers=providers)
22embed_session = onnxruntime.InferenceSession(embed_model_path, providers=providers)
23decoder_session = onnxruntime.InferenceSession(decoder_model_path, providers=providers)
24
25## Set config values
26text_config = config.text_config
27num_key_value_heads = text_config.num_key_value_heads
28head_dim = text_config.head_dim
29num_hidden_layers = text_config.num_hidden_layers
30eos_token_id = text_config.eos_token_id
31image_token_index = config.image_token_index
32
33# 2. Prepare inputs
34image_url = "https://static.wikia.nocookie.net/essentialsdocs/images/7/70/Battle.png/revision/latest?cb=20220523172438"
35messages = [
36 {
37 "role": "user",
38 "content": [
39 {
40 "type": "text",
41 "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.",
42 },
43 {"type": "image", "url": image_url},
44 ],
45 },
46]
47inputs = processor.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt")
48
49input_ids = inputs['input_ids'].numpy()
50attention_mask = inputs['attention_mask'].numpy()
51pixel_values = inputs['pixel_values'].numpy()
52batch_size = input_ids.shape[0]
53past_key_values = {
54 f'past_key_values.{layer}.{kv}': np.zeros([batch_size, num_key_value_heads, 0, head_dim], dtype=np.float32)
55 for layer in range(num_hidden_layers)
56 for kv in ('key', 'value')
57}
58position_ids = np.tile(np.arange(0, input_ids.shape[-1]), (batch_size, 1))
59
60# 3. Generation loop
61max_new_tokens = 1024
62generated_tokens = np.array([[]], dtype=np.int64)
63image_features = None
64for i in range(max_new_tokens):
65 inputs_embeds = embed_session.run(None, {'input_ids': input_ids})[0]
66
67 if image_features is None:
68 ## Only compute vision features if not already computed
69 image_features = vision_session.run(None, dict(
70 pixel_values=pixel_values,
71 ))[0]
72
73 ## Merge text and vision embeddings
74 inputs_embeds[input_ids == image_token_index] = image_features.reshape(-1, image_features.shape[-1])
75
76 logits, *present_key_values = decoder_session.run(None, dict(
77 inputs_embeds=inputs_embeds,
78 attention_mask=attention_mask,
79 position_ids=position_ids,
80 **past_key_values,
81 ))
82
83 ## Update values for next generation loop
84 input_ids = logits[:, -1].argmax(-1, keepdims=True)
85 attention_mask = np.concatenate([attention_mask, np.ones((batch_size, 1), dtype=attention_mask.dtype)], axis=-1)
86 position_ids = position_ids[:, -1:] + 1
87 for j, key in enumerate(past_key_values):
88 past_key_values[key] = present_key_values[j]
89
90 generated_tokens = np.concatenate([generated_tokens, input_ids], axis=-1)
91 if (input_ids == eos_token_id).all():
92 break
93
94 ## (Optional) Streaming
95 print(processor.decode(input_ids[0]), end='', flush=True)
96print()
97
98# 4. Output result
99print(processor.batch_decode(generated_tokens, skip_special_tokens=True)[0])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:
---
### **1. FIGHT**
**Explanation:**
- You choose to engage in battle.
- 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.
- **Pros:**
- Pikachu is stronger and likely to win if it lands a hit.
- Pidgey may be able to land a few moves before being overwhelmed.
- **Cons:**
- Pidgey is likely to lose quickly due to its lower stats and experience.
- Pikachu may have a high chance of winning in one or two turns.
---
### **2. BAG**
**Explanation:**
- You choose to **Bag** Pikachu.
- **Pros:**
- You can keep Pikachu in your bag for later use.
- If you need to switch Pokémon or use Pikachu in another battle, this is a viable option.
- **Cons:**
- You miss out on the opportunity to potentially defeat Pidgey and gain experience.
- If Pidgey is a rare or special Pokémon, bagging it might not be ideal.
---
### **3. RUN**
**Explanation:**
- You choose to **Run** (escape the battle).
- **Pros:**
- You avoid losing HP and experience points.
- You can continue your journey without facing a weaker opponent.
- **Cons:**
- You might miss out on a chance to level up Pikachu or gain experience.
- If you are in a competitive setting, running might not be the best strategy.
---
### **Summary of Best Options:**
- **If you want to continue the game and gain experience:**
- **Fight** Pikachu, but be prepared for a potentially quick loss.
- **If you want to save Pikachu for later:**
- **Bag** Pikachu and continue your journey.
- **If you want to avoid unnecessary battles:**
- **Run** away from the battle.
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.
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:
---
### **1. FIGHT**
**Explanation:**
- You choose to engage in battle.
- 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.
- **Pros:**
- Pikachu is stronger and likely to win if it lands a hit.
- Pidgey may be able to land a few moves before being overwhelmed.
- **Cons:**
- Pidgey is likely to lose quickly due to its lower stats and experience.
- Pikachu may have a high chance of winning in one or two turns.
---
### **2. BAG**
**Explanation:**
- You choose to **Bag** Pikachu.
- **Pros:**
- You can keep Pikachu in your bag for later use.
- If you need to switch Pokémon or use Pikachu in another battle, this is a viable option.
- **Cons:**
- You miss out on the opportunity to potentially defeat Pidgey and gain experience.
- If Pidgey is a rare or special Pokémon, bagging it might not be ideal.
---
### **3. RUN**
**Explanation:**
- You choose to **Run** (escape the battle).
- **Pros:**
- You avoid losing HP and experience points.
- You can continue your journey without facing a weaker opponent.
- **Cons:**
- You might miss out on a chance to level up Pikachu or gain experience.
- If you are in a competitive setting, running might not be the best strategy.
---
### **Summary of Best Options:**
- **If you want to continue the game and gain experience:**
- **Fight** Pikachu, but be prepared for a potentially quick loss.
- **If you want to save Pikachu for later:**
- **Bag** Pikachu and continue your journey.
- **If you want to avoid unnecessary battles:**
- **Run** away from the battle.
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.