跳转至

sam

mindnlp.transformers.models.sam.configuration_sam

SAM model configuration

mindnlp.transformers.models.sam.configuration_sam.SamConfig

Bases: PretrainedConfig

[SamConfig] is the configuration class to store the configuration of a [SamModel]. It is used to instantiate a SAM model according to the specified arguments, defining the vision model, prompt-encoder model and mask decoder configs. Instantiating a configuration with the defaults will yield a similar configuration to that of the SAM-ViT-H facebook/sam-vit-huge architecture.

Configuration objects inherit from [PretrainedConfig] and can be used to control the model outputs. Read the documentation from [PretrainedConfig] for more information.

PARAMETER DESCRIPTION
vision_config

Dictionary of configuration options used to initialize [SamVisionConfig].

TYPE: Union[`dict`, `SamVisionConfig`], *optional* DEFAULT: None

prompt_encoder_config

Dictionary of configuration options used to initialize [SamPromptEncoderConfig].

TYPE: Union[`dict`, `SamPromptEncoderConfig`], *optional* DEFAULT: None

mask_decoder_config

Dictionary of configuration options used to initialize [SamMaskDecoderConfig].

TYPE: Union[`dict`, `SamMaskDecoderConfig`], *optional* DEFAULT: None

kwargs

Dictionary of keyword arguments.

TYPE: *optional* DEFAULT: {}

Example
>>> from transformers import (
...     SamVisionConfig,
...     SamPromptEncoderConfig,
...     SamMaskDecoderConfig,
...     SamModel,
... )
...
>>> # Initializing a SamConfig with `"facebook/sam-vit-huge"` style configuration
>>> configuration = SamConfig()
...
>>> # Initializing a SamModel (with random weights) from the `"facebook/sam-vit-huge"` style configuration
>>> model = SamModel(configuration)
...
>>> # Accessing the model configuration
>>> configuration = model.config
...
>>> # We can also initialize a SamConfig from a SamVisionConfig, SamPromptEncoderConfig, and SamMaskDecoderConfig
...
>>> # Initializing SAM vision, SAM Q-Former and language model configurations
>>> vision_config = SamVisionConfig()
>>> prompt_encoder_config = SamPromptEncoderConfig()
>>> mask_decoder_config = SamMaskDecoderConfig()

>>> config = SamConfig(vision_config, prompt_encoder_config, mask_decoder_config)
Source code in mindnlp\transformers\models\sam\configuration_sam.py
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
class SamConfig(PretrainedConfig):
    r"""
    [`SamConfig`] is the configuration class to store the configuration of a [`SamModel`]. It is used to instantiate a
    SAM model according to the specified arguments, defining the vision model, prompt-encoder model and mask decoder
    configs. Instantiating a configuration with the defaults will yield a similar configuration to that of the
    SAM-ViT-H [facebook/sam-vit-huge](https://huggingface.co/facebook/sam-vit-huge) architecture.

    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
    documentation from [`PretrainedConfig`] for more information.

    Args:
        vision_config (Union[`dict`, `SamVisionConfig`], *optional*):
            Dictionary of configuration options used to initialize [`SamVisionConfig`].
        prompt_encoder_config (Union[`dict`, `SamPromptEncoderConfig`], *optional*):
            Dictionary of configuration options used to initialize [`SamPromptEncoderConfig`].
        mask_decoder_config (Union[`dict`, `SamMaskDecoderConfig`], *optional*):
            Dictionary of configuration options used to initialize [`SamMaskDecoderConfig`].

        kwargs (*optional*):
            Dictionary of keyword arguments.

    Example:
        ```python
        >>> from transformers import (
        ...     SamVisionConfig,
        ...     SamPromptEncoderConfig,
        ...     SamMaskDecoderConfig,
        ...     SamModel,
        ... )
        ...
        >>> # Initializing a SamConfig with `"facebook/sam-vit-huge"` style configuration
        >>> configuration = SamConfig()
        ...
        >>> # Initializing a SamModel (with random weights) from the `"facebook/sam-vit-huge"` style configuration
        >>> model = SamModel(configuration)
        ...
        >>> # Accessing the model configuration
        >>> configuration = model.config
        ...
        >>> # We can also initialize a SamConfig from a SamVisionConfig, SamPromptEncoderConfig, and SamMaskDecoderConfig
        ...
        >>> # Initializing SAM vision, SAM Q-Former and language model configurations
        >>> vision_config = SamVisionConfig()
        >>> prompt_encoder_config = SamPromptEncoderConfig()
        >>> mask_decoder_config = SamMaskDecoderConfig()

        >>> config = SamConfig(vision_config, prompt_encoder_config, mask_decoder_config)
        ```
    """
    model_type = "sam"

    def __init__(
        self,
        vision_config=None,
        prompt_encoder_config=None,
        mask_decoder_config=None,
        initializer_range=0.02,
        **kwargs,
    ):
        """
        Initializes a new instance of the SamConfig class.

        Args:
            self: The current instance of the SamConfig class.
            vision_config (SamVisionConfig or None): The configuration for vision. If provided,
                it should be an instance of SamVisionConfig. Defaults to None.
            prompt_encoder_config (SamPromptEncoderConfig or None): The configuration for prompt encoder.
                If provided, it should be an instance of SamPromptEncoderConfig. Defaults to None.
            mask_decoder_config (SamMaskDecoderConfig or None): The configuration for mask decoder.
                If provided, it should be an instance of SamMaskDecoderConfig. Defaults to None.
            initializer_range (float): The range for weight initialization. Defaults to 0.02.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__(**kwargs)
        vision_config = vision_config if vision_config is not None else {}
        prompt_encoder_config = prompt_encoder_config if prompt_encoder_config is not None else {}
        mask_decoder_config = mask_decoder_config if mask_decoder_config is not None else {}

        if isinstance(vision_config, SamVisionConfig):
            vision_config = vision_config.to_dict()
        if isinstance(prompt_encoder_config, SamPromptEncoderConfig):
            prompt_encoder_config = prompt_encoder_config.to_dict()
        if isinstance(mask_decoder_config, SamMaskDecoderConfig):
            mask_decoder_config = mask_decoder_config.to_dict()

        self.vision_config = SamVisionConfig(**vision_config)
        self.prompt_encoder_config = SamPromptEncoderConfig(**prompt_encoder_config)
        self.mask_decoder_config = SamMaskDecoderConfig(**mask_decoder_config)
        self.initializer_range = initializer_range

mindnlp.transformers.models.sam.configuration_sam.SamConfig.__init__(vision_config=None, prompt_encoder_config=None, mask_decoder_config=None, initializer_range=0.02, **kwargs)

Initializes a new instance of the SamConfig class.

PARAMETER DESCRIPTION
self

The current instance of the SamConfig class.

vision_config

The configuration for vision. If provided, it should be an instance of SamVisionConfig. Defaults to None.

TYPE: SamVisionConfig or None DEFAULT: None

prompt_encoder_config

The configuration for prompt encoder. If provided, it should be an instance of SamPromptEncoderConfig. Defaults to None.

TYPE: SamPromptEncoderConfig or None DEFAULT: None

mask_decoder_config

The configuration for mask decoder. If provided, it should be an instance of SamMaskDecoderConfig. Defaults to None.

TYPE: SamMaskDecoderConfig or None DEFAULT: None

initializer_range

The range for weight initialization. Defaults to 0.02.

TYPE: float DEFAULT: 0.02

RETURNS DESCRIPTION

None.

Source code in mindnlp\transformers\models\sam\configuration_sam.py
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
def __init__(
    self,
    vision_config=None,
    prompt_encoder_config=None,
    mask_decoder_config=None,
    initializer_range=0.02,
    **kwargs,
):
    """
    Initializes a new instance of the SamConfig class.

    Args:
        self: The current instance of the SamConfig class.
        vision_config (SamVisionConfig or None): The configuration for vision. If provided,
            it should be an instance of SamVisionConfig. Defaults to None.
        prompt_encoder_config (SamPromptEncoderConfig or None): The configuration for prompt encoder.
            If provided, it should be an instance of SamPromptEncoderConfig. Defaults to None.
        mask_decoder_config (SamMaskDecoderConfig or None): The configuration for mask decoder.
            If provided, it should be an instance of SamMaskDecoderConfig. Defaults to None.
        initializer_range (float): The range for weight initialization. Defaults to 0.02.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__(**kwargs)
    vision_config = vision_config if vision_config is not None else {}
    prompt_encoder_config = prompt_encoder_config if prompt_encoder_config is not None else {}
    mask_decoder_config = mask_decoder_config if mask_decoder_config is not None else {}

    if isinstance(vision_config, SamVisionConfig):
        vision_config = vision_config.to_dict()
    if isinstance(prompt_encoder_config, SamPromptEncoderConfig):
        prompt_encoder_config = prompt_encoder_config.to_dict()
    if isinstance(mask_decoder_config, SamMaskDecoderConfig):
        mask_decoder_config = mask_decoder_config.to_dict()

    self.vision_config = SamVisionConfig(**vision_config)
    self.prompt_encoder_config = SamPromptEncoderConfig(**prompt_encoder_config)
    self.mask_decoder_config = SamMaskDecoderConfig(**mask_decoder_config)
    self.initializer_range = initializer_range

mindnlp.transformers.models.sam.configuration_sam.SamMaskDecoderConfig

Bases: PretrainedConfig

This is the configuration class to store the configuration of a [SamMaskDecoder]. It is used to instantiate a SAM mask decoder to the specified arguments, defining the model architecture. Instantiating a configuration defaults will yield a similar configuration to that of the SAM-vit-h facebook/sam-vit-huge architecture.

Configuration objects inherit from [PretrainedConfig] and can be used to control the model outputs. Read the documentation from [PretrainedConfig] for more information.

PARAMETER DESCRIPTION
hidden_size

Dimensionality of the hidden states.

TYPE: `int`, *optional*, defaults to 256 DEFAULT: 256

hidden_act

The non-linear activation function used inside the SamMaskDecoder module.

TYPE: `str`, *optional*, defaults to `"relu"` DEFAULT: 'relu'

mlp_dim

Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.

TYPE: `int`, *optional*, defaults to 2048 DEFAULT: 2048

num_hidden_layers

Number of hidden layers in the Transformer encoder.

TYPE: `int`, *optional*, defaults to 2 DEFAULT: 2

num_attention_heads

Number of attention heads for each attention layer in the Transformer encoder.

TYPE: `int`, *optional*, defaults to 8 DEFAULT: 8

attention_downsample_rate

The downsampling rate of the attention layer.

TYPE: `int`, *optional*, defaults to 2 DEFAULT: 2

num_multimask_outputs

The number of outputs from the SamMaskDecoder module. In the Segment Anything paper, this is set to 3.

TYPE: `int`, *optional*, defaults to 3 DEFAULT: 3

iou_head_depth

The number of layers in the IoU head module.

TYPE: `int`, *optional*, defaults to 3 DEFAULT: 3

iou_head_hidden_dim

The dimensionality of the hidden states in the IoU head module.

TYPE: `int`, *optional*, defaults to 256 DEFAULT: 256

layer_norm_eps

The epsilon used by the layer normalization layers.

TYPE: `float`, *optional*, defaults to 1e-06 DEFAULT: 1e-06

Source code in mindnlp\transformers\models\sam\configuration_sam.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
class SamMaskDecoderConfig(PretrainedConfig):
    r"""
    This is the configuration class to store the configuration of a [`SamMaskDecoder`]. It is used to instantiate a SAM
    mask decoder to the specified arguments, defining the model architecture. Instantiating a configuration defaults
    will yield a similar configuration to that of the SAM-vit-h
    [facebook/sam-vit-huge](https://huggingface.co/facebook/sam-vit-huge) architecture.

    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
    documentation from [`PretrainedConfig`] for more information.

    Args:
        hidden_size (`int`, *optional*, defaults to 256):
            Dimensionality of the hidden states.
        hidden_act (`str`, *optional*, defaults to `"relu"`):
            The non-linear activation function used inside the `SamMaskDecoder` module.
        mlp_dim (`int`, *optional*, defaults to 2048):
            Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
        num_hidden_layers (`int`, *optional*, defaults to 2):
            Number of hidden layers in the Transformer encoder.
        num_attention_heads (`int`, *optional*, defaults to 8):
            Number of attention heads for each attention layer in the Transformer encoder.
        attention_downsample_rate (`int`, *optional*, defaults to 2):
            The downsampling rate of the attention layer.
        num_multimask_outputs (`int`, *optional*, defaults to 3):
            The number of outputs from the `SamMaskDecoder` module. In the Segment Anything paper, this is set to 3.
        iou_head_depth (`int`, *optional*, defaults to 3):
            The number of layers in the IoU head module.
        iou_head_hidden_dim (`int`, *optional*, defaults to 256):
            The dimensionality of the hidden states in the IoU head module.
        layer_norm_eps (`float`, *optional*, defaults to 1e-06):
            The epsilon used by the layer normalization layers.

    """
    def __init__(
        self,
        hidden_size=256,
        hidden_act="relu",
        mlp_dim=2048,
        num_hidden_layers=2,
        num_attention_heads=8,
        attention_downsample_rate=2,
        num_multimask_outputs=3,
        iou_head_depth=3,
        iou_head_hidden_dim=256,
        layer_norm_eps=1e-6,
        **kwargs,
    ):
        """
        Initializes a new instance of the SamMaskDecoderConfig class.

        Args:
            self: The object itself.
            hidden_size (int, optional): The size of the hidden layer. Default is 256.
            hidden_act (str, optional): The activation function to be used in the hidden layer. Default is 'relu'.
            mlp_dim (int, optional): The dimension of the Multi-Layer Perceptron (MLP). Default is 2048.
            num_hidden_layers (int, optional): The number of hidden layers. Default is 2.
            num_attention_heads (int, optional): The number of attention heads. Default is 8.
            attention_downsample_rate (int, optional): The downsample rate for attention. Default is 2.
            num_multimask_outputs (int, optional): The number of outputs for multimask. Default is 3.
            iou_head_depth (int, optional): The depth of the Intersection over Union (IoU) head. Default is 3.
            iou_head_hidden_dim (int, optional): The hidden dimension of the IoU head. Default is 256.
            layer_norm_eps (float, optional): The epsilon value for layer normalization. Default is 1e-06.

        Returns:
            None

        Raises:
            None
        """
        super().__init__(**kwargs)
        self.hidden_size = hidden_size
        self.hidden_act = hidden_act
        self.mlp_dim = mlp_dim
        self.num_hidden_layers = num_hidden_layers
        self.num_attention_heads = num_attention_heads
        self.attention_downsample_rate = attention_downsample_rate
        self.num_multimask_outputs = num_multimask_outputs
        self.iou_head_depth = iou_head_depth
        self.iou_head_hidden_dim = iou_head_hidden_dim
        self.layer_norm_eps = layer_norm_eps

mindnlp.transformers.models.sam.configuration_sam.SamMaskDecoderConfig.__init__(hidden_size=256, hidden_act='relu', mlp_dim=2048, num_hidden_layers=2, num_attention_heads=8, attention_downsample_rate=2, num_multimask_outputs=3, iou_head_depth=3, iou_head_hidden_dim=256, layer_norm_eps=1e-06, **kwargs)

Initializes a new instance of the SamMaskDecoderConfig class.

PARAMETER DESCRIPTION
self

The object itself.

hidden_size

The size of the hidden layer. Default is 256.

TYPE: int DEFAULT: 256

hidden_act

The activation function to be used in the hidden layer. Default is 'relu'.

TYPE: str DEFAULT: 'relu'

mlp_dim

The dimension of the Multi-Layer Perceptron (MLP). Default is 2048.

TYPE: int DEFAULT: 2048

num_hidden_layers

The number of hidden layers. Default is 2.

TYPE: int DEFAULT: 2

num_attention_heads

The number of attention heads. Default is 8.

TYPE: int DEFAULT: 8

attention_downsample_rate

The downsample rate for attention. Default is 2.

TYPE: int DEFAULT: 2

num_multimask_outputs

The number of outputs for multimask. Default is 3.

TYPE: int DEFAULT: 3

iou_head_depth

The depth of the Intersection over Union (IoU) head. Default is 3.

TYPE: int DEFAULT: 3

iou_head_hidden_dim

The hidden dimension of the IoU head. Default is 256.

TYPE: int DEFAULT: 256

layer_norm_eps

The epsilon value for layer normalization. Default is 1e-06.

TYPE: float DEFAULT: 1e-06

RETURNS DESCRIPTION

None

Source code in mindnlp\transformers\models\sam\configuration_sam.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
def __init__(
    self,
    hidden_size=256,
    hidden_act="relu",
    mlp_dim=2048,
    num_hidden_layers=2,
    num_attention_heads=8,
    attention_downsample_rate=2,
    num_multimask_outputs=3,
    iou_head_depth=3,
    iou_head_hidden_dim=256,
    layer_norm_eps=1e-6,
    **kwargs,
):
    """
    Initializes a new instance of the SamMaskDecoderConfig class.

    Args:
        self: The object itself.
        hidden_size (int, optional): The size of the hidden layer. Default is 256.
        hidden_act (str, optional): The activation function to be used in the hidden layer. Default is 'relu'.
        mlp_dim (int, optional): The dimension of the Multi-Layer Perceptron (MLP). Default is 2048.
        num_hidden_layers (int, optional): The number of hidden layers. Default is 2.
        num_attention_heads (int, optional): The number of attention heads. Default is 8.
        attention_downsample_rate (int, optional): The downsample rate for attention. Default is 2.
        num_multimask_outputs (int, optional): The number of outputs for multimask. Default is 3.
        iou_head_depth (int, optional): The depth of the Intersection over Union (IoU) head. Default is 3.
        iou_head_hidden_dim (int, optional): The hidden dimension of the IoU head. Default is 256.
        layer_norm_eps (float, optional): The epsilon value for layer normalization. Default is 1e-06.

    Returns:
        None

    Raises:
        None
    """
    super().__init__(**kwargs)
    self.hidden_size = hidden_size
    self.hidden_act = hidden_act
    self.mlp_dim = mlp_dim
    self.num_hidden_layers = num_hidden_layers
    self.num_attention_heads = num_attention_heads
    self.attention_downsample_rate = attention_downsample_rate
    self.num_multimask_outputs = num_multimask_outputs
    self.iou_head_depth = iou_head_depth
    self.iou_head_hidden_dim = iou_head_hidden_dim
    self.layer_norm_eps = layer_norm_eps

mindnlp.transformers.models.sam.configuration_sam.SamPromptEncoderConfig

Bases: PretrainedConfig

This is the configuration class to store the configuration of a [SamPromptEncoder]. The [SamPromptEncoder] module is used to encode the input 2D points and bounding boxes. Instantiating a configuration defaults will yield a similar configuration to that of the SAM-vit-h facebook/sam-vit-huge architecture.

Configuration objects inherit from [PretrainedConfig] and can be used to control the model outputs. Read the documentation from [PretrainedConfig] for more information.

PARAMETER DESCRIPTION
hidden_size

Dimensionality of the hidden states.

TYPE: `int`, *optional*, defaults to 256 DEFAULT: 256

image_size

The expected output resolution of the image.

TYPE: `int`, *optional*, defaults to 1024 DEFAULT: 1024

patch_size

The size (resolution) of each patch.

TYPE: `int`, *optional*, defaults to 16 DEFAULT: 16

mask_input_channels

The number of channels to be fed to the MaskDecoder module.

TYPE: `int`, *optional*, defaults to 16 DEFAULT: 16

num_point_embeddings

The number of point embeddings to be used.

TYPE: `int`, *optional*, defaults to 4 DEFAULT: 4

hidden_act

The non-linear activation function in the encoder and pooler.

TYPE: `str`, *optional*, defaults to `"gelu"` DEFAULT: 'gelu'

Source code in mindnlp\transformers\models\sam\configuration_sam.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
class SamPromptEncoderConfig(PretrainedConfig):
    r"""
    This is the configuration class to store the configuration of a [`SamPromptEncoder`]. The [`SamPromptEncoder`]
    module is used to encode the input 2D points and bounding boxes. Instantiating a configuration defaults will yield
    a similar configuration to that of the SAM-vit-h
    [facebook/sam-vit-huge](https://huggingface.co/facebook/sam-vit-huge) architecture.

    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
    documentation from [`PretrainedConfig`] for more information.

    Args:
        hidden_size (`int`, *optional*, defaults to 256):
            Dimensionality of the hidden states.
        image_size (`int`, *optional*, defaults to 1024):
            The expected output resolution of the image.
        patch_size (`int`, *optional*, defaults to 16):
            The size (resolution) of each patch.
        mask_input_channels (`int`, *optional*, defaults to 16):
            The number of channels to be fed to the `MaskDecoder` module.
        num_point_embeddings (`int`, *optional*, defaults to 4):
            The number of point embeddings to be used.
        hidden_act (`str`, *optional*, defaults to `"gelu"`):
            The non-linear activation function in the encoder and pooler.
    """
    def __init__(
        self,
        hidden_size=256,
        image_size=1024,
        patch_size=16,
        mask_input_channels=16,
        num_point_embeddings=4,
        hidden_act="gelu",
        layer_norm_eps=1e-6,
        **kwargs,
    ):
        """
        Initializes an instance of the SamPromptEncoderConfig class.

        Args:
            self (SamPromptEncoderConfig): The instance of the class itself.
            hidden_size (int, optional): The size of the hidden state. Defaults to 256.
            image_size (int, optional): The size of the input image. Defaults to 1024.
            patch_size (int, optional): The size of each image patch. Defaults to 16.
            mask_input_channels (int, optional): The number of input channels for masking. Defaults to 16.
            num_point_embeddings (int, optional): The number of point embeddings. Defaults to 4.
            hidden_act (str, optional): The activation function for the hidden layers. Defaults to 'gelu'.
            layer_norm_eps (float, optional): The epsilon value for layer normalization. Defaults to 1e-06.

        Returns:
            None

        Raises:
            None
        """
        super().__init__(**kwargs)
        self.hidden_size = hidden_size
        self.image_size = image_size
        self.patch_size = patch_size
        self.image_embedding_size = image_size // patch_size
        self.mask_input_channels = mask_input_channels
        self.num_point_embeddings = num_point_embeddings
        self.hidden_act = hidden_act
        self.layer_norm_eps = layer_norm_eps

mindnlp.transformers.models.sam.configuration_sam.SamPromptEncoderConfig.__init__(hidden_size=256, image_size=1024, patch_size=16, mask_input_channels=16, num_point_embeddings=4, hidden_act='gelu', layer_norm_eps=1e-06, **kwargs)

Initializes an instance of the SamPromptEncoderConfig class.

PARAMETER DESCRIPTION
self

The instance of the class itself.

TYPE: SamPromptEncoderConfig

hidden_size

The size of the hidden state. Defaults to 256.

TYPE: int DEFAULT: 256

image_size

The size of the input image. Defaults to 1024.

TYPE: int DEFAULT: 1024

patch_size

The size of each image patch. Defaults to 16.

TYPE: int DEFAULT: 16

mask_input_channels

The number of input channels for masking. Defaults to 16.

TYPE: int DEFAULT: 16

num_point_embeddings

The number of point embeddings. Defaults to 4.

TYPE: int DEFAULT: 4

hidden_act

The activation function for the hidden layers. Defaults to 'gelu'.

TYPE: str DEFAULT: 'gelu'

layer_norm_eps

The epsilon value for layer normalization. Defaults to 1e-06.

TYPE: float DEFAULT: 1e-06

RETURNS DESCRIPTION

None

Source code in mindnlp\transformers\models\sam\configuration_sam.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
def __init__(
    self,
    hidden_size=256,
    image_size=1024,
    patch_size=16,
    mask_input_channels=16,
    num_point_embeddings=4,
    hidden_act="gelu",
    layer_norm_eps=1e-6,
    **kwargs,
):
    """
    Initializes an instance of the SamPromptEncoderConfig class.

    Args:
        self (SamPromptEncoderConfig): The instance of the class itself.
        hidden_size (int, optional): The size of the hidden state. Defaults to 256.
        image_size (int, optional): The size of the input image. Defaults to 1024.
        patch_size (int, optional): The size of each image patch. Defaults to 16.
        mask_input_channels (int, optional): The number of input channels for masking. Defaults to 16.
        num_point_embeddings (int, optional): The number of point embeddings. Defaults to 4.
        hidden_act (str, optional): The activation function for the hidden layers. Defaults to 'gelu'.
        layer_norm_eps (float, optional): The epsilon value for layer normalization. Defaults to 1e-06.

    Returns:
        None

    Raises:
        None
    """
    super().__init__(**kwargs)
    self.hidden_size = hidden_size
    self.image_size = image_size
    self.patch_size = patch_size
    self.image_embedding_size = image_size // patch_size
    self.mask_input_channels = mask_input_channels
    self.num_point_embeddings = num_point_embeddings
    self.hidden_act = hidden_act
    self.layer_norm_eps = layer_norm_eps

mindnlp.transformers.models.sam.configuration_sam.SamVisionConfig

Bases: PretrainedConfig

This is the configuration class to store the configuration of a [SamVisionModel]. It is used to instantiate a SAM vision encoder according to the specified arguments, defining the model architecture. Instantiating a configuration defaults will yield a similar configuration to that of the SAM ViT-h facebook/sam-vit-huge architecture.

Configuration objects inherit from [PretrainedConfig] and can be used to control the model outputs. Read the documentation from [PretrainedConfig] for more information.

PARAMETER DESCRIPTION
hidden_size

Dimensionality of the encoder layers and the pooler layer.

TYPE: `int`, *optional*, defaults to 768 DEFAULT: 768

output_channels

Dimensionality of the output channels in the Patch Encoder.

TYPE: `int`, *optional*, defaults to 256 DEFAULT: 256

num_hidden_layers

Number of hidden layers in the Transformer encoder.

TYPE: `int`, *optional*, defaults to 12 DEFAULT: 12

num_attention_heads

