-
Notifications
You must be signed in to change notification settings - Fork 231
[OpenVINO] Add export and inference support for ministral reasoning model 2510 #1669
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||
|---|---|---|---|---|
|
|
@@ -227,6 +227,15 @@ def patch_cos_sin_cached_fp32(model): | |||
| def eager_mask_without_vmap(*args, **kwargs) -> Optional[torch.Tensor]: | ||||
| kwargs.pop("allow_is_causal_skip", None) | ||||
| dtype = kwargs.get("dtype", torch.float32) | ||||
| # Handle transformers >= 5.4 API change: q_length kwarg instead of cache_position positional arg | ||||
| if "q_length" in kwargs and "cache_position" not in kwargs: | ||||
| q_length = kwargs.pop("q_length") | ||||
| q_offset = kwargs.pop("q_offset", 0) | ||||
| device = kwargs.get("device", "cpu") | ||||
| kwargs["cache_position"] = torch.arange(q_offset, q_offset + q_length, device=device) | ||||
| # Remove kwargs not accepted by sdpa_mask_without_vmap | ||||
| for key in ["allow_is_bidirectional_skip", "allow_torch_fix", "use_vmap", "config", "dtype"]: | ||||
| kwargs.pop(key, None) | ||||
| mask = sdpa_mask_without_vmap(*args, allow_is_causal_skip=False, **kwargs) | ||||
| # we use torch.finfo(torch.float16).min instead torch.finfo(dtype).min to avoid an overflow but not | ||||
| # sure this is the right way to handle this, we are basically pretending that -65,504 is -inf | ||||
|
|
@@ -8319,3 +8328,160 @@ def __exit__(self, exc_type, exc_value, traceback): | |||
| sparse_moe_block = decoder_layer.mlp | ||||
| decoder_layer.mlp.forward = decoder_layer.mlp._orig_forward | ||||
| del sparse_moe_block.down_projs, sparse_moe_block.gate_projs, sparse_moe_block.up_projs | ||||
|
|
||||
|
|
||||
| def _mistral3_vision_embed_forward(self, pixel_values): | ||||
| """ | ||||
| Inline vision pipeline (vision_tower + multi_modal_projector) for Mistral3. | ||||
| All dimensions are derived from tensor .shape to stay dynamic during OpenVINO tracing. | ||||
| """ | ||||
| vision_tower = self.model.vision_tower | ||||
| projector = self.model.multi_modal_projector | ||||
| config = self.config | ||||
|
|
||||
| # Step 1: Patch convolution | ||||
| target_dtype = vision_tower.patch_conv.weight.dtype | ||||
| patch_embeds = vision_tower.patch_conv(pixel_values.to(dtype=target_dtype)) | ||||
| # patch_embeds: (batch, hidden, h_patches, w_patches) | ||||
| h_patches = patch_embeds.shape[2] | ||||
| w_patches = patch_embeds.shape[3] | ||||
| d = patch_embeds.shape[1] | ||||
|
|
||||
| # Step 2: Flatten and normalize (single image, batch=1) | ||||
| patch_embeds = patch_embeds[0].flatten(1).T.unsqueeze(0) # (1, h*w, d) | ||||
| patch_embeds = vision_tower.ln_pre(patch_embeds) | ||||
|
Comment on lines
+8350
to
+8352
|
||||
|
|
||||
| # Step 3: Position embeddings - derive from tensor shapes | ||||
| max_width = config.vision_config.image_size // config.vision_config.patch_size | ||||
| h_idx = torch.arange(h_patches, device=pixel_values.device) | ||||
| w_idx = torch.arange(w_patches, device=pixel_values.device) | ||||
| mesh_h, mesh_w = torch.meshgrid(h_idx, w_idx, indexing="ij") | ||||
| position_ids = (mesh_h.reshape(-1) * max_width + mesh_w.reshape(-1)) | ||||
|
|
||||
| position_embeddings = vision_tower.patch_positional_embedding(patch_embeds, position_ids) | ||||
|
|
||||
| # Step 4: Build block attention mask for non-flash attention | ||||
| seq_len = patch_embeds.shape[1] | ||||
| causal_mask = torch.zeros((seq_len, seq_len), dtype=patch_embeds.dtype, device=patch_embeds.device) | ||||
| attention_mask = causal_mask[None, None, :, :].expand(1, 1, -1, -1) | ||||
|
|
||||
| # Step 5: Transformer layers | ||||
| transformer_out = vision_tower.transformer( | ||||
| patch_embeds, | ||||
| attention_mask=attention_mask, | ||||
| position_embeddings=position_embeddings, | ||||
| ) | ||||
|
|
||||
| # Step 6: Select feature layer | ||||
| selected = transformer_out.last_hidden_state # (1, num_patches, hidden) | ||||
|
|
||||
| # Step 7: Apply projector (norm + patch_merger + MLP) | ||||
| image_features = projector.norm(selected.squeeze(0)) # (num_patches, hidden) | ||||
|
|
||||
| # Patch merger - unfold + merge | ||||
| spatial_merge = config.spatial_merge_size | ||||
| patch_size = config.vision_config.patch_size | ||||
|
||||
| patch_size = config.vision_config.patch_size |
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -4802,6 +4802,61 @@ def preprocess_inputs( | |||||||||||||||||||||||||||||||
| return inputs | ||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||
| class _OVMistral3ForCausalLM(OVModelForVisualCausalLM): | ||||||||||||||||||||||||||||||||
| def get_vision_embeddings(self, pixel_values, input_ids=None, **kwargs): | ||||||||||||||||||||||||||||||||
| if input_ids is not None and input_ids.shape[1] == 1: | ||||||||||||||||||||||||||||||||
| return None | ||||||||||||||||||||||||||||||||
| if pixel_values is not None and pixel_values.dtype != torch.float32: | ||||||||||||||||||||||||||||||||
| pixel_values = pixel_values.to(torch.float32) | ||||||||||||||||||||||||||||||||
| return self.vision_embeddings(pixel_values).last_hidden_state | ||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||
| def merge_vision_text_embeddings( | ||||||||||||||||||||||||||||||||
| self, vision_embeds, inputs_embeds, input_ids=None, attention_mask=None, position_ids=None, **kwargs | ||||||||||||||||||||||||||||||||
| ): | ||||||||||||||||||||||||||||||||
| image_features = torch.from_numpy(vision_embeds) if isinstance(vision_embeds, np.ndarray) else vision_embeds | ||||||||||||||||||||||||||||||||
| inputs_embeds = torch.from_numpy(inputs_embeds) if isinstance(inputs_embeds, np.ndarray) else inputs_embeds | ||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||
| image_token_id = getattr(self.config, "image_token_index", getattr(self.config, "image_token_id", 10)) | ||||||||||||||||||||||||||||||||
| special_image_mask = (input_ids == image_token_id).unsqueeze(-1) | ||||||||||||||||||||||||||||||||
| special_image_mask = special_image_mask.expand_as(inputs_embeds) | ||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||
| image_features = image_features.view(-1, image_features.shape[-1]).to(inputs_embeds.device, inputs_embeds.dtype) | ||||||||||||||||||||||||||||||||
|
Comment on lines
+4820
to
+4823
|
||||||||||||||||||||||||||||||||
| special_image_mask = (input_ids == image_token_id).unsqueeze(-1) | |
| special_image_mask = special_image_mask.expand_as(inputs_embeds) | |
| image_features = image_features.view(-1, image_features.shape[-1]).to(inputs_embeds.device, inputs_embeds.dtype) | |
| special_image_mask = (input_ids == image_token_id).unsqueeze(-1).to(inputs_embeds.device) | |
| image_features = image_features.view(-1, image_features.shape[-1]).to(inputs_embeds.device, inputs_embeds.dtype) | |
| num_image_tokens = special_image_mask[..., 0].sum().item() | |
| num_image_features = image_features.shape[0] | |
| if num_image_tokens != num_image_features: | |
| raise ValueError( | |
| f"Image features and image tokens do not match: tokens: {num_image_tokens}, features {num_image_features}" | |
| ) | |
| special_image_mask = special_image_mask.expand_as(inputs_embeds) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This PR introduces a new model type (
mistral3) with custom export/inference behavior, but there are no corresponding OpenVINO tests added. Given the existing coverage for other VLMs intests/openvino/*, please add at least a smoke test that exports and runs a short generate pass formistral3(or a tiny/random checkpoint) to prevent regressions in the patchers and behavior routing.