Skip to content

[model-gateway] add image processor and transformer structure#14344

Merged
slin1237 merged 2 commits intomainfrom
smg-mm-2/n
Dec 3, 2025
Merged

[model-gateway] add image processor and transformer structure#14344
slin1237 merged 2 commits intomainfrom
smg-mm-2/n

Conversation

@slin1237
Copy link
Collaborator

@slin1237 slin1237 commented Dec 3, 2025

Checklist

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @slin1237, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request establishes the foundational structure for image processing and transformation within the model-gateway by introducing a dedicated vision module. It defines a clear interface for model-specific image preprocessors, a standardized output format for processed images, and robust utilities for parsing HuggingFace configurations and performing essential image manipulations. This work is crucial for enabling multimodal capabilities by allowing efficient and flexible handling of visual inputs in a pure Rust environment, paving the way for future integration of various vision models.

Highlights

  • New Vision Module: Introduced a new vision module under sgl-router/src/multimodal to encapsulate all image processing and transformation logic.
  • Image PreProcessor Trait: Defined the ImagePreProcessor trait, providing a standardized interface for model-specific image preprocessing pipelines (e.g., LLaVA, Qwen-VL, Phi3-Vision).
  • PreprocessedImages Structure: Added the PreprocessedImages struct to hold processed pixel values, token counts, original image sizes, and model-specific auxiliary outputs, ready for model consumption.
  • HuggingFace Config Parsing: Implemented PreProcessorConfig to parse preprocessor_config.json files from HuggingFace, allowing dynamic configuration of image processing steps.
  • Core Image Transformations: Provided a suite of pure Rust image transformation functions in transforms.rs, including to_tensor, normalize, rescale, resize, center_crop, expand_to_square, pad_to_size, and stack_batch.
  • Image Processor Registry: Included an ImageProcessorRegistry to manage and discover image processors based on model IDs, facilitating flexible integration of different vision models.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@slin1237 slin1237 added the run-ci label Dec 3, 2025
Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request lays a solid foundation for vision processing in Rust by introducing a well-structured module for image transformations, configuration parsing, and a processor registry. The code is clean and includes tests, which is great. My review focuses on improving the robustness of the processor registry, making configuration handling more explicit to avoid surprising defaults, and suggesting performance optimizations for tensor conversions.

Comment on lines +181 to +196
pub fn get_target_size(&self) -> Option<(u32, u32)> {
self.size.as_ref().map(|s| {
// Try explicit height/width first
let h = s
.get("height")
.or_else(|| s.get("shortest_edge"))
.copied()
.unwrap_or(224);
let w = s
.get("width")
.or_else(|| s.get("shortest_edge"))
.copied()
.unwrap_or(224);
(h, w)
})
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The use of unwrap_or(224) can lead to surprising behavior. For example, if the config contains "size": {}, this function will return Some((224, 224)). It would be more robust to return None if the necessary keys (height/width or shortest_edge) are not present in the size map. This makes the function's behavior more explicit and less magical.

    pub fn get_target_size(&self) -> Option<(u32, u32)> {
        self.size.as_ref().and_then(|s| {
            if let (Some(&h), Some(&w)) = (s.get("height"), s.get("width")) {
                Some((h, w))
            } else {
                s.get("shortest_edge").map(|&edge| (edge, edge))
            }
        })
    }

Comment on lines +201 to +207
pub fn get_crop_size(&self) -> Option<(u32, u32)> {
self.crop_size.as_ref().map(|s| {
let h = s.get("height").copied().unwrap_or(224);
let w = s.get("width").copied().unwrap_or(224);
(h, w)
})
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Similar to get_target_size, get_crop_size uses unwrap_or(224), which can cause unexpected behavior if crop_size is an empty map. It's better to return None if height and width are not specified, making the contract of the function clearer.

    pub fn get_crop_size(&self) -> Option<(u32, u32)> {
        self.crop_size.as_ref().and_then(|s| {
            if let (Some(&h), Some(&w)) = (s.get("height"), s.get("width")) {
                Some((h, w))
            } else {
                None
            }
        })
    }

Comment on lines +51 to +63
pub fn to_tensor_no_norm(image: &DynamicImage) -> Array3<f32> {
let rgb = image.to_rgb8();
let (w, h) = (rgb.width() as usize, rgb.height() as usize);
let mut arr = Array3::<f32>::zeros((3, h, w));

for (x, y, pixel) in rgb.enumerate_pixels() {
let (x, y) = (x as usize, y as usize);
arr[[0, y, x]] = pixel[0] as f32;
arr[[1, y, x]] = pixel[1] as f32;
arr[[2, y, x]] = pixel[2] as f32;
}
arr
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Similar to to_tensor, this function can be optimized by avoiding the pixel-by-pixel loop and using ndarray's vectorized operations on a view of the raw image data. This will improve performance, especially for larger images.

pub fn to_tensor_no_norm(image: &DynamicImage) -> Array3<f32> {
    let rgb = image.to_rgb8();
    let (h, w) = (rgb.height() as usize, rgb.width() as usize);
    let raw_data = rgb.into_raw();

    // Create a view of shape [h, w, 3], permute to [3, h, w], then map to f32
    ndarray::ArrayView::from_shape((h, w, 3), &raw_data)
        .expect("Image buffer should match dimensions")
        .permuted_axes([2, 0, 1])
        .mapv(|&x| x as f32)
}

Comment on lines +184 to +187
return Err(TransformError::InvalidShape {
expected: format!("[{}, {}, {}]", c, h, w),
actual: tensor.shape().to_vec(),
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

When checking for inconsistent tensor shapes, the function returns a TransformError::InvalidShape. However, there is a more specific and descriptive error variant, TransformError::InconsistentShapes, available in the same enum. Using the more specific variant would improve error handling clarity and make debugging easier.

            return Err(TransformError::InconsistentShapes);

@slin1237 slin1237 merged commit 58ac3f3 into main Dec 3, 2025
51 of 54 checks passed
@slin1237 slin1237 deleted the smg-mm-2/n branch December 3, 2025 08:04
yingluosanqian pushed a commit to yingluosanqian/sglang that referenced this pull request Dec 4, 2025
tonyluj pushed a commit to openanolis/sglang that referenced this pull request Dec 5, 2025
tonyluj pushed a commit to openanolis/sglang that referenced this pull request Dec 5, 2025
yuchengz816-bot pushed a commit to yuchengz816-bot/sglang that referenced this pull request Dec 8, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

Comments