Number of attention heads for each attention layer in the Transformer encoder.

TYPE: `int`, *optional*, defaults to 12 DEFAULT: 12

num_channels

Number of channels in the input image.

TYPE: `int`, *optional*, defaults to 3 DEFAULT: 3

image_size

Expected resolution. Target size of the resized input image.

TYPE: `int`, *optional*, defaults to 1024 DEFAULT: 1024

patch_size

Size of the patches to be extracted from the input image.

TYPE: `int`, *optional*, defaults to 16 DEFAULT: 16

hidden_act

The non-linear activation function (function or string)

TYPE: `str`, *optional*, defaults to `"gelu"` DEFAULT: 'gelu'

layer_norm_eps

The epsilon used by the layer normalization layers.

TYPE: `float`, *optional*, defaults to 1e-06 DEFAULT: 1e-06

attention_dropout

The dropout ratio for the attention probabilities.

TYPE: `float`, *optional*, defaults to 0.0 DEFAULT: 0.0

initializer_range

The standard deviation of the truncated_normal_initializer for initializing all weight matrices.

TYPE: `float`, *optional*, defaults to 1e-10 DEFAULT: 1e-10

qkv_bias

Whether to add a bias to query, key, value projections.

TYPE: `bool`, *optional*, defaults to `True` DEFAULT: True

mlp_ratio

Ratio of mlp hidden dim to embedding dim.

TYPE: `float`, *optional*, defaults to 4.0 DEFAULT: 4.0

use_abs_pos

Whether to use absolute position embedding.

TYPE: `bool`, *optional*, defaults to `True` DEFAULT: True

use_rel_pos

Whether to use relative position embedding.

TYPE: `bool`, *optional*, defaults to `True` DEFAULT: True

window_size

Window size for relative position.

TYPE: `int`, *optional*, defaults to 14 DEFAULT: 14

global_attn_indexes

The indexes of the global attention layers.

TYPE: `List[int]`, *optional*, defaults to `[2, 5, 8, 11]` DEFAULT: [2, 5, 8, 11]

num_pos_feats

The dimensionality of the position embedding.

TYPE: `int`, *optional*, defaults to 128 DEFAULT: 128

mlp_dim

The dimensionality of the MLP layer in the Transformer encoder. If None, defaults to mlp_ratio * hidden_size.

TYPE: `int`, *optional* DEFAULT: None

Source code in mindnlp\transformers\models\sam\configuration_sam.py
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
class SamVisionConfig(PretrainedConfig):
    r"""
    This is the configuration class to store the configuration of a [`SamVisionModel`]. It is used to instantiate a SAM
    vision encoder according to the specified arguments, defining the model architecture. Instantiating a configuration
    defaults will yield a similar configuration to that of the SAM ViT-h
    [facebook/sam-vit-huge](https://huggingface.co/facebook/sam-vit-huge) architecture.

    Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
    documentation from [`PretrainedConfig`] for more information.

    Args:
        hidden_size (`int`, *optional*, defaults to 768):
            Dimensionality of the encoder layers and the pooler layer.
        output_channels (`int`, *optional*, defaults to 256):
            Dimensionality of the output channels in the Patch Encoder.
        num_hidden_layers (`int`, *optional*, defaults to 12):
            Number of hidden layers in the Transformer encoder.
        num_attention_heads (`int`, *optional*, defaults to 12):
            Number of attention heads for each attention layer in the Transformer encoder.
        num_channels (`int`, *optional*, defaults to 3):
            Number of channels in the input image.
        image_size (`int`, *optional*, defaults to 1024):
            Expected resolution. Target size of the resized input image.
        patch_size (`int`, *optional*, defaults to 16):
            Size of the patches to be extracted from the input image.
        hidden_act (`str`, *optional*, defaults to `"gelu"`):
            The non-linear activation function (function or string)
        layer_norm_eps (`float`, *optional*, defaults to 1e-06):
            The epsilon used by the layer normalization layers.
        attention_dropout (`float`, *optional*, defaults to 0.0):
            The dropout ratio for the attention probabilities.
        initializer_range (`float`, *optional*, defaults to 1e-10):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
        qkv_bias (`bool`, *optional*, defaults to `True`):
            Whether to add a bias to query, key, value projections.
        mlp_ratio (`float`, *optional*, defaults to 4.0):
            Ratio of mlp hidden dim to embedding dim.
        use_abs_pos (`bool`, *optional*, defaults to `True`):
            Whether to use absolute position embedding.
        use_rel_pos (`bool`, *optional*, defaults to `True`):
            Whether to use relative position embedding.
        window_size (`int`, *optional*, defaults to 14):
            Window size for relative position.
        global_attn_indexes (`List[int]`, *optional*, defaults to `[2, 5, 8, 11]`):
            The indexes of the global attention layers.
        num_pos_feats (`int`, *optional*, defaults to 128):
            The dimensionality of the position embedding.
        mlp_dim (`int`, *optional*):
            The dimensionality of the MLP layer in the Transformer encoder. If `None`, defaults to `mlp_ratio *
            hidden_size`.
    """
    def __init__(
        self,
        hidden_size=768,
        output_channels=256,
        num_hidden_layers=12,
        num_attention_heads=12,
        num_channels=3,
        image_size=1024,
        patch_size=16,
        hidden_act="gelu",
        layer_norm_eps=1e-06,
        attention_dropout=0.0,
        initializer_range=1e-10,
        qkv_bias=True,
        mlp_ratio=4.0,
        use_abs_pos=True,
        use_rel_pos=True,
        window_size=14,
        global_attn_indexes=[2, 5, 8, 11],
        num_pos_feats=128,
        mlp_dim=None,
        **kwargs,
    ):
        """
        Initializes an instance of the SamVisionConfig class.

        Args:
            self: The object instance.
            hidden_size (int, optional): The size of the hidden state. Defaults to 768.
            output_channels (int, optional): The number of output channels. Defaults to 256.
            num_hidden_layers (int, optional): The number of hidden layers. Defaults to 12.
            num_attention_heads (int, optional): The number of attention heads. Defaults to 12.
            num_channels (int, optional): The number of input channels. Defaults to 3.
            image_size (int, optional): The size of the input image. Defaults to 1024.
            patch_size (int, optional): The size of each patch in the image. Defaults to 16.
            hidden_act (str, optional): The activation function for the hidden layers. Defaults to 'gelu'.
            layer_norm_eps (float, optional): The epsilon value for layer normalization. Defaults to 1e-06.
            attention_dropout (float, optional): The dropout rate for the attention mechanism. Defaults to 0.0.
            initializer_range (float, optional): The range for parameter initialization. Defaults to 1e-10.
            qkv_bias (bool, optional): Whether to include bias in the query, key, and value projections. Defaults to True.
            mlp_ratio (float, optional): The ratio of the hidden size to the feed-forward network size. Defaults to 4.0.
            use_abs_pos (bool, optional): Whether to use absolute position embeddings. Defaults to True.
            use_rel_pos (bool, optional): Whether to use relative position embeddings. Defaults to True.
            window_size (int, optional): The size of the attention window. Defaults to 14.
            global_attn_indexes (list[int], optional): The list of indexes for global attention. Defaults to [2, 5, 8, 11].
            num_pos_feats (int, optional): The number of positional features. Defaults to 128.
            mlp_dim (int, optional): The size of the hidden layer in the feed-forward network. If not provided,
                it is calculated as int(hidden_size * mlp_ratio).

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__(**kwargs)

        self.hidden_size = hidden_size
        self.output_channels = output_channels
        self.num_hidden_layers = num_hidden_layers
        self.num_attention_heads = num_attention_heads
        self.num_channels = num_channels
        self.image_size = image_size
        self.patch_size = patch_size
        self.hidden_act = hidden_act
        self.layer_norm_eps = layer_norm_eps
        self.attention_dropout = attention_dropout
        self.initializer_range = initializer_range
        self.qkv_bias = qkv_bias
        self.mlp_ratio = mlp_ratio
        self.use_abs_pos = use_abs_pos
        self.use_rel_pos = use_rel_pos
        self.window_size = window_size
        self.global_attn_indexes = global_attn_indexes
        self.num_pos_feats = num_pos_feats
        self.mlp_dim = int(hidden_size * mlp_ratio) if mlp_dim is None else mlp_dim

mindnlp.transformers.models.sam.configuration_sam.SamVisionConfig.__init__(hidden_size=768, output_channels=256, num_hidden_layers=12, num_attention_heads=12, num_channels=3, image_size=1024, patch_size=16, hidden_act='gelu', layer_norm_eps=1e-06, attention_dropout=0.0, initializer_range=1e-10, qkv_bias=True, mlp_ratio=4.0, use_abs_pos=True, use_rel_pos=True, window_size=14, global_attn_indexes=[2, 5, 8, 11], num_pos_feats=128, mlp_dim=None, **kwargs)

Initializes an instance of the SamVisionConfig class.

PARAMETER DESCRIPTION
self

The object instance.

hidden_size

The size of the hidden state. Defaults to 768.

TYPE: int DEFAULT: 768

output_channels

The number of output channels. Defaults to 256.

TYPE: int DEFAULT: 256

num_hidden_layers

The number of hidden layers. Defaults to 12.

TYPE: int DEFAULT: 12

num_attention_heads

The number of attention heads. Defaults to 12.

TYPE: int DEFAULT: 12

num_channels

The number of input channels. Defaults to 3.

TYPE: int DEFAULT: 3

image_size

The size of the input image. Defaults to 1024.

TYPE: int DEFAULT: 1024

patch_size

The size of each patch in the image. Defaults to 16.

TYPE: int DEFAULT: 16

hidden_act

The activation function for the hidden layers. Defaults to 'gelu'.

TYPE: str DEFAULT: 'gelu'

layer_norm_eps

The epsilon value for layer normalization. Defaults to 1e-06.

TYPE: float DEFAULT: 1e-06

attention_dropout

The dropout rate for the attention mechanism. Defaults to 0.0.

TYPE: float DEFAULT: 0.0

initializer_range

The range for parameter initialization. Defaults to 1e-10.

TYPE: float DEFAULT: 1e-10

qkv_bias

Whether to include bias in the query, key, and value projections. Defaults to True.

TYPE: bool DEFAULT: True

mlp_ratio

The ratio of the hidden size to the feed-forward network size. Defaults to 4.0.

TYPE: float DEFAULT: 4.0

use_abs_pos

Whether to use absolute position embeddings. Defaults to True.

TYPE: bool DEFAULT: True

use_rel_pos

Whether to use relative position embeddings. Defaults to True.

TYPE: bool DEFAULT: True

window_size

The size of the attention window. Defaults to 14.

TYPE: int DEFAULT: 14

global_attn_indexes

The list of indexes for global attention. Defaults to [2, 5, 8, 11].

TYPE: list[int] DEFAULT: [2, 5, 8, 11]

num_pos_feats

The number of positional features. Defaults to 128.

TYPE: int DEFAULT: 128

mlp_dim

The size of the hidden layer in the feed-forward network. If not provided, it is calculated as int(hidden_size * mlp_ratio).

TYPE: int DEFAULT: None

RETURNS DESCRIPTION

None.

Source code in mindnlp\transformers\models\sam\configuration_sam.py
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
def __init__(
    self,
    hidden_size=768,
    output_channels=256,
    num_hidden_layers=12,
    num_attention_heads=12,
    num_channels=3,
    image_size=1024,
    patch_size=16,
    hidden_act="gelu",
    layer_norm_eps=1e-06,
    attention_dropout=0.0,
    initializer_range=1e-10,
    qkv_bias=True,
    mlp_ratio=4.0,
    use_abs_pos=True,
    use_rel_pos=True,
    window_size=14,
    global_attn_indexes=[2, 5, 8, 11],
    num_pos_feats=128,
    mlp_dim=None,
    **kwargs,
):
    """
    Initializes an instance of the SamVisionConfig class.

    Args:
        self: The object instance.
        hidden_size (int, optional): The size of the hidden state. Defaults to 768.
        output_channels (int, optional): The number of output channels. Defaults to 256.
        num_hidden_layers (int, optional): The number of hidden layers. Defaults to 12.
        num_attention_heads (int, optional): The number of attention heads. Defaults to 12.
        num_channels (int, optional): The number of input channels. Defaults to 3.
        image_size (int, optional): The size of the input image. Defaults to 1024.
        patch_size (int, optional): The size of each patch in the image. Defaults to 16.
        hidden_act (str, optional): The activation function for the hidden layers. Defaults to 'gelu'.
        layer_norm_eps (float, optional): The epsilon value for layer normalization. Defaults to 1e-06.
        attention_dropout (float, optional): The dropout rate for the attention mechanism. Defaults to 0.0.
        initializer_range (float, optional): The range for parameter initialization. Defaults to 1e-10.
        qkv_bias (bool, optional): Whether to include bias in the query, key, and value projections. Defaults to True.
        mlp_ratio (float, optional): The ratio of the hidden size to the feed-forward network size. Defaults to 4.0.
        use_abs_pos (bool, optional): Whether to use absolute position embeddings. Defaults to True.
        use_rel_pos (bool, optional): Whether to use relative position embeddings. Defaults to True.
        window_size (int, optional): The size of the attention window. Defaults to 14.
        global_attn_indexes (list[int], optional): The list of indexes for global attention. Defaults to [2, 5, 8, 11].
        num_pos_feats (int, optional): The number of positional features. Defaults to 128.
        mlp_dim (int, optional): The size of the hidden layer in the feed-forward network. If not provided,
            it is calculated as int(hidden_size * mlp_ratio).

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__(**kwargs)

    self.hidden_size = hidden_size
    self.output_channels = output_channels
    self.num_hidden_layers = num_hidden_layers
    self.num_attention_heads = num_attention_heads
    self.num_channels = num_channels
    self.image_size = image_size
    self.patch_size = patch_size
    self.hidden_act = hidden_act
    self.layer_norm_eps = layer_norm_eps
    self.attention_dropout = attention_dropout
    self.initializer_range = initializer_range
    self.qkv_bias = qkv_bias
    self.mlp_ratio = mlp_ratio
    self.use_abs_pos = use_abs_pos
    self.use_rel_pos = use_rel_pos
    self.window_size = window_size
    self.global_attn_indexes = global_attn_indexes
    self.num_pos_feats = num_pos_feats
    self.mlp_dim = int(hidden_size * mlp_ratio) if mlp_dim is None else mlp_dim

mindnlp.transformers.models.sam.image_processing_sam

Image processor class for SAM.

mindnlp.transformers.models.sam.image_processing_sam.SamImageProcessor

Bases: BaseImageProcessor

Constructs a SAM image processor.

PARAMETER DESCRIPTION
do_resize

Whether to resize the image's (height, width) dimensions to the specified size. Can be overridden by the do_resize parameter in the preprocess method.

TYPE: `bool`, *optional*, defaults to `True` DEFAULT: True

size

Size of the output image after resizing. Resizes the longest edge of the image to match size["longest_edge"] while maintaining the aspect ratio. Can be overridden by the size parameter in the preprocess method.

TYPE: `dict`, *optional*, defaults to `{"longest_edge" -- 1024}` DEFAULT: None

mask_size

Size of the output segmentation map after resizing. Resizes the longest edge of the image to match size["longest_edge"] while maintaining the aspect ratio. Can be overridden by the mask_size parameter in the preprocess method.

TYPE: `dict`, *optional*, defaults to `{"longest_edge" -- 256}` DEFAULT: None

resample

Resampling filter to use if resizing the image. Can be overridden by the resample parameter in the preprocess method.

TYPE: `PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR` DEFAULT: BILINEAR

do_rescale

Wwhether to rescale the image by the specified scale rescale_factor. Can be overridden by the do_rescale parameter in the preprocess method.

TYPE: `bool`, *optional*, defaults to `True` DEFAULT: True

rescale_factor

Scale factor to use if rescaling the image. Only has an effect if do_rescale is set to True. Can be overridden by the rescale_factor parameter in the preprocess method.

TYPE: `int` or `float`, *optional*, defaults to `1/255` DEFAULT: 1 / 255

do_normalize

Whether to normalize the image. Can be overridden by the do_normalize parameter in the preprocess method. Can be overridden by the do_normalize parameter in the preprocess method.

TYPE: `bool`, *optional*, defaults to `True` DEFAULT: True

image_mean

Mean to use if normalizing the image. This is a float or list of floats the length of the number of channels in the image. Can be overridden by the image_mean parameter in the preprocess method. Can be overridden by the image_mean parameter in the preprocess method.

TYPE: `float` or `List[float]`, *optional*, defaults to `IMAGENET_DEFAULT_MEAN` DEFAULT: None

image_std

Standard deviation to use if normalizing the image. This is a float or list of floats the length of the number of channels in the image. Can be overridden by the image_std parameter in the preprocess method. Can be overridden by the image_std parameter in the preprocess method.

TYPE: `float` or `List[float]`, *optional*, defaults to `IMAGENET_DEFAULT_STD` DEFAULT: None

do_pad

Whether to pad the image to the specified pad_size. Can be overridden by the do_pad parameter in the preprocess method.

TYPE: `bool`, *optional*, defaults to `True` DEFAULT: True

pad_size

Size of the output image after padding. Can be overridden by the pad_size parameter in the preprocess method.

TYPE: `dict`, *optional*, defaults to `{"height" -- 1024, "width" -- 1024}` DEFAULT: None

mask_pad_size

Size of the output segmentation map after padding. Can be overridden by the mask_pad_size parameter in the preprocess method.

TYPE: `dict`, *optional*, defaults to `{"height" -- 256, "width" -- 256}` DEFAULT: None

do_convert_rgb

Whether to convert the image to RGB.

TYPE: `bool`, *optional*, defaults to `True` DEFAULT: True

