Skip to content

Conversation

@The-truthh
Copy link
Contributor

@The-truthh The-truthh commented Oct 30, 2025

What does this PR do?

Add

  • add models of eomt and timesfm;
    • mindone.transformers.models.eomt
    • mindone.transformers.models.timesfm
  • add UTs of above models and all passed.

Limitation

FP16 is not supported in timesfm due to the occurrence of NaN values in its outputs.

Usage

  • eomt
import matplotlib.pyplot as plt
import requests
import mindspore as ms
from PIL import Image

from mindone.transformers import EomtForUniversalSegmentation, AutoImageProcessor


model_id = "tue-mps/ade20k_semantic_eomt_large_512"
processor = AutoImageProcessor.from_pretrained(model_id)
model = EomtForUniversalSegmentation.from_pretrained(model_id)

image = Image.open(requests.get("http://images.cocodataset.org/val2017/000000039769.jpg", stream=True).raw)

inputs = processor(
    images=image,
    return_tensors="ms",
)

outputs = model(**inputs)

# Prepare the original image size in the format (height, width)
target_sizes = [(image.height, image.width)]

# Post-process the model outputs to get final segmentation prediction
preds = processor.post_process_semantic_segmentation(
    outputs,
    target_sizes=target_sizes,
)

# Visualize the segmentation mask
plt.imshow(preds[0])
plt.axis("off")
plt.title("Semantic Segmentation")
plt.show()
  • timesfm
from mindone.transformers import TimesFmModelForPrediction
import mindspore as ms
from mindspore import mint

model = TimesFmModelForPrediction.from_pretrained("google/timesfm-2.0-500m-pytorch")

forecast_input = [mint.linspace(0, 20, 100).sin(), mint.linspace(0, 20, 200).sin(), mint.linspace(0, 20, 400).sin()]
frequency_input = ms.tensor([0, 1, 2], dtype=ms.int64)

# Generate
outputs = model(past_values=forecast_input, freq=frequency_input, return_dict=True)
point_forecast_conv = outputs.mean_predictions
quantile_forecast_conv = outputs.full_predictions

Performance

model mode speed weight loading
eomt pynative 0.94s 17.43s
timesfm pynative 0.77s 42.17s

Before submitting

  • This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
  • Did you read the contributor guideline?
  • Did you make sure to update the documentation with your changes? E.g. record bug fixes or new features in What's New. Here are the
    documentation guidelines
  • Did you build and run the code without any errors?
  • Did you report the running environment (NPU type/MS version) and performance in the doc? (better record it for data loading, model inference, or training tasks)
  • Did you write any new necessary tests?

Who can review?

Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.

@xxx

@The-truthh The-truthh requested a review from vigo999 as a code owner October 30, 2025 03:03
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @The-truthh, 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 significantly expands the mindone/transformers library by integrating the EoMT (Efficient and Optimal Multi-task Transformer) family of models. It introduces a complete set of components for universal segmentation, including the core EomtForUniversalSegmentation model, specialized image processors for data preparation and result interpretation, and a robust testing framework. This addition enhances the library's capacity for advanced computer vision tasks, particularly in the domain of image segmentation.

Highlights

  • New EoMT Models: Introduction of EomtPreTrainedModel and EomtForUniversalSegmentation for universal segmentation tasks, expanding the library's model offerings.
  • Image Processors: Addition of EomtImageProcessor and its faster counterpart EomtImageProcessorFast for efficient image preprocessing and post-processing of segmentation outputs.
  • MindSpore Integration: The new models and processors are implemented using MindSpore, extending the framework's capabilities within the mindone/transformers library.
  • Comprehensive Testing: A dedicated test suite test_modeling_eomt.py has been added to ensure the correctness and numerical stability of the new EoMT model across different data types and execution modes.
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.

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 introduces the EoMT model, including its modeling files and image processors. The implementation appears to be a port from the Hugging Face Transformers library. While the overall structure is good, there are several critical issues that need to be addressed. These include incorrect API usage when porting from PyTorch to MindSpore, such as using .copy_() and calling linear_sum_assignment with a tensor instead of a NumPy array, which will lead to runtime errors. I've also identified several incorrect type hints and unsafe dictionary access patterns. My review provides specific suggestions to fix these bugs and improve the code's correctness and robustness.

Comment on lines +214 to +221
masks, classes = convert_segmentation_map_to_binary_masks(
segmentation_map,
instance_id,
ignore_index=ignore_index,
)
Copy link
Contributor

Choose a reason for hiding this comment

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

critical

The convert_segmentation_map_to_binary_masks function expects a NumPy array for the segmentation_map argument, but it is being passed a MindSpore tensor. This will cause a runtime error. You need to convert the tensor to a NumPy array using .asnumpy() before passing it to the function.

Suggested change
masks, classes = convert_segmentation_map_to_binary_masks(
segmentation_map,
instance_id,
ignore_index=ignore_index,
)
masks, classes = convert_segmentation_map_to_binary_masks(
segmentation_map.asnumpy(),
instance_id,
ignore_index=ignore_index,
)

cost_matrix = mint.maximum(cost_matrix, ms.tensor(-1e10))
cost_matrix = mint.nan_to_num(cost_matrix, 0)
# do the assignment using the hungarian algorithm in scipy
assigned_indices: tuple[np.array] = linear_sum_assignment(cost_matrix)
Copy link
Contributor

Choose a reason for hiding this comment

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

