[MM][Mistral3] Image preprocessing optimization (#57531)
Signed-off-by: Jakub Zakrzewski <jzakrzewski@nvidia.com> Co-authored-by: OpenAI Codex <noreply@openai.com> Co-authored-by: OpenAI Codex <codex@openai.com> Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
OpenAI Codex
OpenAI Codex
mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
parent
65ed0a2642
commit
d86cf91240
@@ -10,6 +10,7 @@ from typing import Annotated, Literal
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from mistral_common.protocol.instruct.chunk import ImageChunk, TextChunk
|
||||
from mistral_common.protocol.instruct.messages import UserMessage
|
||||
from mistral_common.protocol.instruct.request import ChatCompletionRequest
|
||||
@@ -1427,12 +1428,55 @@ class PixtralHFTransformer(nn.Module):
|
||||
return x
|
||||
|
||||
|
||||
def pixtral_patch_embed(
|
||||
images: list[torch.Tensor],
|
||||
weight: torch.Tensor,
|
||||
input_norm: nn.Module,
|
||||
) -> tuple[torch.Tensor, list[torch.Tensor]]:
|
||||
"""Normalize and project all CHW images in one matrix multiplication."""
|
||||
out_channels, in_channels, patch_height, patch_width = weight.shape
|
||||
grid_sizes = []
|
||||
for image in images:
|
||||
assert image.ndim == 3 and image.shape[0] == in_channels
|
||||
_, height, width = image.shape
|
||||
patch_rows = height // patch_height
|
||||
patch_cols = width // patch_width
|
||||
grid_sizes.append((patch_rows, patch_cols))
|
||||
|
||||
patch_counts = [rows * cols for rows, cols in grid_sizes]
|
||||
packed = torch.empty(
|
||||
(sum(patch_counts), in_channels * patch_height * patch_width),
|
||||
dtype=images[0].dtype,
|
||||
device=images[0].device,
|
||||
)
|
||||
offset = 0
|
||||
for image, (rows, cols), count in zip(images, grid_sizes, patch_counts):
|
||||
source = (
|
||||
image[:, : rows * patch_height, : cols * patch_width]
|
||||
.reshape(in_channels, rows, patch_height, cols, patch_width)
|
||||
.permute(1, 3, 0, 2, 4)
|
||||
)
|
||||
packed[offset : offset + count].view(
|
||||
rows, cols, in_channels, patch_height, patch_width
|
||||
).copy_(source)
|
||||
offset += count
|
||||
|
||||
normalized = input_norm(packed, weight.dtype)
|
||||
projected = F.linear(normalized, weight.reshape(out_channels, -1))
|
||||
embeddings = [
|
||||
tokens.transpose(0, 1).reshape(1, out_channels, rows, cols)
|
||||
for tokens, (rows, cols) in zip(projected.split(patch_counts), grid_sizes)
|
||||
]
|
||||
return projected.unsqueeze(0), embeddings
|
||||
|
||||
|
||||
class PixtralHFVisionModel(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
config: PixtralVisionConfig,
|
||||
quant_config: QuantizationConfig | None = None,
|
||||
*,
|
||||
input_norm: nn.Module | None = None,
|
||||
num_hidden_layers_override: int | None = None,
|
||||
require_post_norm: bool | None = None,
|
||||
prefix: str = "",
|
||||
@@ -1440,6 +1484,7 @@ class PixtralHFVisionModel(nn.Module):
|
||||
super().__init__()
|
||||
|
||||
self.config = config
|
||||
self.input_norm = input_norm
|
||||
|
||||
self.patch_conv = Conv2dLayer(
|
||||
in_channels=config.num_channels,
|
||||
@@ -1495,16 +1540,24 @@ class PixtralHFVisionModel(nn.Module):
|
||||
all tokens of all images of shape (N_toks, D)
|
||||
|
||||
"""
|
||||
# pass images through initial convolution independently
|
||||
patch_embeds_list = [
|
||||
self.patch_conv(img.unsqueeze(0).to(self.dtype)) for img in pixel_values
|
||||
]
|
||||
images = [image.to(device=self.device) for image in pixel_values]
|
||||
if self.input_norm is not None:
|
||||
patch_embeds, patch_embeds_list = pixtral_patch_embed(
|
||||
images,
|
||||
self.patch_conv.weight,
|
||||
self.input_norm,
|
||||
)
|
||||
else:
|
||||
patch_embeds_list = []
|
||||
for image in images:
|
||||
patch_embeds_list.append(
|
||||
self.patch_conv(image.unsqueeze(0).to(self.dtype))
|
||||
)
|
||||
patch_embeds = torch.cat(
|
||||
[p.flatten(2).permute(0, 2, 1) for p in patch_embeds_list], dim=1
|
||||
)
|
||||
|
||||
patch_embeds = [p.flatten(2).permute(0, 2, 1) for p in patch_embeds_list]
|
||||
embed_sizes = [p.shape[1] for p in patch_embeds]
|
||||
|
||||
# flatten to a single sequence
|
||||
patch_embeds = torch.cat(patch_embeds, dim=1)
|
||||
embed_sizes = [p.shape[-2] * p.shape[-1] for p in patch_embeds_list]
|
||||
patch_embeds = self.ln_pre(patch_embeds)
|
||||
|
||||
# positional embeddings
|
||||
|
||||
Reference in New Issue
Block a user