Source code in mindnlp\transformers\models\sam\image_processing_sam.py
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
class SamImageProcessor(BaseImageProcessor):
    r"""
    Constructs a SAM image processor.

    Args:
        do_resize (`bool`, *optional*, defaults to `True`):
            Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the
            `do_resize` parameter in the `preprocess` method.
        size (`dict`, *optional*, defaults to `{"longest_edge" -- 1024}`):
            Size of the output image after resizing. Resizes the longest edge of the image to match
            `size["longest_edge"]` while maintaining the aspect ratio. Can be overridden by the `size` parameter in the
            `preprocess` method.
        mask_size (`dict`, *optional*, defaults to `{"longest_edge" -- 256}`):
            Size of the output segmentation map after resizing. Resizes the longest edge of the image to match
            `size["longest_edge"]` while maintaining the aspect ratio. Can be overridden by the `mask_size` parameter
            in the `preprocess` method.
        resample (`PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR`):
            Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
            `preprocess` method.
        do_rescale (`bool`, *optional*, defaults to `True`):
            Wwhether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the
            `do_rescale` parameter in the `preprocess` method.
        rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
            Scale factor to use if rescaling the image. Only has an effect if `do_rescale` is set to `True`. Can be
            overridden by the `rescale_factor` parameter in the `preprocess` method.
        do_normalize (`bool`, *optional*, defaults to `True`):
            Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
            method. Can be overridden by the `do_normalize` parameter in the `preprocess` method.
        image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_DEFAULT_MEAN`):
            Mean to use if normalizing the image. This is a float or list of floats the length of the number of
            channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method. Can be
            overridden by the `image_mean` parameter in the `preprocess` method.
        image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_DEFAULT_STD`):
            Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
            number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
            Can be overridden by the `image_std` parameter in the `preprocess` method.
        do_pad (`bool`, *optional*, defaults to `True`):
            Whether to pad the image to the specified `pad_size`. Can be overridden by the `do_pad` parameter in the
            `preprocess` method.
        pad_size (`dict`, *optional*, defaults to `{"height" -- 1024, "width" -- 1024}`):
            Size of the output image after padding. Can be overridden by the `pad_size` parameter in the `preprocess`
            method.
        mask_pad_size (`dict`, *optional*, defaults to `{"height" -- 256, "width" -- 256}`):
            Size of the output segmentation map after padding. Can be overridden by the `mask_pad_size` parameter in
            the `preprocess` method.
        do_convert_rgb (`bool`, *optional*, defaults to `True`):
            Whether to convert the image to RGB.
    """
    model_input_names = ["pixel_values"]

    def __init__(
        self,
        do_resize: bool = True,
        size: Dict[str, int] = None,
        mask_size: Dict[str, int] = None,
        resample: PILImageResampling = PILImageResampling.BILINEAR,
        do_rescale: bool = True,
        rescale_factor: Union[int, float] = 1 / 255,
        do_normalize: bool = True,
        image_mean: Optional[Union[float, List[float]]] = None,
        image_std: Optional[Union[float, List[float]]] = None,
        do_pad: bool = True,
        pad_size: int = None,
        mask_pad_size: int = None,
        do_convert_rgb: bool = True,
        **kwargs,
    ) -> None:
        """
        Initializes an instance of the SamImageProcessor class.

        Args:
            self: The instance of the class.
            do_resize (bool): Determines whether resizing of images should be performed. Defaults to True.
            size (Dict[str, int]): The desired size of the images. Defaults to {'longest_edge': 1024}.
                The size can be specified as a dictionary with keys 'longest_edge' or 'height' and 'width'.
                If not provided as a dictionary, it is converted to a dictionary with the 'longest_edge' key.
            mask_size (Dict[str, int]): The desired size of the segmentation masks. Defaults to {'longest_edge': 256}.
                The size can be specified as a dictionary with keys 'longest_edge' or 'height' and 'width'.
                If not provided as a dictionary, it is converted to a dictionary with the 'longest_edge' key.
            resample (PILImageResampling): The resampling method to use during image resizing.
                Defaults to PILImageResampling.BILINEAR.
            do_rescale (bool): Determines whether rescaling of pixel values should be performed. Defaults to True.
            rescale_factor (Union[int, float]): The factor to divide pixel values by during rescaling.
                Defaults to 1 / 255.
            do_normalize (bool): Determines whether normalization of pixel values should be performed.
                Defaults to True.
            image_mean (Optional[Union[float, List[float]]]): The mean values to subtract from pixel values
                during normalization. Defaults to None, which uses the IMAGENET_DEFAULT_MEAN.
            image_std (Optional[Union[float, List[float]]]): The standard deviation values to divide pixel values
                by during normalization. Defaults to None, which uses the IMAGENET_DEFAULT_STD.
            do_pad (bool): Determines whether padding of images should be performed. Defaults to True.
            pad_size (int): The desired size of the padded images. Defaults to None,
                which uses {'height': 1024, 'width': 1024}. The size can be specified as a single integer, representing
                both height and width.
            mask_pad_size (int): The desired size of the padded segmentation masks. Defaults to None,
                which uses {'height': 256, 'width': 256}. The size can be specified as a single integer,
                representing both height and width.
            do_convert_rgb (bool): Determines whether conversion to RGB color space should be performed. Defaults to True.
            **kwargs: Additional keyword arguments to be passed to the parent class forwardor.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__(**kwargs)
        size = size if size is not None else {"longest_edge": 1024}
        size = get_size_dict(max_size=size, default_to_square=False) if not isinstance(size, dict) else size

        pad_size = pad_size if pad_size is not None else {"height": 1024, "width": 1024}
        pad_size = get_size_dict(pad_size, default_to_square=True)

        mask_size = mask_size if mask_size is not None else {"longest_edge": 256}
        mask_size = (
            get_size_dict(max_size=mask_size, default_to_square=False)
            if not isinstance(mask_size, dict)
            else mask_size
        )

        mask_pad_size = mask_pad_size if mask_pad_size is not None else {"height": 256, "width": 256}
        mask_pad_size = get_size_dict(mask_pad_size, default_to_square=True)

        self.do_resize = do_resize
        self.size = size
        self.mask_size = mask_size
        self.resample = resample
        self.do_rescale = do_rescale
        self.rescale_factor = rescale_factor
        self.do_normalize = do_normalize
        self.image_mean = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
        self.image_std = image_std if image_std is not None else IMAGENET_DEFAULT_STD
        self.do_pad = do_pad
        self.pad_size = pad_size
        self.mask_pad_size = mask_pad_size
        self.do_convert_rgb = do_convert_rgb
        self._valid_processor_keys = [
            "images",
            "segmentation_maps",
            "do_resize",
            "size",
            "mask_size",
            "resample",
            "do_rescale",
            "rescale_factor",
            "do_normalize",
            "image_mean",
            "image_std",
            "do_pad",
            "pad_size",
            "mask_pad_size",
            "do_convert_rgb",
            "return_tensors",
            "data_format",
            "input_data_format",
        ]

    def pad_image(
        self,
        image: np.ndarray,
        pad_size: Dict[str, int],
        data_format: Optional[Union[str, ChannelDimension]] = None,
        input_data_format: Optional[Union[str, ChannelDimension]] = None,
        **kwargs,
    ) -> np.ndarray:
        """
        Pad an image to `(pad_size["height"], pad_size["width"])` with zeros to the right and bottom.

        Args:
            image (`np.ndarray`):
                Image to pad.
            pad_size (`Dict[str, int]`):
                Size of the output image after padding.
            data_format (`str` or `ChannelDimension`, *optional*):
                The data format of the image. Can be either "channels_first" or "channels_last". If `None`, the
                `data_format` of the `image` will be used.
            input_data_format (`str` or `ChannelDimension`, *optional*):
                The channel dimension format of the input image. If not provided, it will be inferred.
        """
        output_height, output_width = pad_size["height"], pad_size["width"]
        input_height, input_width = get_image_size(image, channel_dim=input_data_format)

        pad_width = output_width - input_width
        pad_height = output_height - input_height

        padded_image = pad(
            image,
            ((0, pad_height), (0, pad_width)),
            data_format=data_format,
            input_data_format=input_data_format,
            **kwargs,
        )
        return padded_image

    def _get_preprocess_shape(self, old_shape: Tuple[int, int], longest_edge: int):
        """
        Compute the output size given input size and target long side length.
        """
        oldh, oldw = old_shape
        scale = longest_edge * 1.0 / max(oldh, oldw)
        newh, neww = oldh * scale, oldw * scale
        newh = int(newh + 0.5)
        neww = int(neww + 0.5)
        return (newh, neww)

    def resize(
        self,
        image: np.ndarray,
        size: Dict[str, int],
        resample: PILImageResampling = PILImageResampling.BICUBIC,
        data_format: Optional[Union[str, ChannelDimension]] = None,
        input_data_format: Optional[Union[str, ChannelDimension]] = None,
        **kwargs,
    ) -> np.ndarray:
        """
        Resize an image to `(size["height"], size["width"])`.

        Args:
            image (`np.ndarray`):
                Image to resize.
            size (`Dict[str, int]`):
                Dictionary in the format `{"longest_edge": int}` specifying the size of the output image. The longest
                edge of the image will be resized to the specified size, while the other edge will be resized to
                maintain the aspect ratio.
            resample:
                `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
            data_format (`ChannelDimension` or `str`, *optional*):
                The channel dimension format for the output image. If unset, the channel dimension format of the input
                image is used. Can be one of:

                - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
                - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
            input_data_format (`ChannelDimension` or `str`, *optional*):
                The channel dimension format for the input image. If unset, the channel dimension format is inferred
                from the input image. Can be one of:

                - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
                - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.

        Returns:
            `np.ndarray`: The resized image.
        """
        size = get_size_dict(size)
        if "longest_edge" not in size:
            raise ValueError(f"The `size` dictionary must contain the key `longest_edge`. Got {size.keys()}")
        input_size = get_image_size(image, channel_dim=input_data_format)
        output_height, output_width = self._get_preprocess_shape(input_size, size["longest_edge"])
        return resize(
            image,
            size=(output_height, output_width),
            resample=resample,
            data_format=data_format,
            input_data_format=input_data_format,
            **kwargs,
        )

    def _preprocess(
        self,
        image: ImageInput,
        do_resize: bool,
        do_rescale: bool,
        do_normalize: bool,
        size: Optional[Dict[str, int]] = None,
        resample: PILImageResampling = None,
        rescale_factor: Optional[float] = None,
        image_mean: Optional[Union[float, List[float]]] = None,
        image_std: Optional[Union[float, List[float]]] = None,
        do_pad: Optional[bool] = None,
        pad_size: Optional[Dict[str, int]] = None,
        input_data_format: Optional[Union[str, ChannelDimension]] = None,
    ):
        '''
        This method preprocesses the input image according to the specified operations such as resizing, rescaling,
        normalization, and padding.

        Args:
            self: The instance of the SamImageProcessor class.
            image (ImageInput): The input image to be preprocessed.
            do_resize (bool): A flag indicating whether to perform resizing on the input image.
            do_rescale (bool): A flag indicating whether to perform rescaling on the input image.
            do_normalize (bool): A flag indicating whether to perform normalization on the input image.
            size (Optional[Dict[str, int]]): The target size for resizing the image in the format
                {'width': int, 'height': int}. Default is None.
            resample (PILImageResampling): The resampling filter to be used during image resizing. Default is None.
            rescale_factor (Optional[float]): The factor by which the image should be rescaled. Default is None.
            image_mean (Optional[Union[float, List[float]]]): The mean value to be used for image normalization.
                It can be a single float value or a list of float values, depending on the input_data_format.
                Default is None.
            image_std (Optional[Union[float, List[float]]]):
                The standard deviation value to be used for image normalization.
                It can be a single float value or a list of float values, depending on the input_data_format.
                Default is None.
            do_pad (Optional[bool]): A flag indicating whether to perform padding on the input image. Default is None.
            pad_size (Optional[Dict[str, int]]): The size of the padding to be applied in the format
                {'top': int, 'bottom': int, 'left': int, 'right': int}. Default is None.
            input_data_format (Optional[Union[str, ChannelDimension]]): The data format of the input image,
                e.g., 'channels_first' or 'channels_last'. Default is None.

        Returns:
            Tuple[ImageInput, Tuple[int, int, int]]: The preprocessed image and the reshaped input size in the format
                (image, (height, width, channels)).

        Raises:
            ValueError: If the input_data_format is invalid or not supported.
            TypeError: If the input_data_format is not a string or ChannelDimension.
        '''
        if do_resize:
            image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
        reshaped_input_size = get_image_size(image, channel_dim=input_data_format)

        if do_rescale:
            image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)

        if do_normalize:
            image = self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)

        if do_pad:
            image = self.pad_image(image=image, pad_size=pad_size, input_data_format=input_data_format)

        return image, reshaped_input_size

    def _preprocess_image(
        self,
        image: ImageInput,
        do_resize: Optional[bool] = None,
        size: Dict[str, int] = None,
        resample: PILImageResampling = None,
        do_rescale: bool = None,
        rescale_factor: Optional[float] = None,
        do_normalize: Optional[bool] = None,
        image_mean: Optional[Union[float, List[float]]] = None,
        image_std: Optional[Union[float, List[float]]] = None,
        do_pad: Optional[bool] = None,
        pad_size: Optional[Dict[str, int]] = None,
        do_convert_rgb: Optional[bool] = None,
        data_format: Optional[Union[str, ChannelDimension]] = None,
        input_data_format: Optional[Union[str, ChannelDimension]] = None,
    ) -> Tuple[np.ndarray, Tuple[int, int], Tuple[int, int]]:
        """
        This method preprocesses the input image with various transformations and returns the processed image,
        original size, and reshaped input size.

        Args:
            self: The instance of the SamImageProcessor class.
            image (ImageInput): The input image to be preprocessed.
            do_resize (Optional[bool]): A flag indicating whether to resize the image. Defaults to None.
            size (Optional[Dict[str, int]]): A dictionary containing the target width and height for resizing the image.
                Defaults to None.
            resample (PILImageResampling): The resampling filter to be used during image resizing.
            do_rescale (Optional[bool]): A flag indicating whether to rescale the image. Defaults to None.
            rescale_factor (Optional[float]): The factor by which to rescale the image. Defaults to None.
            do_normalize (Optional[bool]): A flag indicating whether to normalize the image. Defaults to None.
            image_mean (Optional[Union[float, List[float]]]): The mean values to be used for image normalization.
                Defaults to None.
            image_std (Optional[Union[float, List[float]]]): The standard deviation values to be used for
                image normalization. Defaults to None.
            do_pad (Optional[bool]): A flag indicating whether to pad the image. Defaults to None.
            pad_size (Optional[Dict[str, int]]): A dictionary containing the padding width and height.
                Defaults to None.
            do_convert_rgb (Optional[bool]): A flag indicating whether to convert the image to RGB format.
                Defaults to None.
            data_format (Optional[Union[str, ChannelDimension]]): The desired data format for the processed image.
            input_data_format (Optional[Union[str, ChannelDimension]]): The input data format of the image.

        Returns:
            Tuple[np.ndarray, Tuple[int, int], Tuple[int, int]]: A tuple containing the processed image as a numpy array,
                the original size of the input image, and the reshaped input size after preprocessing.

        Raises:
            None
        """
        image = to_numpy_array(image)

        # PIL RGBA images are converted to RGB
        if do_convert_rgb:
            image = convert_to_rgb(image)

        # All transformations expect numpy arrays.
        image = to_numpy_array(image)

        if is_scaled_image(image) and do_rescale:
            logger.warning_once(
                "It looks like you are trying to rescale already rescaled images. If the input"
                " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
            )

        if input_data_format is None:
            input_data_format = infer_channel_dimension_format(image)

        original_size = get_image_size(image, channel_dim=input_data_format)

        image, reshaped_input_size = self._preprocess(
            image=image,
            do_resize=do_resize,
            size=size,
            resample=resample,
            do_rescale=do_rescale,
            rescale_factor=rescale_factor,
            do_normalize=do_normalize,
            image_mean=image_mean,
            image_std=image_std,
            do_pad=do_pad,
            pad_size=pad_size,
            input_data_format=input_data_format,
        )

        if data_format is not None:
            image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)

        return image, original_size, reshaped_input_size

    def _preprocess_mask(
        self,
        segmentation_map: ImageInput,
        do_resize: Optional[bool] = None,
        mask_size: Dict[str, int] = None,
        do_pad: Optional[bool] = None,
        mask_pad_size: Optional[Dict[str, int]] = None,
        input_data_format: Optional[Union[str, ChannelDimension]] = None,
    ) -> np.ndarray:
        """
        Method to preprocess a segmentation mask.

        Args:
            self: The instance of the SamImageProcessor class.
            segmentation_map (ImageInput): The input segmentation map to be preprocessed.
            do_resize (Optional[bool]): Flag indicating whether resizing should be performed. Default is None.
            mask_size (Dict[str, int]): Dictionary containing the target size for the mask after resizing.
            do_pad (Optional[bool]): Flag indicating whether padding should be applied. Default is None.
            mask_pad_size (Optional[Dict[str, int]]): Dictionary containing the padding size for the mask.
            input_data_format (Optional[Union[str, ChannelDimension]]): Format of the input data. Default is None.

        Returns:
            np.ndarray: The preprocessed segmentation map as a NumPy array.
            original_size: The size of the original segmentation map.

        Raises:
            None
        """
        segmentation_map = to_numpy_array(segmentation_map)

        # Add channel dimension if missing - needed for certain transformations
        if segmentation_map.ndim == 2:
            added_channel_dim = True
            segmentation_map = segmentation_map[None, ...]
            input_data_format = ChannelDimension.FIRST
        else:
            added_channel_dim = False
            if input_data_format is None:
                input_data_format = infer_channel_dimension_format(segmentation_map, num_channels=1)

        original_size = get_image_size(segmentation_map, channel_dim=input_data_format)

        segmentation_map, _ = self._preprocess(
            image=segmentation_map,
            do_resize=do_resize,
            size=mask_size,
            resample=PILImageResampling.NEAREST,
            do_rescale=False,
            do_normalize=False,
            do_pad=do_pad,
            pad_size=mask_pad_size,
            input_data_format=input_data_format,
        )

        # Remove extra channel dimension if added for processing
        if added_channel_dim:
            segmentation_map = segmentation_map.squeeze(0)
        segmentation_map = segmentation_map.astype(np.int64)

        return segmentation_map, original_size

    def preprocess(
        self,
        images: ImageInput,
        segmentation_maps: Optional[ImageInput] = None,
        do_resize: Optional[bool] = None,
        size: Optional[Dict[str, int]] = None,
        mask_size: Optional[Dict[str, int]] = None,
        resample: Optional["PILImageResampling"] = None,
        do_rescale: Optional[bool] = None,
        rescale_factor: Optional[Union[int, float]] = None,
        do_normalize: Optional[bool] = None,
        image_mean: Optional[Union[float, List[float]]] = None,
        image_std: Optional[Union[float, List[float]]] = None,
        do_pad: Optional[bool] = None,
        pad_size: Optional[Dict[str, int]] = None,
        mask_pad_size: Optional[Dict[str, int]] = None,
        do_convert_rgb: Optional[bool] = None,
        return_tensors: Optional[Union[str, TensorType]] = None,
        data_format: ChannelDimension = ChannelDimension.FIRST,
        input_data_format: Optional[Union[str, ChannelDimension]] = None,
        **kwargs,
    ):
        """
        Preprocess an image or batch of images.

        Args:
            images (`ImageInput`):
                Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
                passing in images with pixel values between 0 and 1, set `do_rescale=False`.
            segmentation_maps (`ImageInput`, *optional*):
                Segmentation map to preprocess.
            do_resize (`bool`, *optional*, defaults to `self.do_resize`):
                Whether to resize the image.
            size (`Dict[str, int]`, *optional*, defaults to `self.size`):
                Controls the size of the image after `resize`. The longest edge of the image is resized to
                `size["longest_edge"]` whilst preserving the aspect ratio.
            mask_size (`Dict[str, int]`, *optional*, defaults to `self.mask_size`):
                Controls the size of the segmentation map after `resize`. The longest edge of the image is resized to
                `size["longest_edge"]` whilst preserving the aspect ratio.
            resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
                `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
            do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
                Whether to rescale the image pixel values by rescaling factor.
            rescale_factor (`int` or `float`, *optional*, defaults to `self.rescale_factor`):
                Rescale factor to apply to the image pixel values.
            do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
                Whether to normalize the image.
            image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
                Image mean to normalize the image by if `do_normalize` is set to `True`.
            image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
                Image standard deviation to normalize the image by if `do_normalize` is set to `True`.
            do_pad (`bool`, *optional*, defaults to `self.do_pad`):
                Whether to pad the image.
            pad_size (`Dict[str, int]`, *optional*, defaults to `self.pad_size`):
                Controls the size of the padding applied to the image. The image is padded to `pad_size["height"]` and
                `pad_size["width"]` if `do_pad` is set to `True`.
            mask_pad_size (`Dict[str, int]`, *optional*, defaults to `self.mask_pad_size`):
                Controls the size of the padding applied to the segmentation map. The image is padded to
                `mask_pad_size["height"]` and `mask_pad_size["width"]` if `do_pad` is set to `True`.
            do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
                Whether to convert the image to RGB.
            return_tensors (`str` or `TensorType`, *optional*):
                The type of tensors to return. Can be one of:

                - Unset: Return a list of `np.ndarray`.
                - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
                - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `mindspore.Tensor`.
                - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
                - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
            data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
                The channel dimension format for the output image. Can be one of:

                - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
                - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
                - Unset: Use the channel dimension format of the input image.
            input_data_format (`ChannelDimension` or `str`, *optional*):
                The channel dimension format for the input image. If unset, the channel dimension format is inferred
                from the input image. Can be one of:

                - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
                - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
                - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
        """
        do_resize = do_resize if do_resize is not None else self.do_resize
        size = size if size is not None else self.size
        size = get_size_dict(max_size=size, default_to_square=False) if not isinstance(size, dict) else size
        mask_size = mask_size if mask_size is not None else self.mask_size
        mask_size = (
            get_size_dict(max_size=mask_size, default_to_square=False)
            if not isinstance(mask_size, dict)
            else mask_size
        )
        resample = resample if resample is not None else self.resample
        do_rescale = do_rescale if do_rescale is not None else self.do_rescale
        rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
        do_normalize = do_normalize if do_normalize is not None else self.do_normalize
        image_mean = image_mean if image_mean is not None else self.image_mean
        image_std = image_std if image_std is not None else self.image_std
        do_pad = do_pad if do_pad is not None else self.do_pad
        pad_size = pad_size if pad_size is not None else self.pad_size
        pad_size = get_size_dict(pad_size, default_to_square=True)
        mask_pad_size = mask_pad_size if mask_pad_size is not None else self.mask_pad_size
        mask_pad_size = get_size_dict(mask_pad_size, default_to_square=True)
        do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

        images = make_list_of_images(images)

        validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_processor_keys)

        if not valid_images(images):
            raise ValueError(
                "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
                "mindspore.Tensor, tf.Tensor or jax.ndarray."
            )

        if segmentation_maps is not None:
            segmentation_maps = make_list_of_images(segmentation_maps, expected_ndims=2)

            if not valid_images(segmentation_maps):
                raise ValueError(
                    "Invalid segmentation map type. Must be of type PIL.Image.Image, numpy.ndarray, "
                    "mindspore.Tensor, tf.Tensor or jax.ndarray."
                )
        validate_preprocess_arguments(
            do_rescale=do_rescale,
            rescale_factor=rescale_factor,
            do_normalize=do_normalize,
            image_mean=image_mean,
            image_std=image_std,
            do_pad=do_pad,
            size_divisibility=pad_size,  # Here _preprocess needs do_pad and pad_size.
            do_resize=do_resize,
            size=size,
            resample=resample,
        )

        images, original_sizes, reshaped_input_sizes = zip(
            *(
                self._preprocess_image(
                    image=img,
                    do_resize=do_resize,
                    size=size,
                    resample=resample,
                    do_rescale=do_rescale,
                    rescale_factor=rescale_factor,
                    do_normalize=do_normalize,
                    image_mean=image_mean,
                    image_std=image_std,
                    do_pad=do_pad,
                    pad_size=pad_size,
                    do_convert_rgb=do_convert_rgb,
                    data_format=data_format,
                    input_data_format=input_data_format,
                )
                for img in images
            )
        )

        data = {
            "pixel_values": images,
            "original_sizes": original_sizes,
            "reshaped_input_sizes": reshaped_input_sizes,
        }

        if segmentation_maps is not None:
            segmentation_maps, original_mask_sizes = zip(
                *(
                    self._preprocess_mask(
                        segmentation_map=mask,
                        do_resize=do_resize,
                        mask_size=mask_size,
                        do_pad=do_pad,
                        mask_pad_size=mask_pad_size,
                        input_data_format=input_data_format,
                    )
                    for mask in segmentation_maps
                )
            )

            # masks should start out the same size as input images
            assert all(
                original_im_size == original_mask_size
                for original_im_size, original_mask_size in zip(original_sizes, original_mask_sizes)
            ), "Segmentation maps should be the same size as input images."

            data["labels"] = segmentation_maps

        return BatchFeature(data=data, tensor_type=return_tensors)

    def post_process_masks(
        self,
        masks,
        original_sizes,
        reshaped_input_sizes,
        mask_threshold=0.0,
        binarize=True,
        pad_size=None,
        return_tensors="ms",
    ):
        """
        Remove padding and upscale masks to the original image size.

        Args:
            masks (`Union[List[mindspore.Tensor], List[np.ndarray], List[tf.Tensor]]`):
                Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format.
            original_sizes (`Union[mindspore.Tensor, tf.Tensor, List[Tuple[int,int]]]`):
                The original sizes of each image before it was resized to the model's expected input shape, in (height,
                width) format.
            reshaped_input_sizes (`Union[mindspore.Tensor, tf.Tensor, List[Tuple[int,int]]]`):
                The size of each image as it is fed to the model, in (height, width) format. Used to remove padding.
            mask_threshold (`float`, *optional*, defaults to 0.0):
                The threshold to use for binarizing the masks.
            binarize (`bool`, *optional*, defaults to `True`):
                Whether to binarize the masks.
            pad_size (`int`, *optional*, defaults to `self.pad_size`):
                The target size the images were padded to before being passed to the model. If None, the target size is
                assumed to be the processor's `pad_size`.
            return_tensors (`str`, *optional*, defaults to `"ms"`):
                If `"ms"`, return PyTorch tensors. If `"tf"`, return TensorFlow tensors.

        Returns:
            (`Union[mindspore.Tensor, tf.Tensor]`): Batched masks in batch_size, num_channels, height, width) format, where
            (height, width) is given by original_size.
        """
        if return_tensors == "ms":
            return self._post_process_masks_ms(
                masks=masks,
                original_sizes=original_sizes,
                reshaped_input_sizes=reshaped_input_sizes,
                mask_threshold=mask_threshold,
                binarize=binarize,
                pad_size=pad_size,
            )
        else:
            raise ValueError("return_tensors must be 'ms'.")

    def _post_process_masks_ms(
        self, masks, original_sizes, reshaped_input_sizes, mask_threshold=0.0, binarize=True, pad_size=None
    ):
        """
        Remove padding and upscale masks to the original image size.

        Args:
            masks (`Union[List[mindspore.Tensor], List[np.ndarray]]`):
                Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format.
            original_sizes (`Union[mindspore.Tensor, List[Tuple[int,int]]]`):
                The original sizes of each image before it was resized to the model's expected input shape, in (height,
                width) format.
            reshaped_input_sizes (`Union[mindspore.Tensor, List[Tuple[int,int]]]`):
                The size of each image as it is fed to the model, in (height, width) format. Used to remove padding.
            mask_threshold (`float`, *optional*, defaults to 0.0):
                The threshold to use for binarizing the masks.
            binarize (`bool`, *optional*, defaults to `True`):
                Whether to binarize the masks.
            pad_size (`int`, *optional*, defaults to `self.pad_size`):
                The target size the images were padded to before being passed to the model. If None, the target size is
                assumed to be the processor's `pad_size`.

        Returns:
            (`mindspore.Tensor`): Batched masks in batch_size, num_channels, height, width) format, where (height, width)
            is given by original_size.
        """
        requires_backends(self, ["mindspore"])
        pad_size = self.pad_size if pad_size is None else pad_size
        target_image_size = (pad_size["height"], pad_size["width"])
        if isinstance(original_sizes, (mindspore.Tensor, np.ndarray)):
            original_sizes = original_sizes.tolist()
        if isinstance(reshaped_input_sizes, (mindspore.Tensor, np.ndarray)):
            reshaped_input_sizes = reshaped_input_sizes.tolist()
        output_masks = []
        for i, original_size in enumerate(original_sizes):
            if isinstance(masks[i], np.ndarray):
                masks[i] = mindspore.Tensor(masks[i], dtype=mindspore.float32)
            elif not isinstance(masks[i], mindspore.Tensor):
                raise ValueError("Input masks should be a list of `mindspore.tensors` or a list of `np.ndarray`")
            interpolated_mask = F.interpolate(masks[i], target_image_size, mode="bilinear", align_corners=False)
            interpolated_mask = interpolated_mask[..., : reshaped_input_sizes[i][0], : reshaped_input_sizes[i][1]]
            interpolated_mask = F.interpolate(interpolated_mask, original_size, mode="bilinear", align_corners=False)
            if binarize:
                interpolated_mask = interpolated_mask > mask_threshold
            output_masks.append(interpolated_mask)

        return output_masks

    def post_process_for_mask_generation(
        self, all_masks, all_scores, all_boxes, crops_nms_thresh, return_tensors="ms"
    ):
        """
        Post processes mask that are generated by calling the Non Maximum Suppression algorithm on the predicted masks.

        Args:
            all_masks (`Union[List[mindspore.Tensor], List[tf.Tensor]]`):
                List of all predicted segmentation masks
            all_scores (`Union[List[mindspore.Tensor], List[tf.Tensor]]`):
                List of all predicted iou scores
            all_boxes (`Union[List[mindspore.Tensor], List[tf.Tensor]]`):
                List of all bounding boxes of the predicted masks
            crops_nms_thresh (`float`):
                Threshold for NMS (Non Maximum Suppression) algorithm.
            return_tensors (`str`, *optional*, defaults to `pt`):
                If `pt`, returns `mindspore.Tensor`. If `tf`, returns `tf.Tensor`.
        """
        if return_tensors == "ms":
            return _postprocess_for_mg(all_masks, all_scores, all_boxes, crops_nms_thresh)

    def generate_crop_boxes(
        self,
        image,
        target_size,
        crop_n_layers: int = 0,
        overlap_ratio: float = 512 / 1500,
        points_per_crop: Optional[int] = 32,
        crop_n_points_downscale_factor: Optional[List[int]] = 1,
        input_data_format: Optional[Union[str, ChannelDimension]] = None,
        return_tensors: str = "ms",
    ):
        """
        Generates a list of crop boxes of different sizes. Each layer has (2**i)**2 boxes for the ith layer.

        Args:
            image (`np.array`):
                Input original image
            target_size (`int`):
                Target size of the resized image
            crop_n_layers (`int`, *optional*, defaults to 0):
                If >0, mask prediction will be run again on crops of the image. Sets the number of layers to run, where
                each layer has 2**i_layer number of image crops.
            overlap_ratio (`float`, *optional*, defaults to 512/1500):
                Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of
                the image length. Later layers with more crops scale down this overlap.
            points_per_crop (`int`, *optional*, defaults to 32):
                Number of points to sample from each crop.
            crop_n_points_downscale_factor (`List[int]`, *optional*, defaults to 1):
                The number of points-per-side sampled in layer n is scaled down by crop_n_points_downscale_factor**n.
            input_data_format (`str` or `ChannelDimension`, *optional*):
                The channel dimension format of the input image. If not provided, it will be inferred.
            return_tensors (`str`, *optional*, defaults to `pt`):
                If `pt`, returns `mindspore.Tensor`. If `tf`, returns `tf.Tensor`.
        """
        crop_boxes, points_per_crop, cropped_images, input_labels = _generate_crop_boxes(
            image,
            target_size,
            crop_n_layers,
            overlap_ratio,
            points_per_crop,
            crop_n_points_downscale_factor,
            input_data_format,
        )
        if return_tensors == "ms":
            crop_boxes = mindspore.tensor(crop_boxes)
            points_per_crop = mindspore.tensor(points_per_crop)
            # cropped_images stays as np
            input_labels = mindspore.tensor(input_labels)
        else:
            raise ValueError("return_tensors must be 'ms'.")
        return crop_boxes, points_per_crop, cropped_images, input_labels

    def filter_masks(
        self,
        masks,
        iou_scores,
        original_size,
        cropped_box_image,
        pred_iou_thresh=0.88,
        stability_score_thresh=0.95,
        mask_threshold=0,
        stability_score_offset=1,
        return_tensors="ms",
    ):
        """
        Filters the predicted masks by selecting only the ones that meets several criteria. The first criterion being
        that the iou scores needs to be greater than `pred_iou_thresh`. The second criterion is that the stability
        score needs to be greater than `stability_score_thresh`. The method also converts the predicted masks to
        bounding boxes and pad the predicted masks if necessary.

        Args:
            masks (`Union[mindspore.Tensor, tf.Tensor]`):
                Input masks.
            iou_scores (`Union[mindspore.Tensor, tf.Tensor]`):
                List of IoU scores.
            original_size (`Tuple[int,int]`):
                Size of the orginal image.
            cropped_box_image (`np.array`):
                The cropped image.
            pred_iou_thresh (`float`, *optional*, defaults to 0.88):
                The threshold for the iou scores.
            stability_score_thresh (`float`, *optional*, defaults to 0.95):
                The threshold for the stability score.
            mask_threshold (`float`, *optional*, defaults to 0):
                The threshold for the predicted masks.
            stability_score_offset (`float`, *optional*, defaults to 1):
                The offset for the stability score used in the `_compute_stability_score` method.
            return_tensors (`str`, *optional*, defaults to `pt`):
                If `pt`, returns `mindspore.Tensor`. If `tf`, returns `tf.Tensor`.
        """
        if return_tensors == "ms":
            return self._filter_masks(
                masks=masks,
                iou_scores=iou_scores,
                original_size=original_size,
                cropped_box_image=cropped_box_image,
                pred_iou_thresh=pred_iou_thresh,
                stability_score_thresh=stability_score_thresh,
                mask_threshold=mask_threshold,
                stability_score_offset=stability_score_offset,
            )
        elif return_tensors == "tf":
            return self._filter_masks_tf(
                masks=masks,
                iou_scores=iou_scores,
                original_size=original_size,
                cropped_box_image=cropped_box_image,
                pred_iou_thresh=pred_iou_thresh,
                stability_score_thresh=stability_score_thresh,
                mask_threshold=mask_threshold,
                stability_score_offset=stability_score_offset,
            )

    def _filter_masks(
        self,
        masks,
        iou_scores,
        original_size,
        cropped_box_image,
        pred_iou_thresh=0.88,
        stability_score_thresh=0.95,
        mask_threshold=0,
        stability_score_offset=1,
    ):
        """
        Filters the predicted masks by selecting only the ones that meets several criteria. The first criterion being
        that the iou scores needs to be greater than `pred_iou_thresh`. The second criterion is that the stability
        score needs to be greater than `stability_score_thresh`. The method also converts the predicted masks to
        bounding boxes and pad the predicted masks if necessary.

        Args:
            masks (`mindspore.Tensor`):
                Input masks.
            iou_scores (`mindspore.Tensor`):
                List of IoU scores.
            original_size (`Tuple[int,int]`):
                Size of the orginal image.
            cropped_box_image (`np.array`):
                The cropped image.
            pred_iou_thresh (`float`, *optional*, defaults to 0.88):
                The threshold for the iou scores.
            stability_score_thresh (`float`, *optional*, defaults to 0.95):
                The threshold for the stability score.
            mask_threshold (`float`, *optional*, defaults to 0):
                The threshold for the predicted masks.
            stability_score_offset (`float`, *optional*, defaults to 1):
                The offset for the stability score used in the `_compute_stability_score` method.

        """
        requires_backends(self, ["torch"])
        original_height, original_width = original_size
        iou_scores = iou_scores.flatten(start_dim=0, end_dim=1)
        masks = masks.flatten(start_dim=0, end_dim=1)

        if masks.shape[0] != iou_scores.shape[0]:
            raise ValueError("masks and iou_scores must have the same batch size.")

        batch_size = masks.shape[0]

        keep_mask = ops.ones(batch_size, dtype=mindspore.bool_)

        if pred_iou_thresh > 0.0:
            keep_mask = keep_mask & (iou_scores > pred_iou_thresh)

        # compute stability score
        if stability_score_thresh > 0.0:
            stability_scores = _compute_stability_score(masks, mask_threshold, stability_score_offset)
            keep_mask = keep_mask & (stability_scores > stability_score_thresh)

        scores = iou_scores[keep_mask]
        masks = masks[keep_mask]

        # binarize masks
        masks = masks > mask_threshold
        converted_boxes = _batched_mask_to_box(masks)

        keep_mask = ~_is_box_near_crop_edge(
            converted_boxes, cropped_box_image, [0, 0, original_width, original_height]
        )

        scores = scores[keep_mask]
        masks = masks[keep_mask]
        converted_boxes = converted_boxes[keep_mask]

        masks = _pad_masks(masks, cropped_box_image, original_height, original_width)
        # conversion to rle is necessary to run non-maximum suppresion
        masks = _mask_to_rle(masks)

        return masks, scores, converted_boxes

mindnlp.transformers.models.sam.image_processing_sam.SamImageProcessor.__init__(do_resize=True, size=None, mask_size=None, resample=PILImageResampling.BILINEAR, do_rescale=True, rescale_factor=1 / 255, do_normalize=True, image_mean=None, image_std=None, do_pad=True, pad_size=None, mask_pad_size=None, do_convert_rgb=True, **kwargs)

Initializes an instance of the SamImageProcessor class.

PARAMETER DESCRIPTION
self

The instance of the class.

do_resize

Determines whether resizing of images should be performed. Defaults to True.

TYPE: bool DEFAULT: True

size

The desired size of the images. Defaults to {'longest_edge': 1024}. The size can be specified as a dictionary with keys 'longest_edge' or 'height' and 'width'. If not provided as a dictionary, it is converted to a dictionary with the 'longest_edge' key.

TYPE: Dict[str, int] DEFAULT: None

mask_size

The desired size of the segmentation masks. Defaults to {'longest_edge': 256}. The size can be specified as a dictionary with keys 'longest_edge' or 'height' and 'width'. If not provided as a dictionary, it is converted to a dictionary with the 'longest_edge' key.

TYPE: Dict[str, int] DEFAULT: None

resample

The resampling method to use during image resizing. Defaults to PILImageResampling.BILINEAR.

TYPE: PILImageResampling DEFAULT: BILINEAR

do_rescale

Determines whether rescaling of pixel values should be performed. Defaults to True.

TYPE: bool DEFAULT: True

rescale_factor

The factor to divide pixel values by during rescaling. Defaults to 1 / 255.

TYPE: Union[int, float] DEFAULT: 1 / 255

do_normalize

Determines whether normalization of pixel values should be performed. Defaults to True.

TYPE: bool DEFAULT: True

image_mean

The mean values to subtract from pixel values during normalization. Defaults to None, which uses the IMAGENET_DEFAULT_MEAN.

TYPE: Optional[Union[float, List[float]]] DEFAULT: None

image_std

The standard deviation values to divide pixel values by during normalization. Defaults to None, which uses the IMAGENET_DEFAULT_STD.

TYPE: Optional[Union[float, List[float]]] DEFAULT: None

do_pad

Determines whether padding of images should be performed. Defaults to True.

TYPE: bool DEFAULT: True

pad_size

The desired size of the padded images. Defaults to None, which uses {'height': 1024, 'width': 1024}. The size can be specified as a single integer, representing both height and width.

TYPE: int DEFAULT: None

mask_pad_size

The desired size of the padded segmentation masks. Defaults to None, which uses {'height': 256, 'width': 256}. The size can be specified as a single integer, representing both height and width.

TYPE: int DEFAULT: None

do_convert_rgb

Determines whether conversion to RGB color space should be performed. Defaults to True.

TYPE: bool DEFAULT: True

**kwargs

Additional keyword arguments to be passed to the parent class forwardor.

DEFAULT: {}

RETURNS DESCRIPTION
None

None.

Source code in mindnlp\transformers\models\sam\image_processing_sam.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
def __init__(
    self,
    do_resize: bool = True,
    size: Dict[str, int] = None,
    mask_size: Dict[str, int] = None,
    resample: PILImageResampling = PILImageResampling.BILINEAR,
    do_rescale: bool = True,
    rescale_factor: Union[int, float] = 1 / 255,
    do_normalize: bool = True,
    image_mean: Optional[Union[float, List[float]]] = None,
    image_std: Optional[Union[float, List[float]]] = None,
    do_pad: bool = True,
    pad_size: int = None,
    mask_pad_size: int = None,
    do_convert_rgb: bool = True,
    **kwargs,
) -> None:
    """
    Initializes an instance of the SamImageProcessor class.

    Args:
        self: The instance of the class.
        do_resize (bool): Determines whether resizing of images should be performed. Defaults to True.
        size (Dict[str, int]): The desired size of the images. Defaults to {'longest_edge': 1024}.
            The size can be specified as a dictionary with keys 'longest_edge' or 'height' and 'width'.
            If not provided as a dictionary, it is converted to a dictionary with the 'longest_edge' key.
        mask_size (Dict[str, int]): The desired size of the segmentation masks. Defaults to {'longest_edge': 256}.
            The size can be specified as a dictionary with keys 'longest_edge' or 'height' and 'width'.
            If not provided as a dictionary, it is converted to a dictionary with the 'longest_edge' key.
        resample (PILImageResampling): The resampling method to use during image resizing.
            Defaults to PILImageResampling.BILINEAR.
        do_rescale (bool): Determines whether rescaling of pixel values should be performed. Defaults to True.
        rescale_factor (Union[int, float]): The factor to divide pixel values by during rescaling.
            Defaults to 1 / 255.
        do_normalize (bool): Determines whether normalization of pixel values should be performed.
            Defaults to True.
        image_mean (Optional[Union[float, List[float]]]): The mean values to subtract from pixel values
            during normalization. Defaults to None, which uses the IMAGENET_DEFAULT_MEAN.
        image_std (Optional[Union[float, List[float]]]): The standard deviation values to divide pixel values
            by during normalization. Defaults to None, which uses the IMAGENET_DEFAULT_STD.
        do_pad (bool): Determines whether padding of images should be performed. Defaults to True.
        pad_size (int): The desired size of the padded images. Defaults to None,
            which uses {'height': 1024, 'width': 1024}. The size can be specified as a single integer, representing
            both height and width.
        mask_pad_size (int): The desired size of the padded segmentation masks. Defaults to None,
            which uses {'height': 256, 'width': 256}. The size can be specified as a single integer,
            representing both height and width.
        do_convert_rgb (bool): Determines whether conversion to RGB color space should be performed. Defaults to True.
        **kwargs: Additional keyword arguments to be passed to the parent class forwardor.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__(**kwargs)
    size = size if size is not None else {"longest_edge": 1024}
    size = get_size_dict(max_size=size, default_to_square=False) if not isinstance(size, dict) else size

    pad_size = pad_size if pad_size is not None else {"height": 1024, "width": 1024}
    pad_size = get_size_dict(pad_size, default_to_square=True)

    mask_size = mask_size if mask_size is not None else {"longest_edge": 256}
    mask_size = (
        get_size_dict(max_size=mask_size, default_to_square=False)
        if not isinstance(mask_size, dict)
        else mask_size
    )

    mask_pad_size = mask_pad_size if mask_pad_size is not None else {"height": 256, "width": 256}
    mask_pad_size = get_size_dict(mask_pad_size, default_to_square=True)

    self.do_resize = do_resize
    self.size = size
    self.mask_size = mask_size
    self.resample = resample
    self.do_rescale = do_rescale
    self.rescale_factor = rescale_factor
    self.do_normalize = do_normalize
    self.image_mean = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
    self.image_std = image_std if image_std is not None else IMAGENET_DEFAULT_STD
    self.do_pad = do_pad
    self.pad_size = pad_size
    self.mask_pad_size = mask_pad_size
    self.do_convert_rgb = do_convert_rgb
    self._valid_processor_keys = [
        "images",
        "segmentation_maps",
        "do_resize",
        "size",
        "mask_size",
        "resample",
        "do_rescale",
        "rescale_factor",
        "do_normalize",
        "image_mean",
        "image_std",
        "do_pad",
        "pad_size",
        "mask_pad_size",
        "do_convert_rgb",
        "return_tensors",
        "data_format",
        "input_data_format",
    ]