critical

The scipy.optimize.linear_sum_assignment function requires a NumPy array as input, but cost_matrix is a MindSpore tensor. This will cause a runtime error. You must convert cost_matrix to a NumPy array using .asnumpy() before the function call.

Suggested change
assigned_indices: tuple[np.array] = linear_sum_assignment(cost_matrix)
assigned_indices: tuple[np.array] = linear_sum_assignment(cost_matrix.asnumpy())

padding_masks = mint.ones((batch_size, height, width), dtype=ms.bool_)
# pad the tensors to the size of the biggest one
for tensor, padded_tensor, padding_mask in zip(tensors, padded_tensors, padding_masks):
padded_tensor[: tensor.shape[0], : tensor.shape[1], : tensor.shape[2]].copy_(tensor)
Copy link
Contributor

Choose a reason for hiding this comment

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

critical

The .copy_() method is an in-place operation from PyTorch and is not available for MindSpore tensors. The equivalent operation in MindSpore can be achieved using slice assignment.

Suggested change
padded_tensor[: tensor.shape[0], : tensor.shape[1], : tensor.shape[2]].copy_(tensor)
padded_tensor[: tensor.shape[0], : tensor.shape[1], : tensor.shape[2]] = tensor

def get_target_size(size_dict: dict[str, int]) -> tuple[int, int]:
"""Returns the height and width from a size dict."""
target_height = size_dict["shortest_edge"]
target_width = size_dict["longest_edge"] or target_height
Copy link
Contributor

Choose a reason for hiding this comment

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

high

Directly accessing size_dict["longest_edge"] is unsafe and will raise a KeyError if the key is not present. It's better to use the .get() method with a fallback value to handle this case gracefully, similar to the implementation in image_processing_eomt.py.

Suggested change
target_width = size_dict["longest_edge"] or target_height
target_width = size_dict.get("longest_edge") or target_height

Comment on lines +14 to +19
from .image_processing_eomt import *
from .image_processing_eomt_fast import *
from .modeling_eomt import *
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

Using wildcard imports (*) is generally discouraged as it can lead to namespace pollution and makes it difficult to trace where symbols are defined. It's better to explicitly import the names that are intended to be part of the module's public API. This also aligns with the convention used in other model directories within this project.

Suggested change
from .image_processing_eomt import *
from .image_processing_eomt_fast import *
from .modeling_eomt import *
from .image_processing_eomt import EomtImageProcessor
from .image_processing_eomt_fast import EomtImageProcessorFast
from .modeling_eomt import EomtForUniversalSegmentation, EomtPreTrainedModel
__all__ = ["EomtImageProcessor", "EomtImageProcessorFast", "EomtForUniversalSegmentation", "EomtPreTrainedModel"]

resample: PILImageResampling = None,
data_format: Union[str, ChannelDimension] = None,
input_data_format: Optional[Union[str, ChannelDimension]] = None,
) -> np.ndarray:
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 return type hint for _preprocess_mask is np.ndarray, but the function returns a ms.Tensor. The type hint should be corrected to ms.Tensor.

Suggested change
) -> np.ndarray:
) -> ms.Tensor:

Comment on lines +674 to +679
(`bool`, *optional*, defaults to `True`):
Whether or not to pad images up to the largest image in a batch and create a pixel mask.

If left to the default, will return a pixel mask that is:

- 1 for pixels that are real (i.e. **not masked**),
- 0 for pixels that are padding (i.e. **masked**).

Copy link
Contributor

Choose a reason for hiding this comment

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

medium

This block of the docstring appears to be a copy-paste artifact, as it describes a parameter that does not exist in the function signature. It should be removed to avoid confusion.

def __init__(self, **kwargs: Unpack[EomtImageProcessorFastKwargs]):
super().__init__(**kwargs)

def _split_image(self, images: ms.Tensor, size: dict, image_indices: int) -> tuple[list, list]:
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 type hint for image_indices is int, but it is used as a sequence on line 133 (image_indices[batch_idx]). The type hint should be corrected to list[int] or a more general sequence type to reflect its actual usage.

Suggested change
def _split_image(self, images: ms.Tensor, size: dict, image_indices: int) -> tuple[list, list]:
def _split_image(self, images: ms.Tensor, size: dict, image_indices: list[int]) -> tuple[list, list]:

self,
outputs,
target_sizes: list[tuple[int, int]],
threshold: float = 0.8,
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 default threshold of 0.8 for instance segmentation is unusually high and likely a copy-paste error from the panoptic segmentation function. A more standard default value for instance segmentation is 0.5. Using a high threshold might lead to valid instances being filtered out.

Suggested change
threshold: float = 0.8,
threshold: float = 0.5,


self.layernorm2d = EomtLayerNorm2d(hidden_size)

def construct(self, hidden_states: ms.tensor) -> ms.Tensor:
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 type hint ms.tensor is incorrect. The correct type for a MindSpore tensor is ms.Tensor (with a capital 'T').

Suggested change
def construct(self, hidden_states: ms.tensor) -> ms.Tensor:
def construct(self, hidden_states: ms.Tensor) -> ms.Tensor:

@The-truthh The-truthh force-pushed the transformers-eomt branch 5 times, most recently from a2c5348 to 24b9b17 Compare November 3, 2025 09:14
@The-truthh The-truthh changed the title feat(transformers/models): add models of eomt feat(transformers/models): add models of eomt and timesfm Nov 4, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant