Skip to content

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
  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
 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
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, ["torch"])
        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.from_numpy(masks[i])
            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 = ops.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 = ops.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
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
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
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
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
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
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
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
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
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
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
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
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
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
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
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
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
1365
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
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
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
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(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
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
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):
        """
        Initializes a new instance of the SamAttention class.

        Args:
            self: The object itself.
            config: An object of the configuration class containing various parameters.
            downsample_rate (optional): An integer representing the downsample rate.
                If not provided, it defaults to None. (default: None)

        Returns:
            None.

        Raises:
            ValueError: If the number of attention heads is not a divisor of hidden_size.
        """
        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:
        """
        Method to separate heads in the attention mechanism.

        Args:
            self (SamAttention): The instance of the SamAttention class.
            hidden_states (Tensor): The input hidden states tensor of shape (batch, point_batch_size, n_tokens, channel).
                This tensor represents the input feature map.
            num_attention_heads (int): The number of attention heads to split the hidden states into.

        Returns:
            Tensor: The tensor resulting from splitting the hidden states into multiple heads.
                The shape of the returned tensor is (batch * point_batch_size, num_attention_heads, n_tokens, c_per_head),
                where c_per_head is the channel size divided by the number of attention heads.

        Raises:
            None
        """
        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 hidden_states.swapaxes(1, 2)

    def _recombine_heads(self, hidden_states: Tensor, point_batch_size: int) -> Tensor:
        """
        Recombines the heads in the hidden states tensor for self attention in the SamAttention class.

        Args:
            self (SamAttention): The instance of the SamAttention class.
            hidden_states (Tensor): A 4D tensor representing the hidden states with shape (batch, n_heads, n_tokens, c_per_head).
                It contains the intermediate representations of the input tokens.

                - batch: The number of sequences in the batch.
                - n_heads: The number of attention heads.
                - n_tokens: The number of input tokens.
                - c_per_head: The size of each head's output.
            point_batch_size (int): The size of the batch for each point.
                Determines how the hidden states should be reshaped.

        Returns:
            Tensor: A reshaped tensor of the hidden states after recombining the heads.
                The shape of the returned tensor is (batch // point_batch_size, point_batch_size, n_tokens,
                n_heads * c_per_head).
                This reshaped tensor is used for further processing in self attention mechanisms.

        Raises:
            None
        """
        batch, n_heads, n_tokens, c_per_head = hidden_states.shape
        hidden_states = hidden_states.swapaxes(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:
        '''
        Constructs a self-attention mechanism for the SamAttention class.

        Args:
            self (SamAttention): An instance of the SamAttention class.
            query (Tensor): The query tensor of shape (batch_size, seq_length, embedding_dim) representing
                the query values.
            key (Tensor): The key tensor of shape (batch_size, seq_length, embedding_dim) representing the key values.
            value (Tensor): The value tensor of shape (batch_size, seq_length, embedding_dim) representing
                the value values.
            attention_similarity (Tensor, optional): The attention similarity tensor of shape
                (batch_size, num_attention_heads, seq_length, seq_length) representing the similarity scores between
                tokens. Defaults to None.

        Returns:
            Tensor: The output tensor of shape (batch_size, seq_length, embedding_dim) representing the attended values.

        Raises:
            None.
        '''
        # 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 / math.sqrt(c_per_head)
        attn = ops.softmax(attn, axis=-1)

        if attention_similarity is not None:
            attn = attn + attention_similarity
            attn = ops.softmax(attn, axis=-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.SamAttention.__init__(config, downsample_rate=None)

Initializes a new instance of the SamAttention class.

PARAMETER DESCRIPTION
self

The object itself.

config

An object of the configuration class containing various parameters.

downsample_rate

An integer representing the downsample rate. If not provided, it defaults to None. (default: None)

TYPE: optional DEFAULT: None

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If the number of attention heads is not a divisor of hidden_size.

Source code in mindnlp/transformers/models/sam/modeling_sam.py
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
def __init__(self, config, downsample_rate=None):
    """
    Initializes a new instance of the SamAttention class.

    Args:
        self: The object itself.
        config: An object of the configuration class containing various parameters.
        downsample_rate (optional): An integer representing the downsample rate.
            If not provided, it defaults to None. (default: None)

    Returns:
        None.

    Raises:
        ValueError: If the number of attention heads is not a divisor of hidden_size.
    """
    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)

mindnlp.transformers.models.sam.modeling_sam.SamAttention.forward(query, key, value, attention_similarity=None)

Constructs a self-attention mechanism for the SamAttention class.

PARAMETER DESCRIPTION
self

An instance of the SamAttention class.

TYPE: SamAttention

query

The query tensor of shape (batch_size, seq_length, embedding_dim) representing the query values.

TYPE: Tensor

key

The key tensor of shape (batch_size, seq_length, embedding_dim) representing the key values.

TYPE: Tensor

value

The value tensor of shape (batch_size, seq_length, embedding_dim) representing the value values.

TYPE: Tensor

attention_similarity

The attention similarity tensor of shape (batch_size, num_attention_heads, seq_length, seq_length) representing the similarity scores between tokens. Defaults to None.

TYPE: Tensor DEFAULT: None

RETURNS DESCRIPTION
Tensor

The output tensor of shape (batch_size, seq_length, embedding_dim) representing the attended values.

TYPE: Tensor

Source code in mindnlp/transformers/models/sam/modeling_sam.py
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
def forward(self, query: Tensor, key: Tensor, value: Tensor, attention_similarity: Tensor = None) -> Tensor:
    '''
    Constructs a self-attention mechanism for the SamAttention class.

    Args:
        self (SamAttention): An instance of the SamAttention class.
        query (Tensor): The query tensor of shape (batch_size, seq_length, embedding_dim) representing
            the query values.
        key (Tensor): The key tensor of shape (batch_size, seq_length, embedding_dim) representing the key values.
        value (Tensor): The value tensor of shape (batch_size, seq_length, embedding_dim) representing
            the value values.
        attention_similarity (Tensor, optional): The attention similarity tensor of shape
            (batch_size, num_attention_heads, seq_length, seq_length) representing the similarity scores between
            tokens. Defaults to None.

    Returns:
        Tensor: The output tensor of shape (batch_size, seq_length, embedding_dim) representing the attended values.

    Raises:
        None.
    '''
    # 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 / math.sqrt(c_per_head)
    attn = ops.softmax(attn, axis=-1)

    if attention_similarity is not None:
        attn = attn + attention_similarity
        attn = ops.softmax(attn, axis=-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.SamFeedForward

Bases: Module

SamFeedForward is a class representing a feedforward neural network model with customizable parameters for input, hidden, and output dimensions, as well as the number of layers. The class allows for the option of applying a sigmoid activation function to the output layer.

PARAMETER DESCRIPTION
input_dim

The dimension of the input data.

TYPE: int

hidden_dim

The dimension of the hidden layers.

TYPE: int

output_dim

The dimension of the output data.

TYPE: int

num_layers

The number of hidden layers in the network.

TYPE: int

sigmoid_output

If True, applies a sigmoid activation function to the output layer. Defaults to False.

TYPE: bool DEFAULT: False

ATTRIBUTE DESCRIPTION
num_layers

The number of hidden layers in the network.

TYPE: int

activation

The rectified linear unit (ReLU) activation function.

TYPE: ReLU

proj_in

The linear transformation for input data to the hidden layer.

TYPE: Linear

proj_out

The linear transformation for the last hidden layer to the output data.

TYPE: Linear

layers

List of Dense layers for the hidden layers in the network.

TYPE: ModuleList

METHOD DESCRIPTION
forward

Constructs the feedforward network by applying linear transformations and activation functions to the input data through the hidden layers, and finally to the output data.

RETURNS DESCRIPTION
hidden_states

The output data after passing through the feedforward network, with optional sigmoid activation applied.

Source code in mindnlp/transformers/models/sam/modeling_sam.py
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
class SamFeedForward(nn.Module):

    """
    SamFeedForward is a class representing a feedforward neural network model with customizable parameters for input,
    hidden, and output dimensions, as well as the number of layers. The class allows for the option of applying a
    sigmoid activation function to the output layer.

    Parameters:
        input_dim (int): The dimension of the input data.
        hidden_dim (int): The dimension of the hidden layers.
        output_dim (int): The dimension of the output data.
        num_layers (int): The number of hidden layers in the network.
        sigmoid_output (bool, optional): If True, applies a sigmoid activation function to the output layer.
            Defaults to False.

    Attributes:
        num_layers (int): The number of hidden layers in the network.
        activation (nn.ReLU): The rectified linear unit (ReLU) activation function.
        proj_in (nn.Linear): The linear transformation for input data to the hidden layer.
        proj_out (nn.Linear): The linear transformation for the last hidden layer to the output data.
        layers (nn.ModuleList): List of Dense layers for the hidden layers in the network.

    Methods:
        forward: Constructs the feedforward network by applying linear transformations and activation functions
            to the input data through the hidden layers, and finally to the output data.

    Returns:
        hidden_states: The output data after passing through the feedforward network, with optional sigmoid activation
            applied.

    """
    def __init__(
        self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int, sigmoid_output: bool = False
    ):
        """
        Initializes an instance of the SamFeedForward class.

        Args:
            self: The instance of the class.
            input_dim (int): The dimension of the input data.
            hidden_dim (int): The dimension of the hidden layers.
            output_dim (int): The dimension of the output data.
            num_layers (int): The number of hidden layers in the network.
            sigmoid_output (bool, optional): Flag to indicate whether the output should be passed through a sigmoid
                activation function. Default is False.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__()
        self.num_layers = num_layers
        self.activation = nn.ReLU()
        self.proj_in = nn.Linear(input_dim, hidden_dim)
        self.proj_out = nn.Linear(hidden_dim, output_dim)
        self.layers = nn.ModuleList([nn.Linear(hidden_dim, hidden_dim) for _ in range(num_layers - 2)])
        self.sigmoid_output = sigmoid_output

    def forward(self, hidden_states):
        """
        This method forwards a feedforward neural network using the provided hidden states.

        Args:
            self (SamFeedForward): The instance of the SamFeedForward class.
            hidden_states (tensor): The input hidden states to be processed by the neural network.

        Returns:
            None.

        Raises:
            None.
        """
        hidden_states = self.proj_in(hidden_states)
        hidden_states = self.activation(hidden_states)
        for layer in self.layers:
            hidden_states = self.activation(layer(hidden_states))

        hidden_states = self.proj_out(hidden_states)
        if self.sigmoid_output:
            hidden_states = ops.sigmoid(hidden_states)
        return hidden_states

mindnlp.transformers.models.sam.modeling_sam.SamFeedForward.__init__(input_dim, hidden_dim, output_dim, num_layers, sigmoid_output=False)

Initializes an instance of the SamFeedForward class.

PARAMETER DESCRIPTION
self

The instance of the class.

input_dim

The dimension of the input data.

TYPE: int

hidden_dim

The dimension of the hidden layers.

TYPE: int

output_dim

The dimension of the output data.

TYPE: int

num_layers

The number of hidden layers in the network.

TYPE: int

sigmoid_output

Flag to indicate whether the output should be passed through a sigmoid activation function. Default is False.

TYPE: bool DEFAULT: False

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/sam/modeling_sam.py
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
def __init__(
    self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int, sigmoid_output: bool = False
):
    """
    Initializes an instance of the SamFeedForward class.

    Args:
        self: The instance of the class.
        input_dim (int): The dimension of the input data.
        hidden_dim (int): The dimension of the hidden layers.
        output_dim (int): The dimension of the output data.
        num_layers (int): The number of hidden layers in the network.
        sigmoid_output (bool, optional): Flag to indicate whether the output should be passed through a sigmoid
            activation function. Default is False.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__()
    self.num_layers = num_layers
    self.activation = nn.ReLU()
    self.proj_in = nn.Linear(input_dim, hidden_dim)
    self.proj_out = nn.Linear(hidden_dim, output_dim)
    self.layers = nn.ModuleList([nn.Linear(hidden_dim, hidden_dim) for _ in range(num_layers - 2)])
    self.sigmoid_output = sigmoid_output

mindnlp.transformers.models.sam.modeling_sam.SamFeedForward.forward(hidden_states)

This method forwards a feedforward neural network using the provided hidden states.

PARAMETER DESCRIPTION
self

The instance of the SamFeedForward class.

TYPE: SamFeedForward

hidden_states

The input hidden states to be processed by the neural network.

TYPE: tensor

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/sam/modeling_sam.py
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
def forward(self, hidden_states):
    """
    This method forwards a feedforward neural network using the provided hidden states.

    Args:
        self (SamFeedForward): The instance of the SamFeedForward class.
        hidden_states (tensor): The input hidden states to be processed by the neural network.

    Returns:
        None.

    Raises:
        None.
    """
    hidden_states = self.proj_in(hidden_states)
    hidden_states = self.activation(hidden_states)
    for layer in self.layers:
        hidden_states = self.activation(layer(hidden_states))

    hidden_states = self.proj_out(hidden_states)
    if self.sigmoid_output:
        hidden_states = ops.sigmoid(hidden_states)
    return hidden_states

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

Source code in mindnlp/transformers/models/sam/modeling_sam.py
 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
@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
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
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"):
        """
        Initializes a new instance of the SamLayerNorm class.

        Args:
            self: The object itself.
            normalized_shape (tuple): The shape of the input tensor, indicating the size of each dimension.
            eps (float, optional): A small value to prevent division by zero when normalizing the input tensor.
                Defaults to 1e-06.
            data_format (str, optional): The format of the input tensor. Accepted values are 'channels_last' and
                'channels_first'. Defaults to 'channels_last'.

        Returns:
            None

        Raises:
            NotImplementedError: If the specified data format is not supported.

        This method initializes the SamLayerNorm object with the provided parameters. It sets the weight and bias
        parameters as trainable variables, initializes the epsilon value for numerical stability, and validates the
        data format. The normalized_shape parameter represents the size of each dimension of the input tensor.
        The eps parameter is used to avoid division by zero when normalizing the input tensor. The data_format parameter
        specifies the layout of the input tensor, which can be either 'channels_last' or 'channels_first'.
        If an unsupported data format is provided, a NotImplementedError is raised.
        """
        super().__init__()
        self.weight = Parameter(ops.ones(normalized_shape))
        self.bias = 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,)
        self.layer_norm = ops.LayerNorm(begin_norm_axis=-1,
                                      begin_params_axis=-1,
                                      epsilon=self.eps)

    def forward(self, x: mindspore.Tensor) -> mindspore.Tensor:
        """
        Constructs a layer normalization operation for the SamLayerNorm class.

        Args:
            self (SamLayerNorm): The instance of the SamLayerNorm class.
            x (mindspore.Tensor): The input tensor to be normalized.

        Returns:
            mindspore.Tensor: A normalized tensor based on the input tensor 'x'.

        Raises:
            ValueError: If the data format is not supported.
            TypeError: If the input tensor 'x' is of an unsupported type.
            RuntimeError: If any runtime error occurs during the normalization process.
        """
        if self.data_format == "channels_last":
            x, _, _ = self.layer_norm(x, self.weight, self.bias)
        elif self.data_format == "channels_first":
            input_dtype = x.dtype
            x = x.float()
            u = x.mean(1, keep_dims=True)
            s = (x - u).pow(2).mean(1, keep_dims=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.SamLayerNorm.__init__(normalized_shape, eps=1e-06, data_format='channels_last')

Initializes a new instance of the SamLayerNorm class.

PARAMETER DESCRIPTION
self

The object itself.

normalized_shape

The shape of the input tensor, indicating the size of each dimension.

TYPE: tuple

eps

A small value to prevent division by zero when normalizing the input tensor. Defaults to 1e-06.

TYPE: float DEFAULT: 1e-06

data_format

The format of the input tensor. Accepted values are 'channels_last' and 'channels_first'. Defaults to 'channels_last'.

TYPE: str DEFAULT: 'channels_last'

RETURNS DESCRIPTION

None

RAISES DESCRIPTION
NotImplementedError

If the specified data format is not supported.

This method initializes the SamLayerNorm object with the provided parameters. It sets the weight and bias parameters as trainable variables, initializes the epsilon value for numerical stability, and validates the data format. The normalized_shape parameter represents the size of each dimension of the input tensor. The eps parameter is used to avoid division by zero when normalizing the input tensor. The data_format parameter specifies the layout of the input tensor, which can be either 'channels_last' or 'channels_first'. If an unsupported data format is provided, a NotImplementedError is raised.

Source code in mindnlp/transformers/models/sam/modeling_sam.py
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
def __init__(self, normalized_shape, eps=1e-6, data_format="channels_last"):
    """
    Initializes a new instance of the SamLayerNorm class.

    Args:
        self: The object itself.
        normalized_shape (tuple): The shape of the input tensor, indicating the size of each dimension.
        eps (float, optional): A small value to prevent division by zero when normalizing the input tensor.
            Defaults to 1e-06.
        data_format (str, optional): The format of the input tensor. Accepted values are 'channels_last' and
            'channels_first'. Defaults to 'channels_last'.

    Returns:
        None

    Raises:
        NotImplementedError: If the specified data format is not supported.

    This method initializes the SamLayerNorm object with the provided parameters. It sets the weight and bias
    parameters as trainable variables, initializes the epsilon value for numerical stability, and validates the
    data format. The normalized_shape parameter represents the size of each dimension of the input tensor.
    The eps parameter is used to avoid division by zero when normalizing the input tensor. The data_format parameter
    specifies the layout of the input tensor, which can be either 'channels_last' or 'channels_first'.
    If an unsupported data format is provided, a NotImplementedError is raised.
    """
    super().__init__()
    self.weight = Parameter(ops.ones(normalized_shape))
    self.bias = 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,)
    self.layer_norm = ops.LayerNorm(begin_norm_axis=-1,
                                  begin_params_axis=-1,
                                  epsilon=self.eps)

mindnlp.transformers.models.sam.modeling_sam.SamLayerNorm.forward(x)

Constructs a layer normalization operation for the SamLayerNorm class.

PARAMETER DESCRIPTION
self

The instance of the SamLayerNorm class.

TYPE: SamLayerNorm

x

The input tensor to be normalized.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

mindspore.Tensor: A normalized tensor based on the input tensor 'x'.

RAISES DESCRIPTION
ValueError

If the data format is not supported.

TypeError

If the input tensor 'x' is of an unsupported type.

RuntimeError

If any runtime error occurs during the normalization process.

Source code in mindnlp/transformers/models/sam/modeling_sam.py
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
def forward(self, x: mindspore.Tensor) -> mindspore.Tensor:
    """
    Constructs a layer normalization operation for the SamLayerNorm class.

    Args:
        self (SamLayerNorm): The instance of the SamLayerNorm class.
        x (mindspore.Tensor): The input tensor to be normalized.

    Returns:
        mindspore.Tensor: A normalized tensor based on the input tensor 'x'.

    Raises:
        ValueError: If the data format is not supported.
        TypeError: If the input tensor 'x' is of an unsupported type.
        RuntimeError: If any runtime error occurs during the normalization process.
    """
    if self.data_format == "channels_last":
        x, _, _ = self.layer_norm(x, self.weight, self.bias)
    elif self.data_format == "channels_first":
        input_dtype = x.dtype
        x = x.float()
        u = x.mean(1, keep_dims=True)
        s = (x - u).pow(2).mean(1, keep_dims=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.SamMLPBlock

Bases: Module

This class represents a Multi-Layer Perceptron (MLP) block used in a neural network. It inherits from the nn.Module class, a base class for all neural network modules in MindSpore.

ATTRIBUTE DESCRIPTION
lin1

The first dense layer of the MLP block.

TYPE: Linear

lin2

The second dense layer of the MLP block.

TYPE: Linear

act

The activation function used in the hidden layer of the MLP block.

TYPE: function

METHOD DESCRIPTION
__init__

Initializes the SamMLPBlock instance.

forward

Constructs the forward pass of the MLP block.

Source code in mindnlp/transformers/models/sam/modeling_sam.py
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
class SamMLPBlock(nn.Module):

    """
    This class represents a Multi-Layer Perceptron (MLP) block used in a neural network.
    It inherits from the nn.Module class, a base class for all neural network modules in MindSpore.

    Attributes:
        lin1 (nn.Linear): The first dense layer of the MLP block.
        lin2 (nn.Linear): The second dense layer of the MLP block.
        act (function): The activation function used in the hidden layer of the MLP block.

    Methods:
        __init__: Initializes the SamMLPBlock instance.
        forward: Constructs the forward pass of the MLP block.

    """
    def __init__(self, config):
        """
        Initializes an instance of the SamMLPBlock class.

        Args:
            self: The instance of the SamMLPBlock class.
            config: An object containing configuration parameters for the MLP block.
                It is expected to have the following attributes:

                - hidden_size (int): The size of the hidden layer.
                - mlp_dim (int): The dimension of the MLP layer.
                - hidden_act (str): The activation function to be applied to the hidden layers.

        Returns:
            None.

        Raises:
            KeyError: If the 'hidden_act' attribute in the 'config' parameter does not correspond to
                any activation function in ACT2FN.
            AttributeError: If the 'config' parameter is missing any of the required attributes.
        """
        super().__init__()
        self.lin1 = nn.Linear(config.hidden_size, config.mlp_dim)
        self.lin2 = nn.Linear(config.mlp_dim, config.hidden_size)
        self.act = ACT2FN[config.hidden_act]

    def forward(self, hidden_states: mindspore.Tensor) -> mindspore.Tensor:
        """
        Constructs a multi-layer perceptron block.

        Args:
            self (SamMLPBlock): The instance of the SamMLPBlock class.
            hidden_states (mindspore.Tensor): The input hidden states tensor to be processed.

        Returns:
            mindspore.Tensor: The processed hidden states tensor after passing through the MLP block.

        Raises:
            None
        """
        hidden_states = self.lin1(hidden_states)
        hidden_states = self.act(hidden_states)
        hidden_states = self.lin2(hidden_states)
        return hidden_states

mindnlp.transformers.models.sam.modeling_sam.SamMLPBlock.__init__(config)

Initializes an instance of the SamMLPBlock class.

PARAMETER DESCRIPTION
self

The instance of the SamMLPBlock class.

config

An object containing configuration parameters for the MLP block. It is expected to have the following attributes:

  • hidden_size (int): The size of the hidden layer.
  • mlp_dim (int): The dimension of the MLP layer.
  • hidden_act (str): The activation function to be applied to the hidden layers.

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
KeyError

If the 'hidden_act' attribute in the 'config' parameter does not correspond to any activation function in ACT2FN.

AttributeError

If the 'config' parameter is missing any of the required attributes.

Source code in mindnlp/transformers/models/sam/modeling_sam.py
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
def __init__(self, config):
    """
    Initializes an instance of the SamMLPBlock class.

    Args:
        self: The instance of the SamMLPBlock class.
        config: An object containing configuration parameters for the MLP block.
            It is expected to have the following attributes:

            - hidden_size (int): The size of the hidden layer.
            - mlp_dim (int): The dimension of the MLP layer.
            - hidden_act (str): The activation function to be applied to the hidden layers.

    Returns:
        None.

    Raises:
        KeyError: If the 'hidden_act' attribute in the 'config' parameter does not correspond to
            any activation function in ACT2FN.
        AttributeError: If the 'config' parameter is missing any of the required attributes.
    """
    super().__init__()
    self.lin1 = nn.Linear(config.hidden_size, config.mlp_dim)
    self.lin2 = nn.Linear(config.mlp_dim, config.hidden_size)
    self.act = ACT2FN[config.hidden_act]

mindnlp.transformers.models.sam.modeling_sam.SamMLPBlock.forward(hidden_states)

Constructs a multi-layer perceptron block.

PARAMETER DESCRIPTION
self

The instance of the SamMLPBlock class.

TYPE: SamMLPBlock

hidden_states

The input hidden states tensor to be processed.

TYPE: Tensor

RETURNS DESCRIPTION
Tensor

mindspore.Tensor: The processed hidden states tensor after passing through the MLP block.

Source code in mindnlp/transformers/models/sam/modeling_sam.py
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
def forward(self, hidden_states: mindspore.Tensor) -> mindspore.Tensor:
    """
    Constructs a multi-layer perceptron block.

    Args:
        self (SamMLPBlock): The instance of the SamMLPBlock class.
        hidden_states (mindspore.Tensor): The input hidden states tensor to be processed.

    Returns:
        mindspore.Tensor: The processed hidden states tensor after passing through the MLP block.

    Raises:
        None
    """
    hidden_states = self.lin1(hidden_states)
    hidden_states = self.act(hidden_states)
    hidden_states = self.lin2(hidden_states)
    return hidden_states

mindnlp.transformers.models.sam.modeling_sam.SamMaskDecoder

Bases: Module

A class representing a Mask Decoder module for generating masks based on image and prompt embeddings.

This class inherits from nn.Module and contains methods for initializing the decoder and forwarding the masks based on input embeddings. The decoder architecture includes components such as transformers, convolutional layers, embeddings, and feedforward networks to generate masks with optional attentions and predictions.

ATTRIBUTE DESCRIPTION
hidden_size

The size of the hidden layers in the decoder.

TYPE: int

num_multimask_outputs

The number of multimask outputs to be generated.

TYPE: int

num_mask_tokens

The total number of mask tokens used in the decoder.

TYPE: int

iou_token

Embedding layer for IOU tokens.

TYPE: Embedding

mask_tokens

Embedding layer for mask tokens.

TYPE: Embedding

transformer

Transformer network used in the decoding process.

TYPE: SamTwoWayTransformer

upscale_conv1

Transposed convolutional layer for upscaling.

TYPE: Conv2dTranspose

upscale_conv2

Additional transposed convolutional layer for upscaling.

TYPE: Conv2dTranspose

upscale_layer_norm

Layer normalization applied after upscaling.

TYPE: SamLayerNorm

activation

Activation function used in the decoder.

TYPE: GELU

output_hypernetworks_mlps

List of feedforward networks for output hypernetworks.

TYPE: ModuleList

iou_prediction_head

Feedforward network for IOU prediction.

TYPE: SamFeedForward

METHOD DESCRIPTION
__init__

Initializes the Mask Decoder with the provided configuration.

forward

Predicts masks based on input embeddings and returns the generated masks along with optional attentions.

For more details on the functionality and usage of the Mask Decoder class, refer to the method descriptions and class attributes above.

Source code in mindnlp/transformers/models/sam/modeling_sam.py
 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
class SamMaskDecoder(nn.Module):

    """
    A class representing a Mask Decoder module for generating masks based on image and prompt embeddings.

    This class inherits from nn.Module and contains methods for initializing the decoder and forwarding the masks
    based on input embeddings. The decoder architecture includes components such as transformers, convolutional layers,
    embeddings, and feedforward networks to generate masks with optional attentions and predictions.

    Attributes:
        hidden_size (int): The size of the hidden layers in the decoder.
        num_multimask_outputs (int): The number of multimask outputs to be generated.
        num_mask_tokens (int): The total number of mask tokens used in the decoder.
        iou_token (nn.Embedding): Embedding layer for IOU tokens.
        mask_tokens (nn.Embedding): Embedding layer for mask tokens.
        transformer (SamTwoWayTransformer): Transformer network used in the decoding process.
        upscale_conv1 (nn.Conv2dTranspose): Transposed convolutional layer for upscaling.
        upscale_conv2 (nn.Conv2dTranspose): Additional transposed convolutional layer for upscaling.
        upscale_layer_norm (SamLayerNorm): Layer normalization applied after upscaling.
        activation (nn.GELU): Activation function used in the decoder.
        output_hypernetworks_mlps (nn.ModuleList): List of feedforward networks for output hypernetworks.
        iou_prediction_head (SamFeedForward): Feedforward network for IOU prediction.

    Methods:
        __init__: Initializes the Mask Decoder with the provided configuration.
        forward: Predicts masks based on input embeddings and returns the generated masks along with optional attentions.

    For more details on the functionality and usage of the Mask Decoder class, refer to the method descriptions and class attributes above.
    """
    def __init__(self, config: SamMaskDecoderConfig):
        """
        Initialize the SamMaskDecoder class.

        Args:
            self: The instance of the SamMaskDecoder class.
            config (SamMaskDecoderConfig): An instance of the SamMaskDecoderConfig class containing the configuration
                parameters for the SamMaskDecoder.
                It includes the following attributes:

                - hidden_size (int): The size of the hidden state.
                - num_multimask_outputs (int): The number of multimask outputs.
                - num_mask_tokens (int): The number of mask tokens, which is calculated as
                config.num_multimask_outputs + 1.
                - iou_token (nn.Embedding): An embedding for the intersection over union (IOU) token with a shape of
                (1, hidden_size).
                - mask_tokens (nn.Embedding): An embedding for the mask tokens with a shape of
                (num_mask_tokens, hidden_size).
                - transformer (SamTwoWayTransformer): The SamTwoWayTransformer instance.
                - upscale_conv1 (nn.Conv2dTranspose): The first convolution layer for upscaling.
                - upscale_conv2 (nn.Conv2dTranspose): The second convolution layer for upscaling.
                - upscale_layer_norm (SamLayerNorm): The layer normalization for upscaling.
                - activation (nn.GELU): The activation function.
                - output_hypernetworks_mlps (nn.ModuleList): A list of SamFeedForward instances for output hypernetworks.
                - iou_prediction_head (SamFeedForward): The SamFeedForward instance for IOU prediction head.

        Returns:
            None.

        Raises:
            None
        """
        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.Conv2dTranspose(self.hidden_size, self.hidden_size // 4, kernel_size=2, stride=2, pad_mode='valid', bias=True)
        self.upscale_conv2 = nn.Conv2dTranspose(self.hidden_size // 4, self.hidden_size // 8, kernel_size=2, stride=2, pad_mode='valid', bias=True)
        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], axis=0)
        output_tokens = output_tokens.repeat(batch_size, point_batch_size, 1, 1)

        if sparse_prompt_embeddings.sum().item() != 0:
            tokens = ops.cat((output_tokens, sparse_prompt_embeddings), axis=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 = image_embeddings.repeat_interleave(point_batch_size, 0)
        image_positional_embeddings = image_positional_embeddings.repeat_interleave(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 = image_embeddings.swapaxes(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, axis=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.__init__(config)

Initialize the SamMaskDecoder class.

PARAMETER DESCRIPTION
self

The instance of the SamMaskDecoder class.

config

An instance of the SamMaskDecoderConfig class containing the configuration parameters for the SamMaskDecoder. It includes the following attributes:

  • hidden_size (int): The size of the hidden state.
  • num_multimask_outputs (int): The number of multimask outputs.
  • num_mask_tokens (int): The number of mask tokens, which is calculated as config.num_multimask_outputs + 1.
  • iou_token (nn.Embedding): An embedding for the intersection over union (IOU) token with a shape of (1, hidden_size).
  • mask_tokens (nn.Embedding): An embedding for the mask tokens with a shape of (num_mask_tokens, hidden_size).
  • transformer (SamTwoWayTransformer): The SamTwoWayTransformer instance.
  • upscale_conv1 (nn.Conv2dTranspose): The first convolution layer for upscaling.
  • upscale_conv2 (nn.Conv2dTranspose): The second convolution layer for upscaling.
  • upscale_layer_norm (SamLayerNorm): The layer normalization for upscaling.
  • activation (nn.GELU): The activation function.
  • output_hypernetworks_mlps (nn.ModuleList): A list of SamFeedForward instances for output hypernetworks.
  • iou_prediction_head (SamFeedForward): The SamFeedForward instance for IOU prediction head.

TYPE: SamMaskDecoderConfig

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/sam/modeling_sam.py
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
def __init__(self, config: SamMaskDecoderConfig):
    """
    Initialize the SamMaskDecoder class.

    Args:
        self: The instance of the SamMaskDecoder class.
        config (SamMaskDecoderConfig): An instance of the SamMaskDecoderConfig class containing the configuration
            parameters for the SamMaskDecoder.
            It includes the following attributes:

            - hidden_size (int): The size of the hidden state.
            - num_multimask_outputs (int): The number of multimask outputs.
            - num_mask_tokens (int): The number of mask tokens, which is calculated as
            config.num_multimask_outputs + 1.
            - iou_token (nn.Embedding): An embedding for the intersection over union (IOU) token with a shape of
            (1, hidden_size).
            - mask_tokens (nn.Embedding): An embedding for the mask tokens with a shape of
            (num_mask_tokens, hidden_size).
            - transformer (SamTwoWayTransformer): The SamTwoWayTransformer instance.
            - upscale_conv1 (nn.Conv2dTranspose): The first convolution layer for upscaling.
            - upscale_conv2 (nn.Conv2dTranspose): The second convolution layer for upscaling.
            - upscale_layer_norm (SamLayerNorm): The layer normalization for upscaling.
            - activation (nn.GELU): The activation function.
            - output_hypernetworks_mlps (nn.ModuleList): A list of SamFeedForward instances for output hypernetworks.
            - iou_prediction_head (SamFeedForward): The SamFeedForward instance for IOU prediction head.

    Returns:
        None.

    Raises:
        None
    """
    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.Conv2dTranspose(self.hidden_size, self.hidden_size // 4, kernel_size=2, stride=2, pad_mode='valid', bias=True)
    self.upscale_conv2 = nn.Conv2dTranspose(self.hidden_size // 4, self.hidden_size // 8, kernel_size=2, stride=2, pad_mode='valid', bias=True)
    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
    )

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
 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
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], axis=0)
    output_tokens = output_tokens.repeat(batch_size, point_batch_size, 1, 1)

    if sparse_prompt_embeddings.sum().item() != 0:
        tokens = ops.cat((output_tokens, sparse_prompt_embeddings), axis=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 = image_embeddings.repeat_interleave(point_batch_size, 0)
    image_positional_embeddings = image_positional_embeddings.repeat_interleave(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 = image_embeddings.swapaxes(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, axis=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.SamMaskEmbedding

Bases: Module

This class represents a mask embedding module used for generating dense embeddings from input masks. It consists of several convolutional and normalization layers for processing the input masks and producing dense embeddings. The class inherits from nn.Module.

ATTRIBUTE DESCRIPTION
mask_input_channels

Number of input channels for the mask

TYPE: int

activation

Activation function used in the module

TYPE: function

conv1

Convolutional layer 1

TYPE: Conv2d

conv2

Convolutional layer 2

TYPE: Conv2d

conv3

Convolutional layer 3

TYPE: Conv2d

layer_norm1

Layer normalization for the first layer

TYPE: SamLayerNorm

layer_norm2

Layer normalization for the second layer

TYPE: SamLayerNorm

METHOD DESCRIPTION
forward

Processes the input masks through the convolutional and normalization layers to generate dense embeddings

Source code in mindnlp/transformers/models/sam/modeling_sam.py
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
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
class SamMaskEmbedding(nn.Module):

    """
    This class represents a mask embedding module used for generating dense embeddings from input masks.
    It consists of several convolutional and normalization layers for processing the input masks and
    producing dense embeddings. The class inherits from nn.Module.

    Attributes:
        mask_input_channels (int): Number of input channels for the mask
        activation (function): Activation function used in the module
        conv1 (nn.Conv2d): Convolutional layer 1
        conv2 (nn.Conv2d): Convolutional layer 2
        conv3 (nn.Conv2d): Convolutional layer 3
        layer_norm1 (SamLayerNorm): Layer normalization for the first layer
        layer_norm2 (SamLayerNorm): Layer normalization for the second layer

    Methods:
        forward: Processes the input masks through the convolutional and normalization layers to generate dense
            embeddings
    """
    def __init__(self, config: SamPromptEncoderConfig):
        """
        Initializes the SamMaskEmbedding object with the provided configuration.

        Args:
            self: The instance of the SamMaskEmbedding class.
            config (SamPromptEncoderConfig): An instance of the SamPromptEncoderConfig class containing the
                configuration settings for the SamMaskEmbedding.

        Returns:
            None.

        Raises:
            None.
        """
        super().__init__()
        self.mask_input_channels = config.mask_input_channels // 4
        self.activation = ACT2FN[config.hidden_act]
        self.conv1 = nn.Conv2d(1, self.mask_input_channels, kernel_size=2, stride=2, pad_mode='valid', bias=True)
        self.conv2 = nn.Conv2d(self.mask_input_channels, config.mask_input_channels, kernel_size=2, stride=2, pad_mode='valid', bias=True)
        self.conv3 = nn.Conv2d(config.mask_input_channels, config.hidden_size, kernel_size=1, pad_mode='valid', bias=True)
        self.layer_norm1 = SamLayerNorm(
            self.mask_input_channels, eps=config.layer_norm_eps, data_format="channels_first"
        )
        self.layer_norm2 = SamLayerNorm(
            self.mask_input_channels * 4, eps=config.layer_norm_eps, data_format="channels_first"
        )

    def forward(self, masks):
        """
        Constructs dense embeddings from masks using convolutional layers.

        Args:
            self: An instance of the SamMaskEmbedding class.
            masks: A tensor of shape (batch_size, channels, height, width) representing the input masks.

        Returns:
            None: The method modifies the state of the object by updating the dense embeddings attribute.

        Raises:
            None.

        This method applies a series of convolutional layers to the input masks to generate dense embeddings.
        The process involves the following steps:

        1. Convolution 1: Applies a 2D convolutional operation to the masks tensor, resulting in hidden states.
        2. Layer Normalization 1: Performs layer normalization on the hidden states.
        3. Activation: Applies an activation function to the normalized hidden states.
        4. Convolution 2: Applies another 2D convolutional operation to the activated hidden states.
        5. Layer Normalization 2: Performs layer normalization on the hidden states from the second convolution.
        6. Activation: Applies the activation function to the normalized hidden states from the second convolution.
        7. Convolution 3: Applies a final 2D convolutional operation to the normalized hidden states from the
        second convolution.

        After these steps, the method returns the dense embeddings.
        """
        hidden_states = self.conv1(masks)
        hidden_states = self.layer_norm1(hidden_states)
        hidden_states = self.activation(hidden_states)

        hidden_states = self.conv2(hidden_states)
        hidden_states = self.layer_norm2(hidden_states)
        hidden_states = self.activation(hidden_states)
        dense_embeddings = self.conv3(hidden_states)
        return dense_embeddings

mindnlp.transformers.models.sam.modeling_sam.SamMaskEmbedding.__init__(config)

Initializes the SamMaskEmbedding object with the provided configuration.

PARAMETER DESCRIPTION
self

The instance of the SamMaskEmbedding class.

config

An instance of the SamPromptEncoderConfig class containing the configuration settings for the SamMaskEmbedding.

TYPE: SamPromptEncoderConfig

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/sam/modeling_sam.py
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
def __init__(self, config: SamPromptEncoderConfig):
    """
    Initializes the SamMaskEmbedding object with the provided configuration.

    Args:
        self: The instance of the SamMaskEmbedding class.
        config (SamPromptEncoderConfig): An instance of the SamPromptEncoderConfig class containing the
            configuration settings for the SamMaskEmbedding.

    Returns:
        None.

    Raises:
        None.
    """
    super().__init__()
    self.mask_input_channels = config.mask_input_channels // 4
    self.activation = ACT2FN[config.hidden_act]
    self.conv1 = nn.Conv2d(1, self.mask_input_channels, kernel_size=2, stride=2, pad_mode='valid', bias=True)
    self.conv2 = nn.Conv2d(self.mask_input_channels, config.mask_input_channels, kernel_size=2, stride=2, pad_mode='valid', bias=True)
    self.conv3 = nn.Conv2d(config.mask_input_channels, config.hidden_size, kernel_size=1, pad_mode='valid', bias=True)
    self.layer_norm1 = SamLayerNorm(
        self.mask_input_channels, eps=config.layer_norm_eps, data_format="channels_first"
    )
    self.layer_norm2 = SamLayerNorm(
        self.mask_input_channels * 4, eps=config.layer_norm_eps, data_format="channels_first"
    )

mindnlp.transformers.models.sam.modeling_sam.SamMaskEmbedding.forward(masks)

Constructs dense embeddings from masks using convolutional layers.

PARAMETER DESCRIPTION
self

An instance of the SamMaskEmbedding class.

masks

A tensor of shape (batch_size, channels, height, width) representing the input masks.

RETURNS DESCRIPTION
None

The method modifies the state of the object by updating the dense embeddings attribute.

This method applies a series of convolutional layers to the input masks to generate dense embeddings. The process involves the following steps:

  1. Convolution 1: Applies a 2D convolutional operation to the masks tensor, resulting in hidden states.
  2. Layer Normalization 1: Performs layer normalization on the hidden states.
  3. Activation: Applies an activation function to the normalized hidden states.
  4. Convolution 2: Applies another 2D convolutional operation to the activated hidden states.
  5. Layer Normalization 2: Performs layer normalization on the hidden states from the second convolution.
  6. Activation: Applies the activation function to the normalized hidden states from the second convolution.
  7. Convolution 3: Applies a final 2D convolutional operation to the normalized hidden states from the second convolution.

After these steps, the method returns the dense embeddings.

Source code in mindnlp/transformers/models/sam/modeling_sam.py
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
def forward(self, masks):
    """
    Constructs dense embeddings from masks using convolutional layers.

    Args:
        self: An instance of the SamMaskEmbedding class.
        masks: A tensor of shape (batch_size, channels, height, width) representing the input masks.

    Returns:
        None: The method modifies the state of the object by updating the dense embeddings attribute.

    Raises:
        None.

    This method applies a series of convolutional layers to the input masks to generate dense embeddings.
    The process involves the following steps:

    1. Convolution 1: Applies a 2D convolutional operation to the masks tensor, resulting in hidden states.
    2. Layer Normalization 1: Performs layer normalization on the hidden states.
    3. Activation: Applies an activation function to the normalized hidden states.
    4. Convolution 2: Applies another 2D convolutional operation to the activated hidden states.
    5. Layer Normalization 2: Performs layer normalization on the hidden states from the second convolution.
    6. Activation: Applies the activation function to the normalized hidden states from the second convolution.
    7. Convolution 3: Applies a final 2D convolutional operation to the normalized hidden states from the
    second convolution.

    After these steps, the method returns the dense embeddings.
    """
    hidden_states = self.conv1(masks)
    hidden_states = self.layer_norm1(hidden_states)
    hidden_states = self.activation(hidden_states)

    hidden_states = self.conv2(hidden_states)
    hidden_states = self.layer_norm2(hidden_states)
    hidden_states = self.activation(hidden_states)
    dense_embeddings = self.conv3(hidden_states)
    return dense_embeddings

mindnlp.transformers.models.sam.modeling_sam.SamModel

Bases: SamPreTrainedModel

The SamModel class is a Python class that represents a model for image segmentation tasks. It is a subclass of the SamPreTrainedModel class.

The SamModel class is typically used for image segmentation tasks. An example of how to use the SamModel class is provided in the docstring.

Note

This docstring provides an overview of the SamModel class and its methods. For more detailed information on the parameters and return types of each method, please refer to the method docstrings.

Source code in mindnlp/transformers/models/sam/modeling_sam.py
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
class SamModel(SamPreTrainedModel):

    """
    The `SamModel` class is a Python class that represents a model for image segmentation tasks.
    It is a subclass of the `SamPreTrainedModel` class.

    The `SamModel` class is typically used for image segmentation tasks. An example of how to use the `SamModel`
    class is provided in the docstring.

    Note:
        This docstring provides an overview of the `SamModel` class and its methods. For more detailed information
        on the parameters and return types of each method, please refer to the method docstrings.
    """
    _tied_weights_keys = ["prompt_encoder.shared_embedding.positional_embedding"]

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

        Args:
            self (SamModel): The current instance of the SamModel class.
            config (object): Configuration object containing various settings for the model.

        Returns:
            None.

        Raises:
            TypeError: If the provided 'config' parameter is not of type 'object'.
            ValueError: If the 'config' parameter is missing required settings or contains invalid values.
            RuntimeError: If any unexpected runtime error occurs during initialization.
        """
        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):
        """
        This method 'get_input_embeddings' in the class 'SamModel' retrieves the input embeddings from the vision encoder.

        Args:
            self: SamModel instance. Represents the current instance of the class.

        Returns:
            None: This method returns None as it simply retrieves the input embeddings from the vision encoder.

        Raises:
            None
        """
        return self.vision_encoder.get_input_embeddings()

    def get_image_wide_positional_embeddings(self):
        """
        This method calculates wide positional embeddings for an image in the SamModel class.

        Args:
            self: An instance of the SamModel class. It is used to access configuration parameters and shared image embeddings.

        Returns:
            positional_embedding (torch.Tensor): A tensor representing the positional embeddings for the image.
                The tensor is permuted and unsqueezed before returning.

        Raises:
            None
        """
        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 = grid.cumsum(axis=0) - 0.5
        x_embed = grid.cumsum(axis=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], axis=-1))
        return positional_embedding.permute(2, 0, 1).unsqueeze(0)  # channel x height x width

    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

    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="pt")
            ...
            >>> # 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.repeat(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.__init__(config)

Initializes a new instance of the SamModel class.

PARAMETER DESCRIPTION
self

The current instance of the SamModel class.

TYPE: SamModel

config

Configuration object containing various settings for the model.

TYPE: object

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the provided 'config' parameter is not of type 'object'.

ValueError

If the 'config' parameter is missing required settings or contains invalid values.

RuntimeError

If any unexpected runtime error occurs during initialization.

Source code in mindnlp/transformers/models/sam/modeling_sam.py
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
def __init__(self, config):
    """
    Initializes a new instance of the SamModel class.

    Args:
        self (SamModel): The current instance of the SamModel class.
        config (object): Configuration object containing various settings for the model.

    Returns:
        None.

    Raises:
        TypeError: If the provided 'config' parameter is not of type 'object'.
        ValueError: If the 'config' parameter is missing required settings or contains invalid values.
        RuntimeError: If any unexpected runtime error occurs during initialization.
    """
    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()

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)

Example
>>> 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="pt")
...
>>> # 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
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
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="pt")
        ...
        >>> # 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.repeat(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
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
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_image_wide_positional_embeddings()

This method calculates wide positional embeddings for an image in the SamModel class.

PARAMETER DESCRIPTION
self

An instance of the SamModel class. It is used to access configuration parameters and shared image embeddings.

RETURNS DESCRIPTION
positional_embedding

A tensor representing the positional embeddings for the image. The tensor is permuted and unsqueezed before returning.

TYPE: Tensor

Source code in mindnlp/transformers/models/sam/modeling_sam.py
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
def get_image_wide_positional_embeddings(self):
    """
    This method calculates wide positional embeddings for an image in the SamModel class.

    Args:
        self: An instance of the SamModel class. It is used to access configuration parameters and shared image embeddings.

    Returns:
        positional_embedding (torch.Tensor): A tensor representing the positional embeddings for the image.
            The tensor is permuted and unsqueezed before returning.

    Raises:
        None
    """
    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 = grid.cumsum(axis=0) - 0.5
    x_embed = grid.cumsum(axis=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], axis=-1))
    return positional_embedding.permute(2, 0, 1).unsqueeze(0)  # channel x height x width

mindnlp.transformers.models.sam.modeling_sam.SamModel.get_input_embeddings()

This method 'get_input_embeddings' in the class 'SamModel' retrieves the input embeddings from the vision encoder.

PARAMETER DESCRIPTION
self

SamModel instance. Represents the current instance of the class.

RETURNS DESCRIPTION
None

This method returns None as it simply retrieves the input embeddings from the vision encoder.

Source code in mindnlp/transformers/models/sam/modeling_sam.py
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
def get_input_embeddings(self):
    """
    This method 'get_input_embeddings' in the class 'SamModel' retrieves the input embeddings from the vision encoder.

    Args:
        self: SamModel instance. Represents the current instance of the class.

    Returns:
        None: This method returns None as it simply retrieves the input embeddings from the vision encoder.

    Raises:
        None
    """
    return self.vision_encoder.get_input_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
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
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 (