mindnlp.transformers.models.sam.image_processing_sam.SamImageProcessor.filter_masks(masks, iou_scores, original_size, cropped_box_image, pred_iou_thresh=0.88, stability_score_thresh=0.95, mask_threshold=0, stability_score_offset=1, return_tensors='ms')

Filters the predicted masks by selecting only the ones that meets several criteria. The first criterion being that the iou scores needs to be greater than pred_iou_thresh. The second criterion is that the stability score needs to be greater than stability_score_thresh. The method also converts the predicted masks to bounding boxes and pad the predicted masks if necessary.

PARAMETER DESCRIPTION
masks

Input masks.

TYPE: `Union[mindspore.Tensor, tf.Tensor]`

iou_scores

List of IoU scores.

TYPE: `Union[mindspore.Tensor, tf.Tensor]`

original_size

Size of the orginal image.

TYPE: `Tuple[int,int]`

cropped_box_image

The cropped image.

TYPE: `np.array`

pred_iou_thresh

The threshold for the iou scores.

TYPE: `float`, *optional*, defaults to 0.88 DEFAULT: 0.88

stability_score_thresh

The threshold for the stability score.

TYPE: `float`, *optional*, defaults to 0.95 DEFAULT: 0.95

mask_threshold

The threshold for the predicted masks.

TYPE: `float`, *optional*, defaults to 0 DEFAULT: 0

stability_score_offset

The offset for the stability score used in the _compute_stability_score method.

TYPE: `float`, *optional*, defaults to 1 DEFAULT: 1

return_tensors

If pt, returns mindspore.Tensor. If tf, returns tf.Tensor.

TYPE: `str`, *optional*, defaults to `pt` DEFAULT: 'ms'

Source code in mindnlp\transformers\models\sam\image_processing_sam.py
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
def filter_masks(
    self,
    masks,
    iou_scores,
    original_size,
    cropped_box_image,
    pred_iou_thresh=0.88,
    stability_score_thresh=0.95,
    mask_threshold=0,
    stability_score_offset=1,
    return_tensors="ms",
):
    """
    Filters the predicted masks by selecting only the ones that meets several criteria. The first criterion being
    that the iou scores needs to be greater than `pred_iou_thresh`. The second criterion is that the stability
    score needs to be greater than `stability_score_thresh`. The method also converts the predicted masks to
    bounding boxes and pad the predicted masks if necessary.

    Args:
        masks (`Union[mindspore.Tensor, tf.Tensor]`):
            Input masks.
        iou_scores (`Union[mindspore.Tensor, tf.Tensor]`):
            List of IoU scores.
        original_size (`Tuple[int,int]`):
            Size of the orginal image.
        cropped_box_image (`np.array`):
            The cropped image.
        pred_iou_thresh (`float`, *optional*, defaults to 0.88):
            The threshold for the iou scores.
        stability_score_thresh (`float`, *optional*, defaults to 0.95):
            The threshold for the stability score.
        mask_threshold (`float`, *optional*, defaults to 0):
            The threshold for the predicted masks.
        stability_score_offset (`float`, *optional*, defaults to 1):
            The offset for the stability score used in the `_compute_stability_score` method.
        return_tensors (`str`, *optional*, defaults to `pt`):
            If `pt`, returns `mindspore.Tensor`. If `tf`, returns `tf.Tensor`.
    """
    if return_tensors == "ms":
        return self._filter_masks(
            masks=masks,
            iou_scores=iou_scores,
            original_size=original_size,
            cropped_box_image=cropped_box_image,
            pred_iou_thresh=pred_iou_thresh,
            stability_score_thresh=stability_score_thresh,
            mask_threshold=mask_threshold,
            stability_score_offset=stability_score_offset,
        )
    elif return_tensors == "tf":
        return self._filter_masks_tf(
            masks=masks,
            iou_scores=iou_scores,
            original_size=original_size,
            cropped_box_image=cropped_box_image,
            pred_iou_thresh=pred_iou_thresh,
            stability_score_thresh=stability_score_thresh,
            mask_threshold=mask_threshold,
            stability_score_offset=stability_score_offset,
        )

mindnlp.transformers.models.sam.image_processing_sam.SamImageProcessor.generate_crop_boxes(image, target_size, crop_n_layers=0, overlap_ratio=512 / 1500, points_per_crop=32, crop_n_points_downscale_factor=1, input_data_format=None, return_tensors='ms')

Generates a list of crop boxes of different sizes. Each layer has (2**i)**2 boxes for the ith layer.

PARAMETER DESCRIPTION
image

Input original image

TYPE: `np.array`

target_size

Target size of the resized image

TYPE: `int`

crop_n_layers

If >0, mask prediction will be run again on crops of the image. Sets the number of layers to run, where each layer has 2**i_layer number of image crops.

TYPE: `int`, *optional*, defaults to 0 DEFAULT: 0

overlap_ratio

Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of the image length. Later layers with more crops scale down this overlap.

TYPE: `float`, *optional*, defaults to 512/1500 DEFAULT: 512 / 1500

points_per_crop

Number of points to sample from each crop.

TYPE: `int`, *optional*, defaults to 32 DEFAULT: 32

crop_n_points_downscale_factor

The number of points-per-side sampled in layer n is scaled down by crop_n_points_downscale_factor**n.

TYPE: `List[int]`, *optional*, defaults to 1 DEFAULT: 1

input_data_format

The channel dimension format of the input image. If not provided, it will be inferred.

TYPE: `str` or `ChannelDimension`, *optional* DEFAULT: None

return_tensors

If pt, returns mindspore.Tensor. If tf, returns tf.Tensor.

TYPE: `str`, *optional*, defaults to `pt` DEFAULT: 'ms'

Source code in mindnlp\transformers\models\sam\image_processing_sam.py
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
def generate_crop_boxes(
    self,
    image,
    target_size,
    crop_n_layers: int = 0,
    overlap_ratio: float = 512 / 1500,
    points_per_crop: Optional[int] = 32,
    crop_n_points_downscale_factor: Optional[List[int]] = 1,
    input_data_format: Optional[Union[str, ChannelDimension]] = None,
    return_tensors: str = "ms",
):
    """
    Generates a list of crop boxes of different sizes. Each layer has (2**i)**2 boxes for the ith layer.

    Args:
        image (`np.array`):
            Input original image
        target_size (`int`):
            Target size of the resized image
        crop_n_layers (`int`, *optional*, defaults to 0):
            If >0, mask prediction will be run again on crops of the image. Sets the number of layers to run, where
            each layer has 2**i_layer number of image crops.
        overlap_ratio (`float`, *optional*, defaults to 512/1500):
            Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of
            the image length. Later layers with more crops scale down this overlap.
        points_per_crop (`int`, *optional*, defaults to 32):
            Number of points to sample from each crop.
        crop_n_points_downscale_factor (`List[int]`, *optional*, defaults to 1):
            The number of points-per-side sampled in layer n is scaled down by crop_n_points_downscale_factor**n.
        input_data_format (`str` or `ChannelDimension`, *optional*):
            The channel dimension format of the input image. If not provided, it will be inferred.
        return_tensors (`str`, *optional*, defaults to `pt`):
            If `pt`, returns `mindspore.Tensor`. If `tf`, returns `tf.Tensor`.
    """
    crop_boxes, points_per_crop, cropped_images, input_labels = _generate_crop_boxes(
        image,
        target_size,
        crop_n_layers,
        overlap_ratio,
        points_per_crop,
        crop_n_points_downscale_factor,
        input_data_format,
    )
    if return_tensors == "ms":
        crop_boxes = mindspore.tensor(crop_boxes)
        points_per_crop = mindspore.tensor(points_per_crop)
        # cropped_images stays as np
        input_labels = mindspore.tensor(input_labels)
    else:
        raise ValueError("return_tensors must be 'ms'.")
    return crop_boxes, points_per_crop, cropped_images, input_labels

mindnlp.transformers.models.sam.image_processing_sam.SamImageProcessor.pad_image(image, pad_size, data_format=None, input_data_format=None, **kwargs)

Pad an image to (pad_size["height"], pad_size["width"]) with zeros to the right and bottom.

PARAMETER DESCRIPTION
image

Image to pad.

TYPE: `np.ndarray`

pad_size

Size of the output image after padding.

TYPE: `Dict[str, int]`

data_format

The data format of the image. Can be either "channels_first" or "channels_last". If None, the data_format of the image will be used.

TYPE: `str` or `ChannelDimension`, *optional* DEFAULT: None

input_data_format

The channel dimension format of the input image. If not provided, it will be inferred.

TYPE: `str` or `ChannelDimension`, *optional* DEFAULT: None

Source code in mindnlp\transformers\models\sam\image_processing_sam.py
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
def pad_image(
    self,
    image: np.ndarray,
    pad_size: Dict[str, int],
    data_format: Optional[Union[str, ChannelDimension]] = None,
    input_data_format: Optional[Union[str, ChannelDimension]] = None,
    **kwargs,
) -> np.ndarray:
    """
    Pad an image to `(pad_size["height"], pad_size["width"])` with zeros to the right and bottom.

    Args:
        image (`np.ndarray`):
            Image to pad.
        pad_size (`Dict[str, int]`):
            Size of the output image after padding.
        data_format (`str` or `ChannelDimension`, *optional*):
            The data format of the image. Can be either "channels_first" or "channels_last". If `None`, the
            `data_format` of the `image` will be used.
        input_data_format (`str` or `ChannelDimension`, *optional*):
            The channel dimension format of the input image. If not provided, it will be inferred.
    """
    output_height, output_width = pad_size["height"], pad_size["width"]
    input_height, input_width = get_image_size(image, channel_dim=input_data_format)

    pad_width = output_width - input_width
    pad_height = output_height - input_height

    padded_image = pad(
        image,
        ((0, pad_height), (0, pad_width)),
        data_format=data_format,
        input_data_format=input_data_format,
        **kwargs,
    )
    return padded_image

mindnlp.transformers.models.sam.image_processing_sam.SamImageProcessor.post_process_for_mask_generation(all_masks, all_scores, all_boxes, crops_nms_thresh, return_tensors='ms')

Post processes mask that are generated by calling the Non Maximum Suppression algorithm on the predicted masks.

PARAMETER DESCRIPTION
all_masks

List of all predicted segmentation masks

TYPE: `Union[List[mindspore.Tensor], List[tf.Tensor]]`

all_scores

List of all predicted iou scores

TYPE: `Union[List[mindspore.Tensor], List[tf.Tensor]]`

all_boxes

List of all bounding boxes of the predicted masks

TYPE: `Union[List[mindspore.Tensor], List[tf.Tensor]]`

crops_nms_thresh

Threshold for NMS (Non Maximum Suppression) algorithm.

TYPE: `float`

return_tensors

If pt, returns mindspore.Tensor. If tf, returns tf.Tensor.

TYPE: `str`, *optional*, defaults to `pt` DEFAULT: 'ms'

Source code in mindnlp\transformers\models\sam\image_processing_sam.py
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
def post_process_for_mask_generation(
    self, all_masks, all_scores, all_boxes, crops_nms_thresh, return_tensors="ms"
):
    """
    Post processes mask that are generated by calling the Non Maximum Suppression algorithm on the predicted masks.

    Args:
        all_masks (`Union[List[mindspore.Tensor], List[tf.Tensor]]`):
            List of all predicted segmentation masks
        all_scores (`Union[List[mindspore.Tensor], List[tf.Tensor]]`):
            List of all predicted iou scores
        all_boxes (`Union[List[mindspore.Tensor], List[tf.Tensor]]`):
            List of all bounding boxes of the predicted masks
        crops_nms_thresh (`float`):
            Threshold for NMS (Non Maximum Suppression) algorithm.
        return_tensors (`str`, *optional*, defaults to `pt`):
            If `pt`, returns `mindspore.Tensor`. If `tf`, returns `tf.Tensor`.
    """
    if return_tensors == "ms":
        return _postprocess_for_mg(all_masks, all_scores, all_boxes, crops_nms_thresh)

mindnlp.transformers.models.sam.image_processing_sam.SamImageProcessor.post_process_masks(masks, original_sizes, reshaped_input_sizes, mask_threshold=0.0, binarize=True, pad_size=None, return_tensors='ms')

Remove padding and upscale masks to the original image size.

PARAMETER DESCRIPTION
masks

Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format.

TYPE: `Union[List[mindspore.Tensor], List[np.ndarray], List[tf.Tensor]]`

original_sizes

The original sizes of each image before it was resized to the model's expected input shape, in (height, width) format.

TYPE: `Union[mindspore.Tensor, tf.Tensor, List[Tuple[int,int]]]`

reshaped_input_sizes

The size of each image as it is fed to the model, in (height, width) format. Used to remove padding.

TYPE: `Union[mindspore.Tensor, tf.Tensor, List[Tuple[int,int]]]`

mask_threshold

The threshold to use for binarizing the masks.

TYPE: `float`, *optional*, defaults to 0.0 DEFAULT: 0.0

binarize

Whether to binarize the masks.

TYPE: `bool`, *optional*, defaults to `True` DEFAULT: True

pad_size

The target size the images were padded to before being passed to the model. If None, the target size is assumed to be the processor's pad_size.

TYPE: `int`, *optional*, defaults to `self.pad_size` DEFAULT: None

return_tensors

If "ms", return PyTorch tensors. If "tf", return TensorFlow tensors.

TYPE: `str`, *optional*, defaults to `"ms"` DEFAULT: 'ms'

RETURNS DESCRIPTION
`Union[mindspore.Tensor, tf.Tensor]`

Batched masks in batch_size, num_channels, height, width) format, where

(height, width) is given by original_size.

Source code in mindnlp\transformers\models\sam\image_processing_sam.py
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
def post_process_masks(
    self,
    masks,
    original_sizes,
    reshaped_input_sizes,
    mask_threshold=0.0,
    binarize=True,
    pad_size=None,
    return_tensors="ms",
):
    """
    Remove padding and upscale masks to the original image size.

    Args:
        masks (`Union[List[mindspore.Tensor], List[np.ndarray], List[tf.Tensor]]`):
            Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format.
        original_sizes (`Union[mindspore.Tensor, tf.Tensor, List[Tuple[int,int]]]`):
            The original sizes of each image before it was resized to the model's expected input shape, in (height,
            width) format.
        reshaped_input_sizes (`Union[mindspore.Tensor, tf.Tensor, List[Tuple[int,int]]]`):
            The size of each image as it is fed to the model, in (height, width) format. Used to remove padding.
        mask_threshold (`float`, *optional*, defaults to 0.0):
            The threshold to use for binarizing the masks.
        binarize (`bool`, *optional*, defaults to `True`):
            Whether to binarize the masks.
        pad_size (`int`, *optional*, defaults to `self.pad_size`):
            The target size the images were padded to before being passed to the model. If None, the target size is
            assumed to be the processor's `pad_size`.
        return_tensors (`str`, *optional*, defaults to `"ms"`):
            If `"ms"`, return PyTorch tensors. If `"tf"`, return TensorFlow tensors.

    Returns:
        (`Union[mindspore.Tensor, tf.Tensor]`): Batched masks in batch_size, num_channels, height, width) format, where
        (height, width) is given by original_size.
    """
    if return_tensors == "ms":
        return self._post_process_masks_ms(
            masks=masks,
            original_sizes=original_sizes,
            reshaped_input_sizes=reshaped_input_sizes,
            mask_threshold=mask_threshold,
            binarize=binarize,
            pad_size=pad_size,
        )
    else:
        raise ValueError("return_tensors must be 'ms'.")

mindnlp.transformers.models.sam.image_processing_sam.SamImageProcessor.preprocess(images, segmentation_maps=None, do_resize=None, size=None, mask_size=None, resample=None, do_rescale=None, rescale_factor=None, do_normalize=None, image_mean=None, image_std=None, do_pad=None, pad_size=None, mask_pad_size=None, do_convert_rgb=None, return_tensors=None, data_format=ChannelDimension.FIRST, input_data_format=None, **kwargs)

Preprocess an image or batch of images.

PARAMETER DESCRIPTION
images

Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, set do_rescale=False.

TYPE: `ImageInput`

segmentation_maps

Segmentation map to preprocess.

TYPE: `ImageInput`, *optional* DEFAULT: None

do_resize

Whether to resize the image.

TYPE: `bool`, *optional*, defaults to `self.do_resize` DEFAULT: None

size

Controls the size of the image after resize. The longest edge of the image is resized to size["longest_edge"] whilst preserving the aspect ratio.

TYPE: `Dict[str, int]`, *optional*, defaults to `self.size` DEFAULT: None

mask_size

Controls the size of the segmentation map after resize. The longest edge of the image is resized to size["longest_edge"] whilst preserving the aspect ratio.

TYPE: `Dict[str, int]`, *optional*, defaults to `self.mask_size` DEFAULT: None

resample

PILImageResampling filter to use when resizing the image e.g. PILImageResampling.BILINEAR.

TYPE: `PILImageResampling`, *optional*, defaults to `self.resample` DEFAULT: None

do_rescale

Whether to rescale the image pixel values by rescaling factor.

TYPE: `bool`, *optional*, defaults to `self.do_rescale` DEFAULT: None

rescale_factor

Rescale factor to apply to the image pixel values.

TYPE: `int` or `float`, *optional*, defaults to `self.rescale_factor` DEFAULT: None

do_normalize

Whether to normalize the image.

TYPE: `bool`, *optional*, defaults to `self.do_normalize` DEFAULT: None

image_mean

Image mean to normalize the image by if do_normalize is set to True.

TYPE: `float` or `List[float]`, *optional*, defaults to `self.image_mean` DEFAULT: None

image_std

Image standard deviation to normalize the image by if do_normalize is set to True.

TYPE: `float` or `List[float]`, *optional*, defaults to `self.image_std` DEFAULT: None

do_pad

Whether to pad the image.

TYPE: `bool`, *optional*, defaults to `self.do_pad` DEFAULT: None

pad_size

Controls the size of the padding applied to the image. The image is padded to pad_size["height"] and pad_size["width"] if do_pad is set to True.

TYPE: `Dict[str, int]`, *optional*, defaults to `self.pad_size` DEFAULT: None

mask_pad_size

Controls the size of the padding applied to the segmentation map. The image is padded to mask_pad_size["height"] and mask_pad_size["width"] if do_pad is set to True.

TYPE: `Dict[str, int]`, *optional*, defaults to `self.mask_pad_size` DEFAULT: None

do_convert_rgb

Whether to convert the image to RGB.

TYPE: `bool`, *optional*, defaults to `self.do_convert_rgb` DEFAULT: None

return_tensors

The type of tensors to return. Can be one of:

  • Unset: Return a list of np.ndarray.
  • TensorType.TENSORFLOW or 'tf': Return a batch of type tf.Tensor.
  • TensorType.PYTORCH or 'pt': Return a batch of type mindspore.Tensor.
  • TensorType.NUMPY or 'np': Return a batch of type np.ndarray.
  • TensorType.JAX or 'jax': Return a batch of type jax.numpy.ndarray.

TYPE: `str` or `TensorType`, *optional* DEFAULT: None

data_format

The channel dimension format for the output image. Can be one of:

  • "channels_first" or ChannelDimension.FIRST: image in (num_channels, height, width) format.
  • "channels_last" or ChannelDimension.LAST: image in (height, width, num_channels) format.
  • Unset: Use the channel dimension format of the input image.

TYPE: `ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST` DEFAULT: FIRST

input_data_format

The channel dimension format for the input image. If unset, the channel dimension format is inferred from the input image. Can be one of:

  • "channels_first" or ChannelDimension.FIRST: image in (num_channels, height, width) format.
  • "channels_last" or ChannelDimension.LAST: image in (height, width, num_channels) format.
  • "none" or ChannelDimension.NONE: image in (height, width) format.

TYPE: `ChannelDimension` or `str`, *optional* DEFAULT: None

Source code in mindnlp\transformers\models\sam\image_processing_sam.py
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
def preprocess(
    self,
    images: ImageInput,
    segmentation_maps: Optional[ImageInput] = None,
    do_resize: Optional[bool] = None,
    size: Optional[Dict[str, int]] = None,
    mask_size: Optional[Dict[str, int]] = None,
    resample: Optional["PILImageResampling"] = None,
    do_rescale: Optional[bool] = None,
    rescale_factor: Optional[Union[int, float]] = None,
    do_normalize: Optional[bool] = None,
    image_mean: Optional[Union[float, List[float]]] = None,
    image_std: Optional[Union[float, List[float]]] = None,
    do_pad: Optional[bool] = None,
    pad_size: Optional[Dict[str, int]] = None,
    mask_pad_size: Optional[Dict[str, int]] = None,
    do_convert_rgb: Optional[bool] = None,
    return_tensors: Optional[Union[str, TensorType]] = None,
    data_format: ChannelDimension = ChannelDimension.FIRST,
    input_data_format: Optional[Union[str, ChannelDimension]] = None,
    **kwargs,
):
    """
    Preprocess an image or batch of images.

    Args:
        images (`ImageInput`):
            Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
            passing in images with pixel values between 0 and 1, set `do_rescale=False`.
        segmentation_maps (`ImageInput`, *optional*):
            Segmentation map to preprocess.
        do_resize (`bool`, *optional*, defaults to `self.do_resize`):
            Whether to resize the image.
        size (`Dict[str, int]`, *optional*, defaults to `self.size`):
            Controls the size of the image after `resize`. The longest edge of the image is resized to
            `size["longest_edge"]` whilst preserving the aspect ratio.
        mask_size (`Dict[str, int]`, *optional*, defaults to `self.mask_size`):
            Controls the size of the segmentation map after `resize`. The longest edge of the image is resized to
            `size["longest_edge"]` whilst preserving the aspect ratio.
        resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
            `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
        do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
            Whether to rescale the image pixel values by rescaling factor.
        rescale_factor (`int` or `float`, *optional*, defaults to `self.rescale_factor`):
            Rescale factor to apply to the image pixel values.
        do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
            Whether to normalize the image.
        image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
            Image mean to normalize the image by if `do_normalize` is set to `True`.
        image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
            Image standard deviation to normalize the image by if `do_normalize` is set to `True`.
        do_pad (`bool`, *optional*, defaults to `self.do_pad`):
            Whether to pad the image.
        pad_size (`Dict[str, int]`, *optional*, defaults to `self.pad_size`):
            Controls the size of the padding applied to the image. The image is padded to `pad_size["height"]` and
            `pad_size["width"]` if `do_pad` is set to `True`.
        mask_pad_size (`Dict[str, int]`, *optional*, defaults to `self.mask_pad_size`):
            Controls the size of the padding applied to the segmentation map. The image is padded to
            `mask_pad_size["height"]` and `mask_pad_size["width"]` if `do_pad` is set to `True`.
        do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
            Whether to convert the image to RGB.
        return_tensors (`str` or `TensorType`, *optional*):
            The type of tensors to return. Can be one of:

            - Unset: Return a list of `np.ndarray`.
            - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
            - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `mindspore.Tensor`.
            - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
            - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
        data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
            The channel dimension format for the output image. Can be one of:

            - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
            - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
            - Unset: Use the channel dimension format of the input image.
        input_data_format (`ChannelDimension` or `str`, *optional*):
            The channel dimension format for the input image. If unset, the channel dimension format is inferred
            from the input image. Can be one of:

            - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
            - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
            - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
    """
    do_resize = do_resize if do_resize is not None else self.do_resize
    size = size if size is not None else self.size
    size = get_size_dict(max_size=size, default_to_square=False) if not isinstance(size, dict) else size
    mask_size = mask_size if mask_size is not None else self.mask_size
    mask_size = (
        get_size_dict(max_size=mask_size, default_to_square=False)
        if not isinstance(mask_size, dict)
        else mask_size
    )
    resample = resample if resample is not None else self.resample
    do_rescale = do_rescale if do_rescale is not None else self.do_rescale
    rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
    do_normalize = do_normalize if do_normalize is not None else self.do_normalize
    image_mean = image_mean if image_mean is not None else self.image_mean
    image_std = image_std if image_std is not None else self.image_std
    do_pad = do_pad if do_pad is not None else self.do_pad
    pad_size = pad_size if pad_size is not None else self.pad_size
    pad_size = get_size_dict(pad_size, default_to_square=True)
    mask_pad_size = mask_pad_size if mask_pad_size is not None else self.mask_pad_size
    mask_pad_size = get_size_dict(mask_pad_size, default_to_square=True)
    do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

    images = make_list_of_images(images)

    validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_processor_keys)

    if not valid_images(images):
        raise ValueError(
            "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
            "mindspore.Tensor, tf.Tensor or jax.ndarray."
        )

    if segmentation_maps is not None:
        segmentation_maps = make_list_of_images(segmentation_maps, expected_ndims=2)

        if not valid_images(segmentation_maps):
            raise ValueError(
                "Invalid segmentation map type. Must be of type PIL.Image.Image, numpy.ndarray, "
                "mindspore.Tensor, tf.Tensor or jax.ndarray."
            )
    validate_preprocess_arguments(
        do_rescale=do_rescale,
        rescale_factor=rescale_factor,
        do_normalize=do_normalize,
        image_mean=image_mean,
        image_std=image_std,
        do_pad=do_pad,
        size_divisibility=pad_size,  # Here _preprocess needs do_pad and pad_size.
        do_resize=do_resize,
        size=size,
        resample=resample,
    )

    images, original_sizes, reshaped_input_sizes = zip(
        *(
            self._preprocess_image(
                image=img,
                do_resize=do_resize,
                size=size,
                resample=resample,
                do_rescale=do_rescale,
                rescale_factor=rescale_factor,
                do_normalize=do_normalize,
                image_mean=image_mean,
                image_std=image_std,
                do_pad=do_pad,
                pad_size=pad_size,
                do_convert_rgb=do_convert_rgb,
                data_format=data_format,
                input_data_format=input_data_format,
            )
            for img in images
        )
    )

    data = {
        "pixel_values": images,
        "original_sizes": original_sizes,
        "reshaped_input_sizes": reshaped_input_sizes,
    }

    if segmentation_maps is not None:
        segmentation_maps, original_mask_sizes = zip(
            *(
                self._preprocess_mask(
                    segmentation_map=mask,
                    do_resize=do_resize,
                    mask_size=mask_size,
                    do_pad=do_pad,
                    mask_pad_size=mask_pad_size,
                    input_data_format=input_data_format,
                )
                for mask in segmentation_maps
            )
        )

        # masks should start out the same size as input images
        assert all(
            original_im_size == original_mask_size
            for original_im_size, original_mask_size in zip(original_sizes, original_mask_sizes)
        ), "Segmentation maps should be the same size as input images."

        data["labels"] = segmentation_maps

    return BatchFeature(data=data, tensor_type=return_tensors)

mindnlp.transformers.models.sam.image_processing_sam.SamImageProcessor.resize(image, size, resample=PILImageResampling.BICUBIC, data_format=None, input_data_format=None, **kwargs)

Resize an image to (size["height"], size["width"]).

PARAMETER DESCRIPTION
image

Image to resize.

TYPE: `np.ndarray`

size

Dictionary in the format {"longest_edge": int} specifying the size of the output image. The longest edge of the image will be resized to the specified size, while the other edge will be resized to maintain the aspect ratio.

TYPE: `Dict[str, int]`

resample

PILImageResampling filter to use when resizing the image e.g. PILImageResampling.BILINEAR.

TYPE: PILImageResampling DEFAULT: BICUBIC

data_format

The channel dimension format for the output image. If unset, the channel dimension format of the input image is used. Can be one of:

  • "channels_first" or ChannelDimension.FIRST: image in (num_channels, height, width) format.
  • "channels_last" or ChannelDimension.LAST: image in (height, width, num_channels) format.

TYPE: `ChannelDimension` or `str`, *optional* DEFAULT: None

input_data_format

The channel dimension format for the input image. If unset, the channel dimension format is inferred from the input image. Can be one of:

  • "channels_first" or ChannelDimension.FIRST: image in (num_channels, height, width) format.
  • "channels_last" or ChannelDimension.LAST: image in (height, width, num_channels) format.

TYPE: `ChannelDimension` or `str`, *optional* DEFAULT: None

RETURNS DESCRIPTION
ndarray

np.ndarray: The resized image.

Source code in mindnlp\transformers\models\sam\image_processing_sam.py
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
def resize(
    self,
    image: np.ndarray,
    size: Dict[str, int],
    resample: PILImageResampling = PILImageResampling.BICUBIC,
    data_format: Optional[Union[str, ChannelDimension]] = None,
    input_data_format: Optional[Union[str, ChannelDimension]] = None,
    **kwargs,
) -> np.ndarray:
    """
    Resize an image to `(size["height"], size["width"])`.

    Args:
        image (`np.ndarray`):
            Image to resize.
        size (`Dict[str, int]`):
            Dictionary in the format `{"longest_edge": int}` specifying the size of the output image. The longest
            edge of the image will be resized to the specified size, while the other edge will be resized to
            maintain the aspect ratio.
        resample:
            `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
        data_format (`ChannelDimension` or `str`, *optional*):
            The channel dimension format for the output image. If unset, the channel dimension format of the input
            image is used. Can be one of:

            - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
            - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
        input_data_format (`ChannelDimension` or `str`, *optional*):
            The channel dimension format for the input image. If unset, the channel dimension format is inferred
            from the input image. Can be one of:

            - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
            - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.

    Returns:
        `np.ndarray`: The resized image.
    """
    size = get_size_dict(size)
    if "longest_edge" not in size:
        raise ValueError(f"The `size` dictionary must contain the key `longest_edge`. Got {size.keys()}")
    input_size = get_image_size(image, channel_dim=input_data_format)
    output_height, output_width = self._get_preprocess_shape(input_size, size["longest_edge"])
    return resize(
        image,
        size=(output_height, output_width),
        resample=resample,
        data_format=data_format,
        input_data_format=input_data_format,
        **kwargs,
    )

mindnlp.transformers.models.sam.image_processing_sam.batched_nms(boxes, scores, idxs, iou_threshold)

Performs non-maximum suppression in a batched fashion.

Each index value correspond to a category, and NMS will not be applied between elements of different categories.

PARAMETER DESCRIPTION
boxes

boxes where NMS will be performed. They are expected to be in (x1, y1, x2, y2) format with 0 <= x1 < x2 and 0 <= y1 < y2.

TYPE: Tensor[N, 4]

scores

scores for each one of the boxes

TYPE: Tensor[N]

idxs

indices of the categories for each one of the boxes.

TYPE: Tensor[N]

iou_threshold

discards all overlapping boxes with IoU > iou_threshold

TYPE: float

RETURNS DESCRIPTION
Tensor

int64 tensor with the indices of the elements that have been kept by NMS, sorted in decreasing order of scores

TYPE: Tensor

Source code in mindnlp\transformers\models\sam\image_processing_sam.py
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
def batched_nms(
    boxes: mindspore.Tensor,
    scores: mindspore.Tensor,
    idxs: mindspore.Tensor,
    iou_threshold: float,
) -> mindspore.Tensor:
    """
    Performs non-maximum suppression in a batched fashion.

    Each index value correspond to a category, and NMS
    will not be applied between elements of different categories.

    Args:
        boxes (Tensor[N, 4]): boxes where NMS will be performed. They
            are expected to be in ``(x1, y1, x2, y2)`` format with ``0 <= x1 < x2`` and ``0 <= y1 < y2``.
        scores (Tensor[N]): scores for each one of the boxes
        idxs (Tensor[N]): indices of the categories for each one of the boxes.
        iou_threshold (float): discards all overlapping boxes with IoU > iou_threshold

    Returns:
        Tensor: int64 tensor with the indices of the elements that have been kept by NMS, sorted
            in decreasing order of scores
    """
    # Benchmarks that drove the following thresholds are at
    # https://github.com/pytorch/vision/issues/1311#issuecomment-781329339
    if boxes.numel() > (4000 if mindspore.get_context('device_target') == "CPU" else 20000):
        return _batched_nms_vanilla(boxes, scores, idxs, iou_threshold)
    else:
        return _batched_nms_coordinate_trick(boxes, scores, idxs, iou_threshold)

mindnlp.transformers.models.sam.image_processing_sam.nms(boxes, scores, iou_threshold)

Performs non-maximum suppression (NMS) on a set of bounding boxes.

PARAMETER DESCRIPTION
boxes

A tensor of shape (N, 4) representing the coordinates of the N bounding boxes. Each bounding box is defined by four values: (x_min, y_min, x_max, y_max).

TYPE: Tensor

scores

A tensor of shape (N,) representing the scores associated with each bounding box.

TYPE: Tensor

iou_threshold

The Intersection over Union (IoU) threshold used for NMS. Bounding boxes with IoU greater than or equal to this threshold will be suppressed.

TYPE: float

RETURNS DESCRIPTION

mindspore.Tensor: A tensor containing the indices of the selected bounding boxes after NMS. The shape of the returned tensor is (M,), where M is the number of selected bounding boxes.

RAISES DESCRIPTION
TypeError

If any of the input arguments are not of the expected type.

ValueError

If the shape of 'boxes' and 'scores' tensors are incompatible or if 'iou_threshold' is not within the valid range.

Source code in mindnlp\transformers\models\sam\image_processing_sam.py
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
def nms(boxes: mindspore.Tensor, scores: mindspore.Tensor, iou_threshold: float):
    """
    Performs non-maximum suppression (NMS) on a set of bounding boxes.

    Args:
        boxes (mindspore.Tensor): A tensor of shape (N, 4) representing the coordinates of the N bounding boxes. 
            Each bounding box is defined by four values: (x_min, y_min, x_max, y_max).
        scores (mindspore.Tensor): A tensor of shape (N,) representing the scores associated with each bounding box.
        iou_threshold (float): The Intersection over Union (IoU) threshold used for NMS. 
            Bounding boxes with IoU greater than or equal to this threshold will be suppressed.

    Returns:
        mindspore.Tensor: A tensor containing the indices of the selected bounding boxes after NMS. 
            The shape of the returned tensor is (M,), where M is the number of selected bounding boxes.

    Raises:
        TypeError: If any of the input arguments are not of the expected type.
        ValueError: If the shape of 'boxes' and 'scores' tensors are incompatible or if 'iou_threshold'
            is not within the valid range.
    """
    box_with_score = ops.stack((boxes, scores))
    _, _, selected_mask = _get_cache_prim(mindspore.ops.NMSWithMask)(iou_threshold)(box_with_score)
    return ops.nonzero(selected_mask).reshape(-1)

mindnlp.transformers.models.sam.modeling_sam

MindSpore SAM model.

mindnlp.transformers.models.sam.modeling_sam.SamAttention

Bases: Module

SAM's attention layer that allows for downscaling the size of the embedding after projection to queries, keys, and values.

Source code in mindnlp\transformers\models\sam\modeling_sam.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
class SamAttention(nn.Module):
    """
    SAM's attention layer that allows for downscaling the size of the embedding after projection to queries, keys, and
    values.
    """

    def __init__(self, config, downsample_rate=None):
        super().__init__()
        self.hidden_size = config.hidden_size

        downsample_rate = config.attention_downsample_rate if downsample_rate is None else downsample_rate

        self.internal_dim = config.hidden_size // downsample_rate
        self.num_attention_heads = config.num_attention_heads
        if self.internal_dim % config.num_attention_heads != 0:
            raise ValueError("num_attention_heads must divide hidden_size.")

        self.q_proj = nn.Linear(self.hidden_size, self.internal_dim)
        self.k_proj = nn.Linear(self.hidden_size, self.internal_dim)
        self.v_proj = nn.Linear(self.hidden_size, self.internal_dim)
        self.out_proj = nn.Linear(self.internal_dim, self.hidden_size)

    def _separate_heads(self, hidden_states: Tensor, num_attention_heads: int) -> Tensor:
        batch, point_batch_size, n_tokens, channel = hidden_states.shape
        c_per_head = channel // num_attention_heads
        hidden_states = hidden_states.reshape(batch * point_batch_size, n_tokens, num_attention_heads, c_per_head)
        return ops.transpose(hidden_states, 1, 2)

    def _recombine_heads(self, hidden_states: Tensor, point_batch_size: int) -> Tensor:
        batch, n_heads, n_tokens, c_per_head = hidden_states.shape
        hidden_states = ops.transpose(hidden_states, 1, 2)
        return hidden_states.reshape(batch // point_batch_size, point_batch_size, n_tokens, n_heads * c_per_head)

    def forward(self, query: Tensor, key: Tensor, value: Tensor, attention_similarity: Tensor = None) -> Tensor:
        # Input projections
        query = self.q_proj(query)
        key = self.k_proj(key)
        value = self.v_proj(value)

        point_batch_size = query.shape[1]
        # Separate into heads
        query = self._separate_heads(query, self.num_attention_heads)
        key = self._separate_heads(key, self.num_attention_heads)
        value = self._separate_heads(value, self.num_attention_heads)

        # SamAttention
        _, _, _, c_per_head = query.shape
        attn = query @ key.permute(0, 1, 3, 2)  # batch_size * point_batch_size  x N_heads x N_tokens x N_tokens
        attn = attn / (c_per_head**0.5)
        attn = ops.softmax(attn, dim=-1)

        if attention_similarity is not None:
            attn = attn + attention_similarity
            attn = ops.softmax(attn, dim=-1)

        # Get output
        out = attn @ value
        out = self._recombine_heads(out, point_batch_size)
        out = self.out_proj(out)

        return out

mindnlp.transformers.models.sam.modeling_sam.SamImageSegmentationOutput dataclass

Bases: ModelOutput

Base class for Segment-Anything model's output

PARAMETER DESCRIPTION
iou_scores

The iou scores of the predicted masks.

TYPE: `mindspore.Tensor` of shape `(batch_size, num_masks)` DEFAULT: None

pred_masks

The predicted low resolutions masks. Needs to be post-processed by the processor

TYPE: `mindspore.Tensor` of shape `(batch_size, num_masks, height, width)` DEFAULT: None

vision_hidden_states

Tuple of mindspore.Tensor (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

Hidden-states of the vision model at the output of each layer plus the optional initial embedding outputs.

TYPE: (`tuple(mindspore.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True` DEFAULT: None

vision_attentions

Tuple of mindspore.Tensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.

TYPE: (`tuple(mindspore.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True` DEFAULT: None

mask_decoder_attentions

Tuple of mindspore.Tensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.

TYPE: `tuple(mindspore.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True` DEFAULT: None

Source code in mindnlp\transformers\models\sam\modeling_sam.py
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
@dataclass
class SamImageSegmentationOutput(ModelOutput):
    """
    Base class for Segment-Anything model's output

    Args:
        iou_scores (`mindspore.Tensor` of shape `(batch_size, num_masks)`):
            The iou scores of the predicted masks.
        pred_masks (`mindspore.Tensor` of shape `(batch_size, num_masks, height, width)`):
            The predicted low resolutions masks. Needs to be post-processed by the processor
        vision_hidden_states  (`tuple(mindspore.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `mindspore.Tensor` (one for the output of the embeddings, if the model has an embedding layer, +
            one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the vision model at the output of each layer plus the optional initial embedding outputs.
        vision_attentions  (`tuple(mindspore.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `mindspore.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
        mask_decoder_attentions (`tuple(mindspore.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `mindspore.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
    """

    iou_scores: mindspore.Tensor = None
    pred_masks: mindspore.Tensor = None
    vision_hidden_states: Optional[Tuple[mindspore.Tensor, ...]] = None
    vision_attentions: Optional[Tuple[mindspore.Tensor, ...]] = None
    mask_decoder_attentions: Optional[Tuple[mindspore.Tensor, ...]] = None

mindnlp.transformers.models.sam.modeling_sam.SamLayerNorm

Bases: Module

LayerNorm that supports two data formats: channels_last (default) or channels_first. The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height, width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width).

Source code in mindnlp\transformers\models\sam\modeling_sam.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
class SamLayerNorm(nn.Module):
    r"""LayerNorm that supports two data formats: channels_last (default) or channels_first.
    The ordering of the dimensions in the inputs. channels_last corresponds to inputs with shape (batch_size, height,
    width, channels) while channels_first corresponds to inputs with shape (batch_size, channels, height, width).
    """

    def __init__(self, normalized_shape, eps=1e-6, data_format="channels_last"):
        super().__init__()
        self.weight = nn.Parameter(ops.ones(normalized_shape))
        self.bias = nn.Parameter(ops.zeros(normalized_shape))
        self.eps = eps
        self.data_format = data_format
        if self.data_format not in ["channels_last", "channels_first"]:
            raise NotImplementedError(f"Unsupported data format: {self.data_format}")
        self.normalized_shape = (normalized_shape,)

    def forward(self, x: mindspore.Tensor) -> mindspore.Tensor:
        if self.data_format == "channels_last":
            x = nn.functional.layer_norm(x, self.normalized_shape, self.weight, self.bias, self.eps)
        elif self.data_format == "channels_first":
            input_dtype = x.dtype
            x = x.float()
            u = ops.mean(x, 1, keepdim=True)
            s = ops.mean((x - u).pow(2), 1, keepdim=True)
            x = (x - u) / ops.sqrt(s + self.eps)
            x = x.to(dtype=input_dtype)
            x = self.weight[:, None, None] * x + self.bias[:, None, None]
        return x

mindnlp.transformers.models.sam.modeling_sam.SamMaskDecoder

Bases: Module

Source code in mindnlp\transformers\models\sam\modeling_sam.py
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
class SamMaskDecoder(nn.Module):
    def __init__(self, config: SamMaskDecoderConfig):
        super().__init__()

        self.hidden_size = config.hidden_size

        self.num_multimask_outputs = config.num_multimask_outputs
        self.num_mask_tokens = config.num_multimask_outputs + 1

        self.iou_token = nn.Embedding(1, self.hidden_size)
        self.mask_tokens = nn.Embedding(self.num_mask_tokens, self.hidden_size)

        self.transformer = SamTwoWayTransformer(config)

        # should we create a new class for this?
        self.upscale_conv1 = nn.ConvTranspose2d(self.hidden_size, self.hidden_size // 4, kernel_size=2, stride=2)
        self.upscale_conv2 = nn.ConvTranspose2d(self.hidden_size // 4, self.hidden_size // 8, kernel_size=2, stride=2)
        self.upscale_layer_norm = SamLayerNorm(self.hidden_size // 4, data_format="channels_first")
        self.activation = nn.GELU()

        mlps_list = []
        for _ in range(self.num_mask_tokens):
            mlps_list += [SamFeedForward(self.hidden_size, self.hidden_size, self.hidden_size // 8, 3)]
        self.output_hypernetworks_mlps = nn.ModuleList(mlps_list)

        self.iou_prediction_head = SamFeedForward(
            self.hidden_size, config.iou_head_hidden_dim, self.num_mask_tokens, config.iou_head_depth
        )

    def forward(
        self,
        image_embeddings: mindspore.Tensor,
        image_positional_embeddings: mindspore.Tensor,
        sparse_prompt_embeddings: mindspore.Tensor,
        dense_prompt_embeddings: mindspore.Tensor,
        multimask_output: bool,
        output_attentions: Optional[bool] = None,
        attention_similarity: mindspore.Tensor = None,
        target_embedding: mindspore.Tensor = None,
    ) -> Tuple[mindspore.Tensor, mindspore.Tensor]:
        """
        Predict masks given image and prompt embeddings.

        Args:
            image_embeddings (`mindspore.Tensor`):
                the embeddings from the image encoder
            image_positional_embedding (`mindspore.Tensor`):
                positional encoding with the shape of image_embeddings
            sparse_prompt_embeddings (`mindspore.Tensor`):
                The embeddings of the points and boxes
            dense_prompt_embeddings (`mindspore.Tensor`):
                the embeddings of the mask inputs
            multimask_output (bool):
                Whether to return multiple masks or a single mask.
            output_attentions (bool, *optional*):
                Whether or not to return the attentions tensors of all attention layers.
        """
        batch_size, num_channels, height, width = image_embeddings.shape
        point_batch_size = sparse_prompt_embeddings.shape[1]
        # Concatenate output tokens
        output_tokens = ops.cat([self.iou_token.weight, self.mask_tokens.weight], dim=0)
        output_tokens = output_tokens.tile((batch_size, point_batch_size, 1, 1))

        if sparse_prompt_embeddings.sum().item() != 0:
            tokens = ops.cat((output_tokens, sparse_prompt_embeddings), dim=2)
        else:
            tokens = output_tokens
        point_embeddings = tokens.to(self.iou_token.weight.dtype)

        # Expand per-image data in batch direction to be per-point
        image_embeddings = image_embeddings + dense_prompt_embeddings
        image_embeddings = ops.repeat_interleave(image_embeddings, point_batch_size, 0)
        image_positional_embeddings = ops.repeat_interleave(image_positional_embeddings, point_batch_size, 0)

        # Run the transformer, image_positional_embedding are consumed
        point_embedding, image_embeddings, attentions = self.transformer(
            point_embeddings=point_embeddings,
            image_embeddings=image_embeddings,
            image_positional_embeddings=image_positional_embeddings,
            attention_similarity=attention_similarity,
            target_embedding=target_embedding,
            output_attentions=output_attentions,
        )
        iou_token_out = point_embedding[:, :, 0, :]
        mask_tokens_out = point_embedding[:, :, 1 : (1 + self.num_mask_tokens), :]

        # Upscale mask embeddings and predict masks using the mask tokens
        image_embeddings = ops.transpose(image_embeddings, 2, 3).reshape(
            batch_size * point_batch_size, num_channels, height, width
        )

        upscaled_embedding = self.upscale_conv1(image_embeddings)
        upscaled_embedding = self.activation(self.upscale_layer_norm(upscaled_embedding))
        upscaled_embedding = self.activation(self.upscale_conv2(upscaled_embedding))

        hyper_in_list = []
        for i in range(self.num_mask_tokens):
            current_mlp = self.output_hypernetworks_mlps[i]
            hyper_in_list += [current_mlp(mask_tokens_out[:, :, i, :])]
        hyper_in = ops.stack(hyper_in_list, dim=2)

        _, num_channels, height, width = upscaled_embedding.shape
        upscaled_embedding = upscaled_embedding.reshape(batch_size, point_batch_size, num_channels, height * width)
        masks = (hyper_in @ upscaled_embedding).reshape(batch_size, point_batch_size, -1, height, width)

        # Generate mask quality predictions
        iou_pred = self.iou_prediction_head(iou_token_out)

        # Select the correct mask or masks for output
        if multimask_output:
            mask_slice = slice(1, None)
        else:
            mask_slice = slice(0, 1)
        masks = masks[:, :, mask_slice, :, :]
        iou_pred = iou_pred[:, :, mask_slice]

        outputs = (masks, iou_pred)

        if output_attentions:
            outputs = outputs + (attentions,)
        else:
            outputs = outputs + (None,)

        return outputs

mindnlp.transformers.models.sam.modeling_sam.SamMaskDecoder.forward(image_embeddings, image_positional_embeddings, sparse_prompt_embeddings, dense_prompt_embeddings, multimask_output, output_attentions=None, attention_similarity=None, target_embedding=None)

Predict masks given image and prompt embeddings.

PARAMETER DESCRIPTION
image_embeddings

the embeddings from the image encoder

TYPE: `mindspore.Tensor`

image_positional_embedding

positional encoding with the shape of image_embeddings

TYPE: `mindspore.Tensor`

sparse_prompt_embeddings

The embeddings of the points and boxes

TYPE: `mindspore.Tensor`

dense_prompt_embeddings

the embeddings of the mask inputs

TYPE: `mindspore.Tensor`

multimask_output

Whether to return multiple masks or a single mask.

TYPE: bool

output_attentions

Whether or not to return the attentions tensors of all attention layers.

TYPE: bool, *optional* DEFAULT: None

Source code in mindnlp\transformers\models\sam\modeling_sam.py
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
def forward(
    self,
    image_embeddings: mindspore.Tensor,
    image_positional_embeddings: mindspore.Tensor,
    sparse_prompt_embeddings: mindspore.Tensor,
    dense_prompt_embeddings: mindspore.Tensor,
    multimask_output: bool,
    output_attentions: Optional[bool] = None,
    attention_similarity: mindspore.Tensor = None,
    target_embedding: mindspore.Tensor = None,
) -> Tuple[mindspore.Tensor, mindspore.Tensor]:
    """
    Predict masks given image and prompt embeddings.

    Args:
        image_embeddings (`mindspore.Tensor`):
            the embeddings from the image encoder
        image_positional_embedding (`mindspore.Tensor`):
            positional encoding with the shape of image_embeddings
        sparse_prompt_embeddings (`mindspore.Tensor`):
            The embeddings of the points and boxes
        dense_prompt_embeddings (`mindspore.Tensor`):
            the embeddings of the mask inputs
        multimask_output (bool):
            Whether to return multiple masks or a single mask.
        output_attentions (bool, *optional*):
            Whether or not to return the attentions tensors of all attention layers.
    """
    batch_size, num_channels, height, width = image_embeddings.shape
    point_batch_size = sparse_prompt_embeddings.shape[1]
    # Concatenate output tokens
    output_tokens = ops.cat([self.iou_token.weight, self.mask_tokens.weight], dim=0)
    output_tokens = output_tokens.tile((batch_size, point_batch_size, 1, 1))

    if sparse_prompt_embeddings.sum().item() != 0:
        tokens = ops.cat((output_tokens, sparse_prompt_embeddings), dim=2)
    else:
        tokens = output_tokens
    point_embeddings = tokens.to(self.iou_token.weight.dtype)

    # Expand per-image data in batch direction to be per-point
    image_embeddings = image_embeddings + dense_prompt_embeddings
    image_embeddings = ops.repeat_interleave(image_embeddings, point_batch_size, 0)
    image_positional_embeddings = ops.repeat_interleave(image_positional_embeddings, point_batch_size, 0)

    # Run the transformer, image_positional_embedding are consumed
    point_embedding, image_embeddings, attentions = self.transformer(
        point_embeddings=point_embeddings,
        image_embeddings=image_embeddings,
        image_positional_embeddings=image_positional_embeddings,
        attention_similarity=attention_similarity,
        target_embedding=target_embedding,
        output_attentions=output_attentions,
    )
    iou_token_out = point_embedding[:, :, 0, :]
    mask_tokens_out = point_embedding[:, :, 1 : (1 + self.num_mask_tokens), :]

    # Upscale mask embeddings and predict masks using the mask tokens
    image_embeddings = ops.transpose(image_embeddings, 2, 3).reshape(
        batch_size * point_batch_size, num_channels, height, width
    )

    upscaled_embedding = self.upscale_conv1(image_embeddings)
    upscaled_embedding = self.activation(self.upscale_layer_norm(upscaled_embedding))
    upscaled_embedding = self.activation(self.upscale_conv2(upscaled_embedding))

    hyper_in_list = []
    for i in range(self.num_mask_tokens):
        current_mlp = self.output_hypernetworks_mlps[i]
        hyper_in_list += [current_mlp(mask_tokens_out[:, :, i, :])]
    hyper_in = ops.stack(hyper_in_list, dim=2)

    _, num_channels, height, width = upscaled_embedding.shape
    upscaled_embedding = upscaled_embedding.reshape(batch_size, point_batch_size, num_channels, height * width)
    masks = (hyper_in @ upscaled_embedding).reshape(batch_size, point_batch_size, -1, height, width)

    # Generate mask quality predictions
    iou_pred = self.iou_prediction_head(iou_token_out)

    # Select the correct mask or masks for output
    if multimask_output:
        mask_slice = slice(1, None)
    else:
        mask_slice = slice(0, 1)
    masks = masks[:, :, mask_slice, :, :]
    iou_pred = iou_pred[:, :, mask_slice]

    outputs = (masks, iou_pred)

    if output_attentions:
        outputs = outputs + (attentions,)
    else:
        outputs = outputs + (None,)

    return outputs

mindnlp.transformers.models.sam.modeling_sam.SamModel

Bases: SamPreTrainedModel

Source code in mindnlp\transformers\models\sam\modeling_sam.py
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
class SamModel(SamPreTrainedModel):
    _tied_weights_keys = ["prompt_encoder.shared_embedding.positional_embedding"]

    def __init__(self, config):
        super().__init__(config)
        self.shared_image_embedding = SamPositionalEmbedding(config.vision_config)

        self.vision_encoder = SamVisionEncoder(config.vision_config)
        self.prompt_encoder = SamPromptEncoder(config.prompt_encoder_config, self.shared_image_embedding)
        self.mask_decoder = SamMaskDecoder(config.mask_decoder_config)

        self.post_init()

    def get_input_embeddings(self):
        return self.vision_encoder.get_input_embeddings()

    def get_image_wide_positional_embeddings(self):
        size = self.config.prompt_encoder_config.image_embedding_size
        target_dtype = self.shared_image_embedding.positional_embedding.dtype
        grid = ops.ones((size, size), dtype=target_dtype)
        y_embed = ops.cumsum(grid, dim=0) - 0.5
        x_embed = ops.cumsum(grid, dim=1) - 0.5
        y_embed = y_embed / size
        x_embed = x_embed / size

        positional_embedding = self.shared_image_embedding(ops.stack([x_embed, y_embed], dim=-1))
        return positional_embedding.permute(2, 0, 1).unsqueeze(0)  # channel x height x width

    @no_grad()
    def get_image_embeddings(
        self,
        pixel_values,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ):
        r"""
        Returns the image embeddings by passing the pixel values through the vision encoder.

        Args:
            pixel_values (`mindspore.Tensor` of shape `(batch_size, num_channels, height, width)`):
                Input pixel values
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers.
            output_hidden_states (`bool`, *optional*):
                Whether or not to return the hidden states of all layers.
            return_dict (`bool`, *optional*):
                Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.

        """
        vision_output = self.vision_encoder(
            pixel_values,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )
        image_embeddings = vision_output[0]
        return image_embeddings

    @no_grad()
    def get_prompt_embeddings(
        self,
        input_points: Optional[mindspore.Tensor] = None,
        input_labels: Optional[mindspore.Tensor] = None,
        input_boxes: Optional[mindspore.Tensor] = None,
        input_masks: Optional[mindspore.Tensor] = None,
    ):
        r"""
        Returns the prompt embeddings by passing the input points, labels, boxes and masks through the prompt encoder.

        Args:
            input_points (`mindspore.Tensor` of shape `(batch_size, point_batch_size, num_points_per_image, 2)`):
                Optional input points for the prompt encoder. The padding of the point is automatically done by the
                processor. `point_batch_size` refers to the number of masks that we want the model to predict per
                point. The model will output `point_batch_size` times 3 masks in total.
            input_labels (`mindspore.Tensor` of shape `(batch_size, point_batch_size, num_points_per_image)`):
                Optional input labels for the prompt encoder. The padding of the labels is automatically done by the
                processor, or can be fed by the user.
            input_boxes (`mindspore.Tensor` of shape `(batch_size, num_boxes_per_image, 4)`):
                Optional input boxes for the prompt encoder. The padding of the boxes is automatically done by the
                processor. users can also pass manually the input boxes.
            input_masks (`mindspore.Tensor` of shape `(batch_size, image_size, image_size)`):
                Optional input masks for the prompt encoder.
        """
        prompt_output = self.prompt_encoder(
            input_points=input_points,
            input_labels=input_labels,
            input_boxes=input_boxes,
            input_masks=input_masks,
        )
        return prompt_output

    def forward(
        self,
        pixel_values: Optional[mindspore.Tensor] = None,
        input_points: Optional[mindspore.Tensor] = None,
        input_labels: Optional[mindspore.Tensor] = None,
        input_boxes: Optional[mindspore.Tensor] = None,
        input_masks: Optional[mindspore.Tensor] = None,
        image_embeddings: Optional[mindspore.Tensor] = None,
        multimask_output: bool = True,
        attention_similarity: Optional[mindspore.Tensor] = None,
        target_embedding: Optional[mindspore.Tensor] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
        **kwargs,
    ) -> List[Dict[str, mindspore.Tensor]]:
        r"""
        Example:

        ```python
        >>> from PIL import Image
        >>> import requests
        >>> from transformers import AutoModel, AutoProcessor

        >>> model = AutoModel.from_pretrained("facebook/sam-vit-base")
        >>> processor = AutoProcessor.from_pretrained("facebook/sam-vit-base")

        >>> img_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/sam-car.png"
        >>> raw_image = Image.open(requests.get(img_url, stream=True).raw).convert("RGB")
        >>> input_points = [[[400, 650]]]  # 2D location of a window on the car
        >>> inputs = processor(images=raw_image, input_points=input_points, return_tensors="ms")

        >>> # Get segmentation mask
        >>> outputs = model(**inputs)

        >>> # Postprocess masks
        >>> masks = processor.post_process_masks(
        ...     outputs.pred_masks, inputs["original_sizes"], inputs["reshaped_input_sizes"]
        ... )
        ```
        """
        output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
        output_hidden_states = (
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        if pixel_values is None and image_embeddings is None:
            raise ValueError("Either pixel_values or image_embeddings must be provided.")

        if pixel_values is not None and image_embeddings is not None:
            raise ValueError("Only one of pixel_values and image_embeddings can be provided.")

        if input_points is not None and len(input_points.shape) != 4:
            raise ValueError(
                "The input_points must be a 4D tensor. Of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.",
                " got {}.".format(input_points.shape),
            )
        if input_boxes is not None and len(input_boxes.shape) != 3:
            raise ValueError(
                "The input_points must be a 3D tensor. Of shape `batch_size`, `nb_boxes`, `4`.",
                " got {}.".format(input_boxes.shape),
            )
        if input_points is not None and input_boxes is not None:
            point_batch_size = input_points.shape[1]
            box_batch_size = input_boxes.shape[1]
            if point_batch_size != box_batch_size:
                raise ValueError(
                    "You should provide as many bounding boxes as input points per box. Got {} and {}.".format(
                        point_batch_size, box_batch_size
                    )
                )

        image_positional_embeddings = self.get_image_wide_positional_embeddings()
        # repeat with batch size
        batch_size = pixel_values.shape[0] if pixel_values is not None else image_embeddings.shape[0]
        image_positional_embeddings = image_positional_embeddings.tile((batch_size, 1, 1, 1))

        vision_attentions = None
        vision_hidden_states = None

        if pixel_values is not None:
            vision_outputs = self.vision_encoder(
                pixel_values,
                output_attentions=output_attentions,
                output_hidden_states=output_hidden_states,
                return_dict=return_dict,
            )
            image_embeddings = vision_outputs[0]

            if output_hidden_states:
                vision_hidden_states = vision_outputs[1]
            if output_attentions:
                vision_attentions = vision_outputs[-1]

        if input_points is not None and input_labels is None:
            input_labels = ops.ones_like(input_points[:, :, :, 0], dtype=mindspore.int32)

        if input_points is not None and image_embeddings.shape[0] != input_points.shape[0]:
            raise ValueError(
                "The batch size of the image embeddings and the input points must be the same. ",
                "Got {} and {} respectively.".format(image_embeddings.shape[0], input_points.shape[0]),
                " if you want to pass multiple points for the same image, make sure that you passed ",
                " input_points of shape (batch_size, point_batch_size, num_points_per_image, 3) and ",
                " input_labels of shape (batch_size, point_batch_size, num_points_per_image)",
            )

        sparse_embeddings, dense_embeddings = self.prompt_encoder(
            input_points=input_points,
            input_labels=input_labels,
            input_boxes=input_boxes,
            input_masks=input_masks,
        )

        low_res_masks, iou_predictions, mask_decoder_attentions = self.mask_decoder(
            image_embeddings=image_embeddings,
            image_positional_embeddings=image_positional_embeddings,
            sparse_prompt_embeddings=sparse_embeddings,
            dense_prompt_embeddings=dense_embeddings,
            multimask_output=multimask_output,
            attention_similarity=attention_similarity,
            target_embedding=target_embedding,
            output_attentions=output_attentions,
        )

        if not return_dict:
            output = (iou_predictions, low_res_masks)
            if output_hidden_states:
                output = output + (vision_hidden_states,)

            if output_attentions:
                output = output + (vision_attentions, mask_decoder_attentions)
            return output

        return SamImageSegmentationOutput(
            iou_scores=iou_predictions,
            pred_masks=low_res_masks,
            vision_hidden_states=vision_hidden_states,
            vision_attentions=vision_attentions,
            mask_decoder_attentions=mask_decoder_attentions,
        )

mindnlp.transformers.models.sam.modeling_sam.SamModel.forward(pixel_values=None, input_points=None, input_labels=None, input_boxes=None, input_masks=None, image_embeddings=None, multimask_output=True, attention_similarity=None, target_embedding=None, output_attentions=None, output_hidden_states=None, return_dict=None, **kwargs)

>>> from PIL import Image
>>> import requests
>>> from transformers import AutoModel, AutoProcessor

>>> model = AutoModel.from_pretrained("facebook/sam-vit-base")
>>> processor = AutoProcessor.from_pretrained("facebook/sam-vit-base")

>>> img_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/sam-car.png"
>>> raw_image = Image.open(requests.get(img_url, stream=True).raw).convert("RGB")
>>> input_points = [[[400, 650]]]  # 2D location of a window on the car
>>> inputs = processor(images=raw_image, input_points=input_points, return_tensors="ms")

>>> # Get segmentation mask
>>> outputs = model(**inputs)

>>> # Postprocess masks
>>> masks = processor.post_process_masks(
...     outputs.pred_masks, inputs["original_sizes"], inputs["reshaped_input_sizes"]
... )
Source code in mindnlp\transformers\models\sam\modeling_sam.py
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
def forward(
    self,
    pixel_values: Optional[mindspore.Tensor] = None,
    input_points: Optional[mindspore.Tensor] = None,
    input_labels: Optional[mindspore.Tensor] = None,
    input_boxes: Optional[mindspore.Tensor] = None,
    input_masks: Optional[mindspore.Tensor] = None,
    image_embeddings: Optional[mindspore.Tensor] = None,
    multimask_output: bool = True,
    attention_similarity: Optional[mindspore.Tensor] = None,
    target_embedding: Optional[mindspore.Tensor] = None,
    output_attentions: Optional[bool] = None,
    output_hidden_states: Optional[bool] = None,
    return_dict: Optional[bool] = None,
    **kwargs,
) -> List[Dict[str, mindspore.Tensor]]:
    r"""
    Example:

    ```python
    >>> from PIL import Image
    >>> import requests
    >>> from transformers import AutoModel, AutoProcessor

    >>> model = AutoModel.from_pretrained("facebook/sam-vit-base")
    >>> processor = AutoProcessor.from_pretrained("facebook/sam-vit-base")

    >>> img_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/sam-car.png"
    >>> raw_image = Image.open(requests.get(img_url, stream=True).raw).convert("RGB")
    >>> input_points = [[[400, 650]]]  # 2D location of a window on the car
    >>> inputs = processor(images=raw_image, input_points=input_points, return_tensors="ms")

    >>> # Get segmentation mask
    >>> outputs = model(**inputs)

    >>> # Postprocess masks
    >>> masks = processor.post_process_masks(
    ...     outputs.pred_masks, inputs["original_sizes"], inputs["reshaped_input_sizes"]
    ... )
    ```
    """
    output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
    output_hidden_states = (
        output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
    )
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict

    if pixel_values is None and image_embeddings is None:
        raise ValueError("Either pixel_values or image_embeddings must be provided.")

    if pixel_values is not None and image_embeddings is not None:
        raise ValueError("Only one of pixel_values and image_embeddings can be provided.")

    if input_points is not None and len(input_points.shape) != 4:
        raise ValueError(
            "The input_points must be a 4D tensor. Of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.",
            " got {}.".format(input_points.shape),
        )
    if input_boxes is not None and len(input_boxes.shape) != 3:
        raise ValueError(
            "The input_points must be a 3D tensor. Of shape `batch_size`, `nb_boxes`, `4`.",
            " got {}.".format(input_boxes.shape),
        )
    if input_points is not None and input_boxes is not None:
        point_batch_size = input_points.shape[1]
        box_batch_size = input_boxes.shape[1]
        if point_batch_size != box_batch_size:
            raise ValueError(
                "You should provide as many bounding boxes as input points per box. Got {} and {}.".format(
                    point_batch_size, box_batch_size
                )
            )

    image_positional_embeddings = self.get_image_wide_positional_embeddings()
    # repeat with batch size
    batch_size = pixel_values.shape[0] if pixel_values is not None else image_embeddings.shape[0]
    image_positional_embeddings = image_positional_embeddings.tile((batch_size, 1, 1, 1))

    vision_attentions = None
    vision_hidden_states = None

    if pixel_values is not None:
        vision_outputs = self.vision_encoder(
            pixel_values,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )
        image_embeddings = vision_outputs[0]

        if output_hidden_states:
            vision_hidden_states = vision_outputs[1]
        if output_attentions:
            vision_attentions = vision_outputs[-1]

    if input_points is not None and input_labels is None:
        input_labels = ops.ones_like(input_points[:, :, :, 0], dtype=mindspore.int32)

    if input_points is not None and image_embeddings.shape[0] != input_points.shape[0]:
        raise ValueError(
            "The batch size of the image embeddings and the input points must be the same. ",
            "Got {} and {} respectively.".format(image_embeddings.shape[0], input_points.shape[0]),
            " if you want to pass multiple points for the same image, make sure that you passed ",
            " input_points of shape (batch_size, point_batch_size, num_points_per_image, 3) and ",
            " input_labels of shape (batch_size, point_batch_size, num_points_per_image)",
        )

    sparse_embeddings, dense_embeddings = self.prompt_encoder(
        input_points=input_points,
        input_labels=input_labels,
        input_boxes=input_boxes,
        input_masks=input_masks,
    )

    low_res_masks, iou_predictions, mask_decoder_attentions = self.mask_decoder(
        image_embeddings=image_embeddings,
        image_positional_embeddings=image_positional_embeddings,
        sparse_prompt_embeddings=sparse_embeddings,
        dense_prompt_embeddings=dense_embeddings,
        multimask_output=multimask_output,
        attention_similarity=attention_similarity,
        target_embedding=target_embedding,
        output_attentions=output_attentions,
    )

    if not return_dict:
        output = (iou_predictions, low_res_masks)
        if output_hidden_states:
            output = output + (vision_hidden_states,)

        if output_attentions:
            output = output + (vision_attentions, mask_decoder_attentions)
        return output

    return SamImageSegmentationOutput(
        iou_scores=iou_predictions,
        pred_masks=low_res_masks,
        vision_hidden_states=vision_hidden_states,
        vision_attentions=vision_attentions,
        mask_decoder_attentions=mask_decoder_attentions,
    )

mindnlp.transformers.models.sam.modeling_sam.SamModel.get_image_embeddings(pixel_values, output_attentions=None, output_hidden_states=None, return_dict=None)

Returns the image embeddings by passing the pixel values through the vision encoder.

PARAMETER DESCRIPTION
pixel_values

Input pixel values

TYPE: `mindspore.Tensor` of shape `(batch_size, num_channels, height, width)`

output_attentions

Whether or not to return the attentions tensors of all attention layers.

TYPE: `bool`, *optional* DEFAULT: None

output_hidden_states

Whether or not to return the hidden states of all layers.

TYPE: `bool`, *optional* DEFAULT: None

return_dict

Whether or not to return a [~utils.ModelOutput] instead of a plain tuple.

TYPE: `bool`, *optional* DEFAULT: None

Source code in mindnlp\transformers\models\sam\modeling_sam.py
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
@no_grad()
def get_image_embeddings(
    self,
    pixel_values,
    output_attentions: Optional[bool] = None,
    output_hidden_states: Optional[bool] = None,
    return_dict: Optional[bool] = None,
):
    r"""
    Returns the image embeddings by passing the pixel values through the vision encoder.

    Args:
        pixel_values (`mindspore.Tensor` of shape `(batch_size, num_channels, height, width)`):
            Input pixel values
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.

    """
    vision_output = self.vision_encoder(
        pixel_values,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )
    image_embeddings = vision_output[0]
    return image_embeddings

mindnlp.transformers.models.sam.modeling_sam.SamModel.get_prompt_embeddings(input_points=None, input_labels=None, input_boxes=None, input_masks=None)

Returns the prompt embeddings by passing the input points, labels, boxes and masks through the prompt encoder.

PARAMETER DESCRIPTION
input_points

Optional input points for the prompt encoder. The padding of the point is automatically done by the processor. point_batch_size refers to the number of masks that we want the model to predict per point. The model will output point_batch_size times 3 masks in total.

TYPE: `mindspore.Tensor` of shape `(batch_size, point_batch_size, num_points_per_image, 2)` DEFAULT: None

input_labels

Optional input labels for the prompt encoder. The padding of the labels is automatically done by the processor, or can be fed by the user.

TYPE: `mindspore.Tensor` of shape `(batch_size, point_batch_size, num_points_per_image)` DEFAULT: None

input_boxes

Optional input boxes for the prompt encoder. The padding of the boxes is automatically done by the processor. users can also pass manually the input boxes.

TYPE: `mindspore.Tensor` of shape `(batch_size, num_boxes_per_image, 4)` DEFAULT: None

input_masks

Optional input masks for the prompt encoder.

TYPE: `mindspore.Tensor` of shape `(batch_size, image_size, image_size)` DEFAULT: None

Source code in mindnlp\transformers\models\sam\modeling_sam.py
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
@no_grad()
def get_prompt_embeddings(
    self,
    input_points: Optional[mindspore.Tensor] = None,
    input_labels: Optional[mindspore.Tensor] = None,
    input_boxes: Optional[mindspore.Tensor] = None,
    input_masks: Optional[mindspore.Tensor] = None,
):
    r"""
    Returns the prompt embeddings by passing the input points, labels, boxes and masks through the prompt encoder.

    Args:
        input_points (`mindspore.Tensor` of shape `(batch_size, point_batch_size, num_points_per_image, 2)`):
            Optional input points for the prompt encoder. The padding of the point is automatically done by the
            processor. `point_batch_size` refers to the number of masks that we want the model to predict per
            point. The model will output `point_batch_size` times 3 masks in total.
        input_labels (`mindspore.Tensor` of shape `(batch_size, point_batch_size, num_points_per_image)`):
            Optional input labels for the prompt encoder. The padding of the labels is automatically done by the
            processor, or can be fed by the user.
        input_boxes (`mindspore.Tensor` of shape `(batch_size, num_boxes_per_image, 4)`):
            Optional input boxes for the prompt encoder. The padding of the boxes is automatically done by the
            processor. users can also pass manually the input boxes.
        input_masks (`mindspore.Tensor` of shape `(batch_size, image_size, image_size)`):
            Optional input masks for the prompt encoder.
    """
    prompt_output = self.prompt_encoder(
        input_points=input_points,
        input_labels=input_labels,
        input_boxes=input_boxes,
        input_masks=input_masks,
    )
    return prompt_output

mindnlp.transformers.models.sam.modeling_sam.SamPatchEmbeddings

Bases: Module

This class turns pixel_values of shape (batch_size, num_channels, height, width) into the initial hidden_states (patch embeddings) of shape (batch_size, seq_length, hidden_size) to be consumed by a Transformer.

Source code in mindnlp\transformers\models\sam\modeling_sam.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
class SamPatchEmbeddings(nn.Module):
    """
    This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
    `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
    Transformer.
    """

    def __init__(self, config):
        super().__init__()
        image_size, patch_size = config.image_size, config.patch_size
        num_channels, hidden_size = config.num_channels, config.hidden_size
        image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
        patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
        num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
        self.image_size = image_size
        self.patch_size = patch_size
        self.num_channels = num_channels
        self.num_patches = num_patches

        self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)

    def forward(self, pixel_values):
        batch_size, num_channels, height, width = pixel_values.shape
        if num_channels != self.num_channels:
            raise ValueError(
                "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
            )
        if height != self.image_size[0] or width != self.image_size[1]:
            raise ValueError(
                f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]})."
            )
        embeddings = self.projection(pixel_values).permute(0, 2, 3, 1)
        return embeddings

mindnlp.transformers.models.sam.modeling_sam.SamPositionalEmbedding

Bases: Module

Source code in mindnlp\transformers\models\sam\modeling_sam.py
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
class SamPositionalEmbedding(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.scale = config.hidden_size // 2
        self.register_buffer("positional_embedding", self.scale * ops.randn((2, config.num_pos_feats)))

    def forward(self, input_coords, input_shape=None):
        """Positionally encode points that are normalized to [0,1]."""
        coordinates = input_coords.copy()

        if input_shape is not None:
            coordinates[:, :, :, 0] = coordinates[:, :, :, 0] / input_shape[1]
            coordinates[:, :, :, 1] = coordinates[:, :, :, 1] / input_shape[0]

        # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape
        coordinates = 2 * coordinates - 1
        coordinates = coordinates.to(self.positional_embedding.dtype)
        coordinates = coordinates @ self.positional_embedding
        coordinates = 2 * np.pi * coordinates
        # outputs d_1 x ... x d_n x channel shape
        return ops.cat([ops.sin(coordinates), ops.cos(coordinates)], dim=-1)

mindnlp.transformers.models.sam.modeling_sam.SamPositionalEmbedding.forward(input_coords, input_shape=None)

Positionally encode points that are normalized to [0,1].

Source code in mindnlp\transformers\models\sam\modeling_sam.py
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
def forward(self, input_coords, input_shape=None):
    """Positionally encode points that are normalized to [0,1]."""
    coordinates = input_coords.copy()

    if input_shape is not None:
        coordinates[:, :, :, 0] = coordinates[:, :, :, 0] / input_shape[1]
        coordinates[:, :, :, 1] = coordinates[:, :, :, 1] / input_shape[0]

    # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape
    coordinates = 2 * coordinates - 1
    coordinates = coordinates.to(self.positional_embedding.dtype)
    coordinates = coordinates @ self.positional_embedding
    coordinates = 2 * np.pi * coordinates
    # outputs d_1 x ... x d_n x channel shape
    return ops.cat([ops.sin(coordinates), ops.cos(coordinates)], dim=-1)

mindnlp.transformers.models.sam.modeling_sam.SamPromptEncoder

Bases: Module

Source code in mindnlp\transformers\models\sam\modeling_sam.py
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
class SamPromptEncoder(nn.Module):
    def __init__(self, config: SamPromptEncoderConfig, shared_patch_embedding):
        super().__init__()
        self.shared_embedding = shared_patch_embedding
        self.mask_embed = SamMaskEmbedding(config)
        self.no_mask_embed = nn.Embedding(1, config.hidden_size)

        self.image_embedding_size = (config.image_embedding_size, config.image_embedding_size)
        self.input_image_size = config.image_size

        self.point_embed = nn.ModuleList(
            [nn.Embedding(1, config.hidden_size) for i in range(config.num_point_embeddings)]
        )
        self.hidden_size = config.hidden_size
        self.not_a_point_embed = nn.Embedding(1, config.hidden_size)

    def _embed_points(self, points: mindspore.Tensor, labels: mindspore.Tensor, pad: bool) -> mindspore.Tensor:
        """Embeds point prompts."""
        points = points + 0.5  # Shift to center of pixel
        if pad:
            target_point_shape = (points.shape[0], points.shape[1], 1, points.shape[-1])
            target_labels_shape = (points.shape[0], points.shape[1], 1)
            padding_point = ops.zeros(target_point_shape)
            padding_label = -ops.ones(target_labels_shape, dtype=labels.dtype)
            points = ops.cat([points, padding_point], dim=2)
            labels = ops.cat([labels, padding_label], dim=2)
        input_shape = (self.input_image_size, self.input_image_size)
        point_embedding = self.shared_embedding(points, input_shape)

        # ops.where and expanding the labels tensor is required by the ONNX export
        point_embedding = ops.where(labels[..., None] == -1, self.not_a_point_embed.weight, point_embedding)

        point_embedding = ops.where(
            labels[..., None] != -10,
            point_embedding,
            mindspore.tensor(0.0, dtype=point_embedding.dtype),
        )

        point_embedding = ops.where(
            (labels == 0)[:, :, :, None],
            point_embedding + self.point_embed[0].weight[None, None, :, :],
            point_embedding,
        )

        point_embedding = ops.where(
            (labels == 1)[:, :, :, None],
            point_embedding + self.point_embed[1].weight[None, None, :, :],
            point_embedding,
        )

        return point_embedding

    def _embed_boxes(self, boxes: mindspore.Tensor) -> mindspore.Tensor:
        """Embeds box prompts."""
        boxes = boxes + 0.5  # Shift to center of pixel
        batch_size, nb_boxes = boxes.shape[:2]
        coords = boxes.reshape(batch_size, nb_boxes, 2, 2)
        input_shape = (self.input_image_size, self.input_image_size)
        corner_embedding = self.shared_embedding(coords, input_shape)
        corner_embedding[:, :, 0, :] += self.point_embed[2].weight
        corner_embedding[:, :, 1, :] += self.point_embed[3].weight
        return corner_embedding

    def forward(
        self,
        input_points: Optional[Tuple[mindspore.Tensor, mindspore.Tensor]],
        input_labels: Optional[mindspore.Tensor],
        input_boxes: Optional[mindspore.Tensor],
        input_masks: Optional[mindspore.Tensor],
    ) -> Tuple[mindspore.Tensor, mindspore.Tensor]:
        """
        Embeds different types of prompts, returning both sparse and dense embeddings.

        Args:
            points (`mindspore.Tensor`, *optional*):
                point coordinates and labels to embed.
            boxes (`mindspore.Tensor`, *optional*):
                boxes to embed
            masks (`mindspore.Tensor`, *optional*):
                masks to embed
        """
        sparse_embeddings = None
        batch_size = 1
        if input_points is not None:
            batch_size, point_batch_size = input_points.shape[:2]
            if input_labels is None:
                raise ValueError("If points are provided, labels must also be provided.")
            point_embeddings = self._embed_points(input_points, input_labels, pad=(input_boxes is None))
            sparse_embeddings = point_embeddings
        if input_boxes is not None:
            batch_size = input_boxes.shape[0]
            box_embeddings = self._embed_boxes(input_boxes)
            if sparse_embeddings is None:
                sparse_embeddings = box_embeddings
            else:
                sparse_embeddings = ops.cat([sparse_embeddings, box_embeddings], dim=2)
        if input_masks is not None:
            dense_embeddings = self.mask_embed(input_masks)
        else:
            dense_embeddings = self.no_mask_embed.weight.reshape(1, -1, 1, 1).broadcast_to(
                (batch_size, -1, self.image_embedding_size[0], self.image_embedding_size[1])
            )

        if sparse_embeddings is None:
            sparse_embeddings = ops.zeros((batch_size, 1, 1, self.hidden_size))

        return sparse_embeddings, dense_embeddings

mindnlp.transformers.models.sam.modeling_sam.SamPromptEncoder.forward(input_points, input_labels, input_boxes, input_masks)

Embeds different types of prompts, returning both sparse and dense embeddings.

PARAMETER DESCRIPTION
points

point coordinates and labels to embed.

TYPE: `mindspore.Tensor`, *optional*

boxes

boxes to embed

TYPE: `mindspore.Tensor`, *optional*

masks

masks to embed

TYPE: `mindspore.Tensor`, *optional*

Source code in mindnlp\transformers\models\sam\modeling_sam.py
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
def forward(
    self,
    input_points: Optional[Tuple[mindspore.Tensor, mindspore.Tensor]],
    input_labels: Optional[mindspore.Tensor],
    input_boxes: Optional[mindspore.Tensor],
    input_masks: Optional[mindspore.Tensor],
) -> Tuple[mindspore.Tensor, mindspore.Tensor]:
    """
    Embeds different types of prompts, returning both sparse and dense embeddings.

    Args:
        points (`mindspore.Tensor`, *optional*):
            point coordinates and labels to embed.
        boxes (`mindspore.Tensor`, *optional*):
            boxes to embed
        masks (`mindspore.Tensor`, *optional*):
            masks to embed
    """
    sparse_embeddings = None
    batch_size = 1
    if input_points is not None:
        batch_size, point_batch_size = input_points.shape[:2]
        if input_labels is None:
            raise ValueError("If points are provided, labels must also be provided.")
        point_embeddings = self._embed_points(input_points, input_labels, pad=(input_boxes is None))
        sparse_embeddings = point_embeddings
    if input_boxes is not None:
        batch_size = input_boxes.shape[0]
        box_embeddings = self._embed_boxes(input_boxes)
        if sparse_embeddings is None:
            sparse_embeddings = box_embeddings
        else:
            sparse_embeddings = ops.cat([sparse_embeddings, box_embeddings], dim=2)
    if input_masks is not None:
        dense_embeddings = self.mask_embed(input_masks)
    else:
        dense_embeddings = self.no_mask_embed.weight.reshape(1, -1, 1, 1).broadcast_to(
            (batch_size, -1, self.image_embedding_size[0], self.image_embedding_size[1])
        )

    if sparse_embeddings is None:
        sparse_embeddings = ops.zeros((batch_size, 1, 1, self.hidden_size))

    return sparse_embeddings, dense_embeddings

mindnlp.transformers.models.sam.modeling_sam.SamTwoWayAttentionBlock

Bases: Module

Source code in mindnlp\transformers\models\sam\modeling_sam.py
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
class SamTwoWayAttentionBlock(nn.Module):
    def __init__(self, config, attention_downsample_rate: int = 2, skip_first_layer_pe: bool = False):
        """
        A transformer block with four layers:
            (1) self-attention of sparse inputs (2) cross attention of sparse inputs -> dense inputs (3) mlp block on
            sparse inputs (4) cross attention of dense inputs -> sparse inputs

        Arguments:
            config (`SamMaskDecoderConfig`):
                The configuration file used to instantiate the block
            attention_downsample_rate (*optionalk*, int, defaults to 2):
                The downsample ratio of the block used to reduce the inner dim of the attention.
            skip_first_layer_pe (*optional*, bool, defaults to `False`):
                Whether or not to skip the addition of the query_point_embedding on the first layer.
        """
        super().__init__()

        self.hidden_size = config.hidden_size
        self.layer_norm_eps = config.layer_norm_eps

        self.self_attn = SamAttention(config, downsample_rate=1)
        self.layer_norm1 = nn.LayerNorm(self.hidden_size, eps=self.layer_norm_eps)

        self.cross_attn_token_to_image = SamAttention(config, downsample_rate=attention_downsample_rate)
        self.layer_norm2 = nn.LayerNorm(self.hidden_size, eps=self.layer_norm_eps)

        self.mlp = SamMLPBlock(config)
        self.layer_norm3 = nn.LayerNorm(self.hidden_size, eps=self.layer_norm_eps)

        self.layer_norm4 = nn.LayerNorm(self.hidden_size, eps=self.layer_norm_eps)
        self.cross_attn_image_to_token = SamAttention(config, downsample_rate=attention_downsample_rate)

        self.skip_first_layer_pe = skip_first_layer_pe

    def forward(
        self,
        queries: Tensor,
        keys: Tensor,
        query_point_embedding: Tensor,
        key_point_embedding: Tensor,
        attention_similarity: Tensor,
        output_attentions: bool = False,
    ):
        # Self attention block
        if self.skip_first_layer_pe:
            queries = self.self_attn(query=queries, key=queries, value=queries)
        else:
            query = queries + query_point_embedding
            attn_out = self.self_attn(query=query, key=query, value=queries)
            queries = queries + attn_out
        queries = self.layer_norm1(queries)

        # Cross attention block, tokens attending to image embedding
        query = queries + query_point_embedding
        key = keys + key_point_embedding

        attn_out = self.cross_attn_token_to_image(
            query=query, key=key, value=keys, attention_similarity=attention_similarity
        )
        queries = queries + attn_out

        queries = self.layer_norm2(queries)

        # MLP block
        mlp_out = self.mlp(queries)
        queries = queries + mlp_out
        queries = self.layer_norm3(queries)

        # Cross attention block, image embedding attending to tokens
        query = queries + query_point_embedding
        key = keys + key_point_embedding

        attn_out = self.cross_attn_image_to_token(query=key, key=query, value=queries)
        keys = keys + attn_out

        keys = self.layer_norm4(keys)

        outputs = (queries, keys)

        if output_attentions:
            outputs = outputs + (attn_out,)
        else:
            outputs = outputs + (None,)

        return outputs

mindnlp.transformers.models.sam.modeling_sam.SamTwoWayAttentionBlock.__init__(config, attention_downsample_rate=2, skip_first_layer_pe=False)

A transformer block with four layers

(1) self-attention of sparse inputs (2) cross attention of sparse inputs -> dense inputs (3) mlp block on sparse inputs (4) cross attention of dense inputs -> sparse inputs

PARAMETER DESCRIPTION
config

The configuration file used to instantiate the block

TYPE: `SamMaskDecoderConfig`

attention_downsample_rate

The downsample ratio of the block used to reduce the inner dim of the attention.

TYPE: *optionalk*, int, defaults to 2 DEFAULT: 2

skip_first_layer_pe

Whether or not to skip the addition of the query_point_embedding on the first layer.

TYPE: *optional*, bool, defaults to `False` DEFAULT: False

Source code in mindnlp\transformers\models\sam\modeling_sam.py
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
def __init__(self, config, attention_downsample_rate: int = 2, skip_first_layer_pe: bool = False):
    """
    A transformer block with four layers:
        (1) self-attention of sparse inputs (2) cross attention of sparse inputs -> dense inputs (3) mlp block on
        sparse inputs (4) cross attention of dense inputs -> sparse inputs

    Arguments:
        config (`SamMaskDecoderConfig`):
            The configuration file used to instantiate the block
        attention_downsample_rate (*optionalk*, int, defaults to 2):
            The downsample ratio of the block used to reduce the inner dim of the attention.
        skip_first_layer_pe (*optional*, bool, defaults to `False`):
            Whether or not to skip the addition of the query_point_embedding on the first layer.
    """
    super().__init__()

    self.hidden_size = config.hidden_size
    self.layer_norm_eps = config.layer_norm_eps

    self.self_attn = SamAttention(config, downsample_rate=1)
    self.layer_norm1 = nn.LayerNorm(self.hidden_size, eps=self.layer_norm_eps)

    self.cross_attn_token_to_image = SamAttention(config, downsample_rate=attention_downsample_rate)
    self.layer_norm2 = nn.LayerNorm(self.hidden_size, eps=self.layer_norm_eps)

    self.mlp = SamMLPBlock(config)
    self.layer_norm3 = nn.LayerNorm(self.hidden_size, eps=self.layer_norm_eps)

    self.layer_norm4 = nn.LayerNorm(self.hidden_size, eps=self.layer_norm_eps)
    self.cross_attn_image_to_token = SamAttention(config, downsample_rate=attention_downsample_rate)

    self.skip_first_layer_pe = skip_first_layer_pe

mindnlp.transformers.models.sam.modeling_sam.SamVisionAttention

Bases: Module

Multi-head Attention block with relative position embeddings.

Source code in mindnlp\transformers\models\sam\modeling_sam.py
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
class SamVisionAttention(nn.Module):
    """Multi-head Attention block with relative position embeddings."""

    def __init__(self, config, window_size):
        super().__init__()
        input_size = (
            (config.image_size // config.patch_size, config.image_size // config.patch_size)
            if window_size == 0
            else (window_size, window_size)
        )

        self.num_attention_heads = config.num_attention_heads
        head_dim = config.hidden_size // config.num_attention_heads
        self.scale = head_dim**-0.5
        self.dropout = config.attention_dropout

        self.qkv = nn.Linear(config.hidden_size, config.hidden_size * 3, bias=config.qkv_bias)
        self.proj = nn.Linear(config.hidden_size, config.hidden_size)

        self.use_rel_pos = config.use_rel_pos
        if self.use_rel_pos:
            if input_size is None:
                raise ValueError("Input size must be provided if using relative positional encoding.")

            # initialize relative positional embeddings
            self.rel_pos_h = nn.Parameter(ops.zeros(2 * input_size[0] - 1, head_dim))
            self.rel_pos_w = nn.Parameter(ops.zeros(2 * input_size[1] - 1, head_dim))

    def get_rel_pos(self, q_size: int, k_size: int, rel_pos: mindspore.Tensor) -> mindspore.Tensor:
        """
        Get relative positional embeddings according to the relative positions of
            query and key sizes.

        Args:
            q_size (int):
                size of the query.
            k_size (int):
                size of key k.
            rel_pos (`mindspore.Tensor`):
                relative position embeddings (L, channel).

        Returns:
            Extracted positional embeddings according to relative positions.
        """
        max_rel_dist = int(2 * max(q_size, k_size) - 1)
        # Interpolate rel pos.
        rel_pos_resized = F.interpolate(
            rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1),
            size=max_rel_dist,
            mode="linear",
        )
        rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0)

        # Scale the coords with short length if shapes for q and k are different.
        q_coords = ops.arange(q_size)[:, None] * max(k_size / q_size, 1.0)
        k_coords = ops.arange(k_size)[None, :] * max(q_size / k_size, 1.0)
        relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0)

        return rel_pos_resized[relative_coords.long()]

    def add_decomposed_rel_pos(
        self,
        attn: mindspore.Tensor,
        query: mindspore.Tensor,
        rel_pos_h: mindspore.Tensor,
        rel_pos_w: mindspore.Tensor,
        q_size: Tuple[int, int],
        k_size: Tuple[int, int],
    ) -> mindspore.Tensor:
        """
        Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`.
        https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py

        Args:
            attn (`mindspore.Tensor`):
                attention map.
            query (`mindspore.Tensor`):
                query q in the attention layer with shape (batch_size, query_height * query_width, channel).
            rel_pos_h (`mindspore.Tensor`):
                relative position embeddings (Lh, channel) for height axis.
            rel_pos_w (`mindspore.Tensor`):
                relative position embeddings (Lw, channel) for width axis.
            q_size (tuple):
                spatial sequence size of query q with (query_height, query_width).
            k_size (tuple):
                spatial sequence size of key k with (key_height, key_width).

        Returns:
            attn (`mindspore.Tensor`):
                attention map with added relative positional embeddings.
        """
        query_height, query_width = q_size
        key_height, key_width = k_size
        relative_position_height = self.get_rel_pos(query_height, key_height, rel_pos_h)
        relative_position_width = self.get_rel_pos(query_width, key_width, rel_pos_w)

        batch_size, _, dim = query.shape
        reshaped_query = query.reshape(batch_size, query_height, query_width, dim)
        rel_h = ops.einsum("bhwc,hkc->bhwk", reshaped_query, relative_position_height)
        rel_w = ops.einsum("bhwc,wkc->bhwk", reshaped_query, relative_position_width)
        attn = attn.reshape(batch_size, query_height, query_width, key_height, key_width)
        attn = attn + rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :]
        attn = attn.reshape(batch_size, query_height * query_width, key_height * key_width)
        return attn

    def forward(self, hidden_states: mindspore.Tensor, output_attentions=False) -> mindspore.Tensor:
        batch_size, height, width, _ = hidden_states.shape
        # qkv with shape (3, batch_size, nHead, height * width, channel)
        qkv = (
            self.qkv(hidden_states)
            .reshape(batch_size, height * width, 3, self.num_attention_heads, -1)
            .permute(2, 0, 3, 1, 4)
        )
        # q, k, v with shape (batch_size * nHead, height * width, channel)
        query, key, value = qkv.reshape(3, batch_size * self.num_attention_heads, height * width, -1).unbind(0)

        attn_weights = (query * self.scale) @ ops.transpose(key, -2, -1)

        if self.use_rel_pos:
            attn_weights = self.add_decomposed_rel_pos(
                attn_weights, query, self.rel_pos_h, self.rel_pos_w, (height, width), (height, width)
            )

        attn_weights = nn.functional.softmax(attn_weights, dtype=mindspore.float32, dim=-1).to(query.dtype)

        attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)

        attn_output = (attn_probs @ value).reshape(batch_size, self.num_attention_heads, height, width, -1)
        attn_output = attn_output.permute(0, 2, 3, 1, 4).reshape(batch_size, height, width, -1)

        attn_output = self.proj(attn_output)

        if output_attentions:
            outputs = (attn_output, attn_weights)
        else:
            outputs = (attn_output, None)

        return outputs

mindnlp.transformers.models.sam.modeling_sam.SamVisionAttention.add_decomposed_rel_pos(attn, query, rel_pos_h, rel_pos_w, q_size, k_size)

Calculate decomposed Relative Positional Embeddings from :paper:mvitv2. https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py

PARAMETER DESCRIPTION
attn

attention map.

TYPE: `mindspore.Tensor`

query

query q in the attention layer with shape (batch_size, query_height * query_width, channel).

TYPE: `mindspore.Tensor`

rel_pos_h

relative position embeddings (Lh, channel) for height axis.

TYPE: `mindspore.Tensor`

rel_pos_w

relative position embeddings (Lw, channel) for width axis.

TYPE: `mindspore.Tensor`

q_size

spatial sequence size of query q with (query_height, query_width).

TYPE: tuple

k_size

spatial sequence size of key k with (key_height, key_width).

TYPE: tuple

RETURNS DESCRIPTION
attn

attention map with added relative positional embeddings.

TYPE: `mindspore.Tensor`

Source code in mindnlp\transformers\models\sam\modeling_sam.py
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
def add_decomposed_rel_pos(
    self,
    attn: mindspore.Tensor,
    query: mindspore.Tensor,
    rel_pos_h: mindspore.Tensor,
    rel_pos_w: mindspore.Tensor,
    q_size: Tuple[int, int],
    k_size: Tuple[int, int],
) -> mindspore.Tensor:
    """
    Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`.
    https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py

    Args:
        attn (`mindspore.Tensor`):
            attention map.
        query (`mindspore.Tensor`):
            query q in the attention layer with shape (batch_size, query_height * query_width, channel).
        rel_pos_h (`mindspore.Tensor`):
            relative position embeddings (Lh, channel) for height axis.
        rel_pos_w (`mindspore.Tensor`):
            relative position embeddings (Lw, channel) for width axis.
        q_size (tuple):
            spatial sequence size of query q with (query_height, query_width).
        k_size (tuple):
            spatial sequence size of key k with (key_height, key_width).

    Returns:
        attn (`mindspore.Tensor`):
            attention map with added relative positional embeddings.
    """
    query_height, query_width = q_size
    key_height, key_width = k_size
    relative_position_height = self.get_rel_pos(query_height, key_height, rel_pos_h)
    relative_position_width = self.get_rel_pos(query_width, key_width, rel_pos_w)

    batch_size, _, dim = query.shape
    reshaped_query = query.reshape(batch_size, query_height, query_width, dim)
    rel_h = ops.einsum("bhwc,hkc->bhwk", reshaped_query, relative_position_height)
    rel_w = ops.einsum("bhwc,wkc->bhwk", reshaped_query, relative_position_width)
    attn = attn.reshape(batch_size, query_height, query_width, key_height, key_width)
    attn = attn + rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :]
    attn = attn.reshape(batch_size, query_height * query_width, key_height * key_width)
    return attn

mindnlp.transformers.models.sam.modeling_sam.SamVisionAttention.get_rel_pos(q_size, k_size, rel_pos)

Get relative positional embeddings according to the relative positions of query and key sizes.

PARAMETER DESCRIPTION
q_size

size of the query.

TYPE: int

k_size

size of key k.

TYPE: int

rel_pos

relative position embeddings (L, channel).

TYPE: `mindspore.Tensor`

RETURNS DESCRIPTION
Tensor

Extracted positional embeddings according to relative positions.

Source code in mindnlp\transformers\models\sam\modeling_sam.py
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
def get_rel_pos(self, q_size: int, k_size: int, rel_pos: mindspore.Tensor) -> mindspore.Tensor:
    """
    Get relative positional embeddings according to the relative positions of
        query and key sizes.

    Args:
        q_size (int):
            size of the query.
        k_size (int):
            size of key k.
        rel_pos (`mindspore.Tensor`):
            relative position embeddings (L, channel).

    Returns:
        Extracted positional embeddings according to relative positions.
    """
    max_rel_dist = int(2 * max(q_size, k_size) - 1)
    # Interpolate rel pos.
    rel_pos_resized = F.interpolate(
        rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1),
        size=max_rel_dist,
        mode="linear",
    )
    rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0)

    # Scale the coords with short length if shapes for q and k are different.
    q_coords = ops.arange(q_size)[:, None] * max(k_size / q_size, 1.0)
    k_coords = ops.arange(k_size)[None, :] * max(q_size / k_size, 1.0)
    relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0)

    return rel_pos_resized[relative_coords.long()]

mindnlp.transformers.models.sam.modeling_sam.SamVisionEncoderOutput dataclass

Bases: ModelOutput

Base class for sam vision model's outputs that also contains image embeddings obtained by applying the projection layer to the pooler_output.

PARAMETER DESCRIPTION
image_embeds

The image embeddings obtained by applying the projection layer to the pooler_output.

TYPE: `mindspore.Tensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True` DEFAULT: None

last_hidden_state

Sequence of hidden-states at the output of the last layer of the model.

TYPE: `mindspore.Tensor` of shape `(batch_size, sequence_length, hidden_size)` DEFAULT: None

hidden_states

Tuple of mindspore.Tensor (one for the output of the embeddings, if the model has an embedding layer, + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size).

Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.

TYPE: `tuple(mindspore.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True` DEFAULT: None

attentions

Tuple of mindspore.Tensor (one for each layer) of shape (batch_size, num_heads, sequence_length, sequence_length).

Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads.

TYPE: `tuple(mindspore.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True` DEFAULT: None

Source code in mindnlp\transformers\models\sam\modeling_sam.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
@dataclass
class SamVisionEncoderOutput(ModelOutput):
    """
    Base class for sam vision model's outputs that also contains image embeddings obtained by applying the projection
    layer to the pooler_output.

    Args:
        image_embeds (`mindspore.Tensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
            The image embeddings obtained by applying the projection layer to the pooler_output.
        last_hidden_state (`mindspore.Tensor` of shape `(batch_size, sequence_length, hidden_size)`):
            Sequence of hidden-states at the output of the last layer of the model.
        hidden_states (`tuple(mindspore.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `mindspore.Tensor` (one for the output of the embeddings, if the model has an embedding layer, +
            one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
        attentions (`tuple(mindspore.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `mindspore.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
    """

    image_embeds: Optional[mindspore.Tensor] = None
    last_hidden_state: mindspore.Tensor = None
    hidden_states: Optional[Tuple[mindspore.Tensor, ...]] = None
    attentions: Optional[Tuple[mindspore.Tensor, ...]] = None

mindnlp.transformers.models.sam.modeling_sam.SamVisionLayer

Bases: Module

Source code in mindnlp\transformers\models\sam\modeling_sam.py
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
class SamVisionLayer(nn.Module):
    def __init__(self, config, window_size):
        super().__init__()
        self.layer_norm1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
        self.attn = SamVisionAttention(config, window_size)
        self.layer_norm2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
        self.mlp = SamMLPBlock(config)
        self.window_size = window_size

    def window_partition(self, hidden_states: mindspore.Tensor, window_size: int) -> Tuple[mindspore.Tensor, Tuple[int, int]]:
        """
        Args:
        Partition into non-overlapping windows with padding if needed.
            hidden_states (tensor): input tokens with [batch_size, height, width, channel]. window_size (int): window
            size.

        Returns:
            windows: windows after partition with [batch_size * num_windows, window_size, window_size, channel].
            (pad_height, pad_width): padded height and width before partition
        """
        batch_size, height, width, channel = hidden_states.shape

        pad_h = (window_size - height % window_size) % window_size
        pad_w = (window_size - width % window_size) % window_size
        hidden_states = F.pad(hidden_states, (0, 0, 0, pad_w, 0, pad_h))
        pad_height, pad_width = height + pad_h, width + pad_w

        hidden_states = hidden_states.reshape(
            batch_size, pad_height // window_size, window_size, pad_width // window_size, window_size, channel
        )
        windows = hidden_states.permute(0, 1, 3, 2, 4, 5).reshape(-1, window_size, window_size, channel)
        return windows, (pad_height, pad_width)

    def window_unpartition(
        self, windows: mindspore.Tensor, window_size: int, padding_shape: Tuple[int, int], original_shape: Tuple[int, int]
    ) -> mindspore.Tensor:
        """
        Args:
        Window unpartition into original sequences and removing padding.
            hidden_states (tensor):
                input tokens with [batch_size * num_windows, window_size, window_size, channel].
            window_size (int):
                window size.
            padding_shape (Tuple):
                padded height and width (pad_height, pad_width).
            original_shape (Tuple): original height and width (height, width) before padding.

        Returns:
            hidden_states: unpartitioned sequences with [batch_size, height, width, channel].
        """
        pad_height, pad_width = padding_shape
        height, width = original_shape
        batch_size = windows.shape[0] // (pad_height * pad_width // window_size // window_size)
        hidden_states = windows.reshape(
            batch_size, pad_height // window_size, pad_width // window_size, window_size, window_size, -1
        )
        hidden_states = (
            hidden_states.permute(0, 1, 3, 2, 4, 5).reshape(batch_size, pad_height, pad_width, -1)
        )

        hidden_states = hidden_states[:, :height, :width, :]
        return hidden_states

    def forward(
        self,
        hidden_states: mindspore.Tensor,
        output_attentions: Optional[bool] = False,
    ) -> Tuple[mindspore.Tensor]:
        residual = hidden_states

        hidden_states = self.layer_norm1(hidden_states)
        # Window partition
        if self.window_size > 0:
            height, width = hidden_states.shape[1], hidden_states.shape[2]
            hidden_states, padding_shape = self.window_partition(hidden_states, self.window_size)

        hidden_states, attn_weights = self.attn(
            hidden_states=hidden_states,
            output_attentions=output_attentions,
        )
        # Reverse window partition
        if self.window_size > 0:
            hidden_states = self.window_unpartition(hidden_states, self.window_size, padding_shape, (height, width))

        hidden_states = residual + hidden_states
        layernorm_output = self.layer_norm2(hidden_states)
        hidden_states = hidden_states + self.mlp(layernorm_output)

        outputs = (hidden_states,)
        if output_attentions:
            outputs += (attn_weights,)

        return outputs

mindnlp.transformers.models.sam.modeling_sam.SamVisionLayer.window_partition(hidden_states, window_size)

Partition into non-overlapping windows with padding if needed. hidden_states (tensor): input tokens with [batch_size, height, width, channel]. window_size (int): window size.

RETURNS DESCRIPTION
windows

windows after partition with [batch_size * num_windows, window_size, window_size, channel].

TYPE: Tensor

(pad_height, pad_width)

padded height and width before partition

Source code in mindnlp\transformers\models\sam\modeling_sam.py
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
def window_partition(self, hidden_states: mindspore.Tensor, window_size: int) -> Tuple[mindspore.Tensor, Tuple[int, int]]:
    """
    Args:
    Partition into non-overlapping windows with padding if needed.
        hidden_states (tensor): input tokens with [batch_size, height, width, channel]. window_size (int): window
        size.

    Returns:
        windows: windows after partition with [batch_size * num_windows, window_size, window_size, channel].
        (pad_height, pad_width): padded height and width before partition
    """
    batch_size, height, width, channel = hidden_states.shape

    pad_h = (window_size - height % window_size) % window_size
    pad_w = (window_size - width % window_size) % window_size
    hidden_states = F.pad(hidden_states, (0, 0, 0, pad_w, 0, pad_h))
    pad_height, pad_width = height + pad_h, width + pad_w

    hidden_states = hidden_states.reshape(
        batch_size, pad_height // window_size, window_size, pad_width // window_size, window_size, channel
    )
    windows = hidden_states.permute(0, 1, 3, 2, 4, 5).reshape(-1, window_size, window_size, channel)
    return windows, (pad_height, pad_width)

mindnlp.transformers.models.sam.modeling_sam.SamVisionLayer.window_unpartition(windows, window_size, padding_shape, original_shape)

Window unpartition into original sequences and removing padding. hidden_states (tensor): input tokens with [batch_size * num_windows, window_size, window_size, channel]. window_size (int): window size. padding_shape (Tuple): padded height and width (pad_height, pad_width). original_shape (Tuple): original height and width (height, width) before padding.

RETURNS DESCRIPTION
hidden_states

unpartitioned sequences with [batch_size, height, width, channel].

TYPE: Tensor

Source code in mindnlp\transformers\models\sam\modeling_sam.py
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
def window_unpartition(
    self, windows: mindspore.Tensor, window_size: int, padding_shape: Tuple[int, int], original_shape: Tuple[int, int]
) -> mindspore.Tensor:
    """
    Args:
    Window unpartition into original sequences and removing padding.
        hidden_states (tensor):
            input tokens with [batch_size * num_windows, window_size, window_size, channel].
        window_size (int):
            window size.
        padding_shape (Tuple):
            padded height and width (pad_height, pad_width).
        original_shape (Tuple): original height and width (height, width) before padding.

    Returns:
        hidden_states: unpartitioned sequences with [batch_size, height, width, channel].
    """
    pad_height, pad_width = padding_shape
    height, width = original_shape
    batch_size = windows.shape[0] // (pad_height * pad_width // window_size // window_size)
    hidden_states = windows.reshape(
        batch_size, pad_height // window_size, pad_width // window_size, window_size, window_size, -1
    )
    hidden_states = (
        hidden_states.permute(0, 1, 3, 2, 4, 5).reshape(batch_size, pad_height, pad_width, -1)
    )

    hidden_states = hidden_states[:, :height, :width, :]
    return hidden_states

mindnlp.transformers.models.sam.processing_sam

Processor class for SAM.

mindnlp.transformers.models.sam.processing_sam.SamProcessor

Bases: ProcessorMixin

Constructs a SAM processor which wraps a SAM image processor and an 2D points & Bounding boxes processor into a single processor.

[SamProcessor] offers all the functionalities of [SamImageProcessor]. See the docstring of [~SamImageProcessor.__call__] for more information.

PARAMETER DESCRIPTION
image_processor

An instance of [SamImageProcessor]. The image processor is a required input.

TYPE: `SamImageProcessor`

Source code in mindnlp\transformers\models\sam\processing_sam.py
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
class SamProcessor(ProcessorMixin):
    r"""
    Constructs a SAM processor which wraps a SAM image processor and an 2D points & Bounding boxes processor into a
    single processor.

    [`SamProcessor`] offers all the functionalities of [`SamImageProcessor`]. See the docstring of
    [`~SamImageProcessor.__call__`] for more information.

    Args:
        image_processor (`SamImageProcessor`):
            An instance of [`SamImageProcessor`]. The image processor is a required input.
    """
    attributes = ["image_processor"]
    image_processor_class = "SamImageProcessor"

    def __init__(self, image_processor):
        """
        Initializes a new instance of the SamProcessor class.

        Args:
            self: The instance of the SamProcessor class.
            image_processor: An image processor object used for image processing operations.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__(image_processor)
        self.current_processor = self.image_processor
        self.point_pad_value = -10
        self.target_size = self.image_processor.size["longest_edge"]

    def __call__(
        self,
        images=None,
        segmentation_maps=None,
        input_points=None,
        input_labels=None,
        input_boxes=None,
        return_tensors: Optional[Union[str, TensorType]] = None,
        **kwargs,
    ) -> BatchEncoding:
        """
        This method uses [`SamImageProcessor.__call__`] method to prepare image(s) for the model. It also prepares 2D
        points and bounding boxes for the model if they are provided.
        """
        encoding_image_processor = self.image_processor(
            images,
            segmentation_maps=segmentation_maps,
            return_tensors=return_tensors,
            **kwargs,
        )

        # pop arguments that are not used in the foward but used nevertheless
        original_sizes = encoding_image_processor["original_sizes"]

        if hasattr(original_sizes, "asnumpy"):  # Checks if MindSpore tensor
            original_sizes = original_sizes.asnumpy()

        input_points, input_labels, input_boxes = self._check_and_preprocess_points(
            input_points=input_points,
            input_labels=input_labels,
            input_boxes=input_boxes,
        )
        encoding_image_processor = self._normalize_and_convert(
            encoding_image_processor,
            original_sizes,
            input_points=input_points,
            input_labels=input_labels,
            input_boxes=input_boxes,
            return_tensors=return_tensors,
        )

        return encoding_image_processor

    def _normalize_and_convert(
        self,
        encoding_image_processor,
        original_sizes,
        input_points=None,
        input_labels=None,
        input_boxes=None,
        return_tensors="ms",
    ):
        """Normalize and convert input data for encoding image processing.

        Args:
            self: SamProcessor
                The instance of the SamProcessor class.
            encoding_image_processor: object
                The encoding image processor object.
            original_sizes: list
                A list containing the original sizes of the input data.
            input_points: list, optional
                A list of input points to be processed. Defaults to None.
            input_labels: list, optional
                A list of input labels to be processed. Defaults to None.
            input_boxes: list, optional
                A list of input boxes to be processed. Defaults to None.
            return_tensors: str
                A string indicating the type of return tensors. Allowed values are: 'ms' for MindSpore tensors.

        Returns:
            None: This method does not return a value. The input encoding_image_processor is updated with
                the processed input data.

        Raises:
            ValueError: If the length of original_sizes does not match the length of input_points or input_boxes.
            ValueError: If input_points and input_labels are not of the same shape.
        """
        if input_points is not None:
            if len(original_sizes) != len(input_points):
                input_points = [
                    self._normalize_coordinates(self.target_size, point, original_sizes[0]) for point in input_points
                ]
            else:
                input_points = [
                    self._normalize_coordinates(self.target_size, point, original_size)
                    for point, original_size in zip(input_points, original_sizes)
                ]
            # check that all arrays have the same shape
            if not all(point.shape == input_points[0].shape for point in input_points):
                if input_labels is not None:
                    input_points, input_labels = self._pad_points_and_labels(input_points, input_labels)

            input_points = np.array(input_points)

        if input_labels is not None:
            input_labels = np.array(input_labels)

        if input_boxes is not None:
            if len(original_sizes) != len(input_boxes):
                input_boxes = [
                    self._normalize_coordinates(self.target_size, box, original_sizes[0], is_bounding_box=True)
                    for box in input_boxes
                ]
            else:
                input_boxes = [
                    self._normalize_coordinates(self.target_size, box, original_size, is_bounding_box=True)
                    for box, original_size in zip(input_boxes, original_sizes)
                ]
            input_boxes = np.array(input_boxes)

        if input_boxes is not None:
            if return_tensors == "ms":
                input_boxes = mindspore.tensor(input_boxes)
                # boxes batch size of 1 by default
                input_boxes = input_boxes.unsqueeze(1) if len(input_boxes.shape) != 3 else input_boxes
            encoding_image_processor.update({"input_boxes": input_boxes})
        if input_points is not None:
            if return_tensors == "ms":
                input_points = mindspore.tensor(input_points, mindspore.float32)
                # point batch size of 1 by default
                input_points = input_points.unsqueeze(1) if len(input_points.shape) != 4 else input_points
            encoding_image_processor.update({"input_points": input_points})
        if input_labels is not None:
            if return_tensors == "ms":
                input_labels = mindspore.tensor(input_labels)
                # point batch size of 1 by default
                input_labels = input_labels.unsqueeze(1) if len(input_labels.shape) != 3 else input_labels
            encoding_image_processor.update({"input_labels": input_labels})

        return encoding_image_processor

    def _pad_points_and_labels(self, input_points, input_labels):
        r"""
        The method pads the 2D points and labels to the maximum number of points in the batch.
        """
        expected_nb_points = max(point.shape[0] for point in input_points)
        processed_input_points = []
        for i, point in enumerate(input_points):
            if point.shape[0] != expected_nb_points:
                point = np.concatenate(
                    [point, np.zeros((expected_nb_points - point.shape[0], 2)) + self.point_pad_value], axis=0
                )
                input_labels[i] = np.append(input_labels[i], [self.point_pad_value])
            processed_input_points.append(point)
        input_points = processed_input_points
        return input_points, input_labels

    def _normalize_coordinates(
        self, target_size: int, coords: np.ndarray, original_size, is_bounding_box=False
    ) -> np.ndarray:
        """
        Expects a numpy array of length 2 in the final dimension. Requires the original image size in (H, W) format.
        """
        old_h, old_w = original_size
        new_h, new_w = self.image_processor._get_preprocess_shape(original_size, longest_edge=target_size)
        coords = deepcopy(coords).astype(float)

        if is_bounding_box:
            coords = coords.reshape(-1, 2, 2)

        coords[..., 0] = coords[..., 0] * (new_w / old_w)
        coords[..., 1] = coords[..., 1] * (new_h / old_h)

        if is_bounding_box:
            coords = coords.reshape(-1, 4)

        return coords

    def _check_and_preprocess_points(
        self,
        input_points=None,
        input_labels=None,
        input_boxes=None,
    ):
        r"""
        Check and preprocesses the 2D points, labels and bounding boxes. It checks if the input is valid and if they
        are, it converts the coordinates of the points and bounding boxes. If a user passes directly a `torch.Tensor`,
        it is converted to a `numpy.ndarray` and then to a `list`.
        """
        if input_points is not None:
            if hasattr(input_points, "asnumpy"):  # Checks for MindSpore tensor
                input_points = input_points.asnumpy().tolist()

            if not isinstance(input_points, list) or not isinstance(input_points[0], list):
                raise ValueError("Input points must be a list of list of floating points.")
            input_points = [np.array(input_point) for input_point in input_points]
        else:
            input_points = None

        if input_labels is not None:
            if hasattr(input_labels, "numpy"):
                input_labels = input_labels.numpy().tolist()

            if not isinstance(input_labels, list) or not isinstance(input_labels[0], list):
                raise ValueError("Input labels must be a list of list integers.")
            input_labels = [np.array(label) for label in input_labels]
        else:
            input_labels = None

        if input_boxes is not None:
            if hasattr(input_boxes, "numpy"):
                input_boxes = input_boxes.numpy().tolist()

            if (
                not isinstance(input_boxes, list)
                or not isinstance(input_boxes[0], list)
                or not isinstance(input_boxes[0][0], list)
            ):
                raise ValueError("Input boxes must be a list of list of list of floating points.")
            input_boxes = [np.array(box).astype(np.float32) for box in input_boxes]
        else:
            input_boxes = None

        return input_points, input_labels, input_boxes

    @property
    def model_input_names(self):
        """
        This method returns a list of unique model input names used in the SamProcessor class.

        Args:
            self (SamProcessor): The instance of the SamProcessor class.

        Returns:
            list: A list of unique model input names extracted from the image processor.

        Raises:
            None.
        """
        image_processor_input_names = self.image_processor.model_input_names
        return list(dict.fromkeys(image_processor_input_names))

    def post_process_masks(self, *args, **kwargs):
        """
        Post-processes masks using the image processor.

        Args:
            self: The instance of the SamProcessor class.

        Returns:
            None.

        Raises:
            Any exceptions raised by the image_processor.post_process_masks method may be propagated from this method.
        """
        return self.image_processor.post_process_masks(*args, **kwargs)

mindnlp.transformers.models.sam.processing_sam.SamProcessor.model_input_names property

This method returns a list of unique model input names used in the SamProcessor class.

PARAMETER DESCRIPTION
self

The instance of the SamProcessor class.

TYPE: SamProcessor

RETURNS DESCRIPTION
list

A list of unique model input names extracted from the image processor.

mindnlp.transformers.models.sam.processing_sam.SamProcessor.__call__(images=None, segmentation_maps=None, input_points=None, input_labels=None, input_boxes=None, return_tensors=None, **kwargs)

This method uses [SamImageProcessor.__call__] method to prepare image(s) for the model. It also prepares 2D points and bounding boxes for the model if they are provided.

Source code in mindnlp\transformers\models\sam\processing_sam.py
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def __call__(
    self,
    images=None,
    segmentation_maps=None,
    input_points=None,
    input_labels=None,
    input_boxes=None,
    return_tensors: Optional[Union[str, TensorType]] = None,
    **kwargs,
) -> BatchEncoding:
    """
    This method uses [`SamImageProcessor.__call__`] method to prepare image(s) for the model. It also prepares 2D
    points and bounding boxes for the model if they are provided.
    """
    encoding_image_processor = self.image_processor(
        images,
        segmentation_maps=segmentation_maps,
        return_tensors=return_tensors,
        **kwargs,
    )

    # pop arguments that are not used in the foward but used nevertheless
    original_sizes = encoding_image_processor["original_sizes"]

    if hasattr(original_sizes, "asnumpy"):  # Checks if MindSpore tensor
        original_sizes = original_sizes.asnumpy()

    input_points, input_labels, input_boxes = self._check_and_preprocess_points(
        input_points=input_points,
        input_labels=input_labels,
        input_boxes=input_boxes,
    )
    encoding_image_processor = self._normalize_and_convert(
        encoding_image_processor,
        original_sizes,
        input_points=input_points,
        input_labels=input_labels,
        input_boxes=input_boxes,
        return_tensors=return_tensors,
    )

    return encoding_image_processor

mindnlp.transformers.models.sam.processing_sam.SamProcessor.__init__(image_processor)

Initializes a new instance of the SamProcessor class.

PARAMETER DESCRIPTION
self

The instance of the SamProcessor class.

image_processor

An image processor object used for image processing operations.

RETURNS DESCRIPTION

None.

Source code in mindnlp\transformers\models\sam\processing_sam.py
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
def __init__(self, image_processor):
    """
    Initializes a new instance of the SamProcessor class.

    Args:
        self: The instance of the SamProcessor class.
        image_processor: An image processor object used for image processing operations.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__(image_processor)
    self.current_processor = self.image_processor
    self.point_pad_value = -10
    self.target_size = self.image_processor.size["longest_edge"]

mindnlp.transformers.models.sam.processing_sam.SamProcessor.post_process_masks(*args, **kwargs)

Post-processes masks using the image processor.

PARAMETER DESCRIPTION
self

The instance of the SamProcessor class.

RETURNS DESCRIPTION

None.

Source code in mindnlp\transformers\models\sam\processing_sam.py
298
299
300
301
302
303
304
305
306
307
308
309
310
311
def post_process_masks(self, *args, **kwargs):
    """
    Post-processes masks using the image processor.

    Args:
        self: The instance of the SamProcessor class.

    Returns:
        None.

    Raises:
        Any exceptions raised by the image_processor.post_process_masks method may be propagated from this method.
    """
    return self.image_processor.post_process_masks(*args, **kwargs)