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 [
TYPE:
|
prompt_encoder_config |
Dictionary of configuration options used to initialize [
TYPE:
|
mask_decoder_config |
Dictionary of configuration options used to initialize [
TYPE:
|
kwargs |
Dictionary of keyword arguments.
TYPE:
|
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 | |
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:
|
prompt_encoder_config |
The configuration for prompt encoder. If provided, it should be an instance of SamPromptEncoderConfig. Defaults to None.
TYPE:
|
mask_decoder_config |
The configuration for mask decoder. If provided, it should be an instance of SamMaskDecoderConfig. Defaults to None.
TYPE:
|
initializer_range |
The range for weight initialization. Defaults to 0.02.
TYPE:
|
| 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 | |
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:
|
hidden_act |
The non-linear activation function used inside the
TYPE:
|
mlp_dim |
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
TYPE:
|
num_hidden_layers |
Number of hidden layers in the Transformer encoder.
TYPE:
|
num_attention_heads |
Number of attention heads for each attention layer in the Transformer encoder.
TYPE:
|
attention_downsample_rate |
The downsampling rate of the attention layer.
TYPE:
|
num_multimask_outputs |
The number of outputs from the
TYPE:
|
iou_head_depth |
The number of layers in the IoU head module.
TYPE:
|
iou_head_hidden_dim |
The dimensionality of the hidden states in the IoU head module.
TYPE:
|
layer_norm_eps |
The epsilon used by the layer normalization layers.
TYPE:
|
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 | |
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:
|
hidden_act |
The activation function to be used in the hidden layer. Default is 'relu'.
TYPE:
|
mlp_dim |
The dimension of the Multi-Layer Perceptron (MLP). Default is 2048.
TYPE:
|
num_hidden_layers |
The number of hidden layers. Default is 2.
TYPE:
|
num_attention_heads |
The number of attention heads. Default is 8.
TYPE:
|
attention_downsample_rate |
The downsample rate for attention. Default is 2.
TYPE:
|
num_multimask_outputs |
The number of outputs for multimask. Default is 3.
TYPE:
|
iou_head_depth |
The depth of the Intersection over Union (IoU) head. Default is 3.
TYPE:
|
iou_head_hidden_dim |
The hidden dimension of the IoU head. Default is 256.
TYPE:
|
layer_norm_eps |
The epsilon value for layer normalization. Default is 1e-06.
TYPE:
|
| 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 | |
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:
|
image_size |
The expected output resolution of the image.
TYPE:
|
patch_size |
The size (resolution) of each patch.
TYPE:
|
mask_input_channels |
The number of channels to be fed to the
TYPE:
|
num_point_embeddings |
The number of point embeddings to be used.
TYPE:
|
hidden_act |
The non-linear activation function in the encoder and pooler.
TYPE:
|
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 | |
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:
|
hidden_size |
The size of the hidden state. Defaults to 256.
TYPE:
|
image_size |
The size of the input image. Defaults to 1024.
TYPE:
|
patch_size |
The size of each image patch. Defaults to 16.
TYPE:
|
mask_input_channels |
The number of input channels for masking. Defaults to 16.
TYPE:
|
num_point_embeddings |
The number of point embeddings. Defaults to 4.
TYPE:
|
hidden_act |
The activation function for the hidden layers. Defaults to 'gelu'.
TYPE:
|
layer_norm_eps |
The epsilon value for layer normalization. Defaults to 1e-06.
TYPE:
|
| 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 | |
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:
|
output_channels |
Dimensionality of the output channels in the Patch Encoder.
TYPE:
|
num_hidden_layers |
Number of hidden layers in the Transformer encoder.
TYPE:
|
num_attention_heads |
Number of attention heads for each attention layer in the Transformer encoder.
TYPE:
|
num_channels |
Number of channels in the input image.
TYPE:
|
image_size |
Expected resolution. Target size of the resized input image.
TYPE:
|
patch_size |
Size of the patches to be extracted from the input image.
TYPE:
|
hidden_act |
The non-linear activation function (function or string)
TYPE:
|
layer_norm_eps |
The epsilon used by the layer normalization layers.
TYPE:
|
attention_dropout |
The dropout ratio for the attention probabilities.
TYPE:
|
initializer_range |
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
TYPE:
|
qkv_bias |
Whether to add a bias to query, key, value projections.
TYPE:
|
mlp_ratio |
Ratio of mlp hidden dim to embedding dim.
TYPE:
|
use_abs_pos |
Whether to use absolute position embedding.
TYPE:
|
use_rel_pos |
Whether to use relative position embedding.
TYPE:
|
window_size |
Window size for relative position.
TYPE:
|
global_attn_indexes |
The indexes of the global attention layers.
TYPE:
|
num_pos_feats |
The dimensionality of the position embedding.
TYPE:
|
mlp_dim |
The dimensionality of the MLP layer in the Transformer encoder. If
TYPE:
|
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 | |
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:
|
output_channels |
The number of output channels. Defaults to 256.
TYPE:
|
num_hidden_layers |
The number of hidden layers. Defaults to 12.
TYPE:
|
num_attention_heads |
The number of attention heads. Defaults to 12.
TYPE:
|
num_channels |
The number of input channels. Defaults to 3.
TYPE:
|
image_size |
The size of the input image. Defaults to 1024.
TYPE:
|
patch_size |
The size of each patch in the image. Defaults to 16.
TYPE:
|
hidden_act |
The activation function for the hidden layers. Defaults to 'gelu'.
TYPE:
|
layer_norm_eps |
The epsilon value for layer normalization. Defaults to 1e-06.
TYPE:
|
attention_dropout |
The dropout rate for the attention mechanism. Defaults to 0.0.
TYPE:
|
initializer_range |
The range for parameter initialization. Defaults to 1e-10.
TYPE:
|
qkv_bias |
Whether to include bias in the query, key, and value projections. Defaults to True.
TYPE:
|
mlp_ratio |
The ratio of the hidden size to the feed-forward network size. Defaults to 4.0.
TYPE:
|
use_abs_pos |
Whether to use absolute position embeddings. Defaults to True.
TYPE:
|
use_rel_pos |
Whether to use relative position embeddings. Defaults to True.
TYPE:
|
window_size |
The size of the attention window. Defaults to 14.
TYPE:
|
global_attn_indexes |
The list of indexes for global attention. Defaults to [2, 5, 8, 11].
TYPE:
|
num_pos_feats |
The number of positional features. Defaults to 128.
TYPE:
|
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:
|
| 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 | |
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
TYPE:
|
size |
Size of the output image after resizing. Resizes the longest edge of the image to match
TYPE:
|
mask_size |
Size of the output segmentation map after resizing. Resizes the longest edge of the image to match
TYPE:
|
resample |
Resampling filter to use if resizing the image. Can be overridden by the
TYPE:
|
do_rescale |
Wwhether to rescale the image by the specified scale
TYPE:
|
rescale_factor |
Scale factor to use if rescaling the image. Only has an effect if
TYPE:
|
do_normalize |
Whether to normalize the image. Can be overridden by the
TYPE:
|
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
TYPE:
|
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
TYPE:
|
do_pad |
Whether to pad the image to the specified
TYPE:
|
pad_size |
Size of the output image after padding. Can be overridden by the
TYPE:
|
mask_pad_size |
Size of the output segmentation map after padding. Can be overridden by the
TYPE:
|
do_convert_rgb |
Whether to convert the image to RGB.
TYPE:
|
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 | |
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:
|
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:
|
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:
|
resample |
The resampling method to use during image resizing. Defaults to PILImageResampling.BILINEAR.
TYPE:
|
do_rescale |
Determines whether rescaling of pixel values should be performed. Defaults to True.
TYPE:
|
rescale_factor |
The factor to divide pixel values by during rescaling. Defaults to 1 / 255.
TYPE:
|
do_normalize |
Determines whether normalization of pixel values should be performed. Defaults to True.
TYPE:
|
image_mean |
The mean values to subtract from pixel values during normalization. Defaults to None, which uses the IMAGENET_DEFAULT_MEAN.
TYPE:
|
image_std |
The standard deviation values to divide pixel values by during normalization. Defaults to None, which uses the IMAGENET_DEFAULT_STD.
TYPE:
|
do_pad |
Determines whether padding of images should be performed. Defaults to True.
TYPE:
|
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:
|
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:
|
do_convert_rgb |
Determines whether conversion to RGB color space should be performed. Defaults to True.
TYPE:
|
**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 | |
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:
|
iou_scores |
List of IoU scores.
TYPE:
|
original_size |
Size of the orginal image.
TYPE:
|
cropped_box_image |
The cropped image.
TYPE:
|
pred_iou_thresh |
The threshold for the iou scores.
TYPE:
|
stability_score_thresh |
The threshold for the stability score.
TYPE:
|
mask_threshold |
The threshold for the predicted masks.
TYPE:
|
stability_score_offset |
The offset for the stability score used in the
TYPE:
|
return_tensors |
If
TYPE:
|
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 | |
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:
|
target_size |
Target size of the resized image
TYPE:
|
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:
|
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:
|
points_per_crop |
Number of points to sample from each crop.
TYPE:
|
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:
|
input_data_format |
The channel dimension format of the input image. If not provided, it will be inferred.
TYPE:
|
return_tensors |
If
TYPE:
|
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 | |
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:
|
pad_size |
Size of the output image after padding.
TYPE:
|
data_format |
The data format of the image. Can be either "channels_first" or "channels_last". If
TYPE:
|
input_data_format |
The channel dimension format of the input image. If not provided, it will be inferred.
TYPE:
|
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 | |
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:
|
all_scores |
List of all predicted iou scores
TYPE:
|
all_boxes |
List of all bounding boxes of the predicted masks
TYPE:
|
crops_nms_thresh |
Threshold for NMS (Non Maximum Suppression) algorithm.
TYPE:
|
return_tensors |
If
TYPE:
|
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 | |
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:
|
original_sizes |
The original sizes of each image before it was resized to the model's expected input shape, in (height, width) format.
TYPE:
|
reshaped_input_sizes |
The size of each image as it is fed to the model, in (height, width) format. Used to remove padding.
TYPE:
|
mask_threshold |
The threshold to use for binarizing the masks.
TYPE:
|
binarize |
Whether to binarize the masks.
TYPE:
|
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
TYPE:
|
return_tensors |
If
TYPE:
|
| 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 | |
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
TYPE:
|
segmentation_maps |
Segmentation map to preprocess.
TYPE:
|
do_resize |
Whether to resize the image.
TYPE:
|
size |
Controls the size of the image after
TYPE:
|
mask_size |
Controls the size of the segmentation map after
TYPE:
|
resample |
TYPE:
|
do_rescale |
Whether to rescale the image pixel values by rescaling factor.
TYPE:
|
rescale_factor |
Rescale factor to apply to the image pixel values.
TYPE:
|
do_normalize |
Whether to normalize the image.
TYPE:
|
image_mean |
Image mean to normalize the image by if
TYPE:
|
image_std |
Image standard deviation to normalize the image by if
TYPE:
|
do_pad |
Whether to pad the image.
TYPE:
|
pad_size |
Controls the size of the padding applied to the image. The image is padded to
TYPE:
|
mask_pad_size |
Controls the size of the padding applied to the segmentation map. The image is padded to
TYPE:
|
do_convert_rgb |
Whether to convert the image to RGB.
TYPE:
|
return_tensors |
The type of tensors to return. Can be one of:
TYPE:
|
data_format |
The channel dimension format for the output image. Can be one of:
TYPE:
|
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:
TYPE:
|
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 | |
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:
|
size |
Dictionary in the format
TYPE:
|
resample |
TYPE:
|
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:
TYPE:
|
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:
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
|
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 | |
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
TYPE:
|
scores |
scores for each one of the boxes
TYPE:
|
idxs |
indices of the categories for each one of the boxes.
TYPE:
|
iou_threshold |
discards all overlapping boxes with IoU > iou_threshold
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
int64 tensor with the indices of the elements that have been kept by NMS, sorted in decreasing order of scores
TYPE:
|
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 | |
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:
|
scores |
A tensor of shape (N,) representing the scores associated with each bounding box.
TYPE:
|
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:
|
| 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 | |
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 | |
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:
|
| 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 | |
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:
|
query |
The query tensor of shape (batch_size, seq_length, embedding_dim) representing the query values.
TYPE:
|
key |
The key tensor of shape (batch_size, seq_length, embedding_dim) representing the key values.
TYPE:
|
value |
The value tensor of shape (batch_size, seq_length, embedding_dim) representing the value values.
TYPE:
|
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:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The output tensor of shape (batch_size, seq_length, embedding_dim) representing the attended values.
TYPE:
|
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 | |
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:
|
hidden_dim |
The dimension of the hidden layers.
TYPE:
|
output_dim |
The dimension of the output data.
TYPE:
|
num_layers |
The number of hidden layers in the network.
TYPE:
|
sigmoid_output |
If True, applies a sigmoid activation function to the output layer. Defaults to False.
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
num_layers |
The number of hidden layers in the network.
TYPE:
|
activation |
The rectified linear unit (ReLU) activation function.
TYPE:
|
proj_in |
The linear transformation for input data to the hidden layer.
TYPE:
|
proj_out |
The linear transformation for the last hidden layer to the output data.
TYPE:
|
layers |
List of Dense layers for the hidden layers in the network.
TYPE:
|
| 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 | |
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:
|
hidden_dim |
The dimension of the hidden layers.
TYPE:
|
output_dim |
The dimension of the output data.
TYPE:
|
num_layers |
The number of hidden layers in the network.
TYPE:
|
sigmoid_output |
Flag to indicate whether the output should be passed through a sigmoid activation function. Default is False.
TYPE:
|
| 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 | |
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:
|
hidden_states |
The input hidden states to be processed by the neural network.
TYPE:
|
| 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 | |
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:
|
pred_masks |
The predicted low resolutions masks. Needs to be post-processed by the processor
TYPE:
|
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 | |
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 | |
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:
|
eps |
A small value to prevent division by zero when normalizing the input tensor. Defaults to 1e-06.
TYPE:
|
data_format |
The format of the input tensor. Accepted values are 'channels_last' and 'channels_first'. Defaults to 'channels_last'.
TYPE:
|
| 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 | |
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:
|
x |
The input tensor to be normalized.
TYPE:
|
| 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 | |
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:
|
lin2 |
The second dense layer of the MLP block.
TYPE:
|
act |
The activation function used in the hidden layer of the MLP block.
TYPE:
|
| 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 | |
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:
|
| 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 | |
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:
|
hidden_states |
The input hidden states tensor to be processed.
TYPE:
|
| 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 | |
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:
|
num_multimask_outputs |
The number of multimask outputs to be generated.
TYPE:
|
num_mask_tokens |
The total number of mask tokens used in the decoder.
TYPE:
|
iou_token |
Embedding layer for IOU tokens.
TYPE:
|
mask_tokens |
Embedding layer for mask tokens.
TYPE:
|
transformer |
Transformer network used in the decoding process.
TYPE:
|
upscale_conv1 |
Transposed convolutional layer for upscaling.
TYPE:
|
upscale_conv2 |
Additional transposed convolutional layer for upscaling.
TYPE:
|
upscale_layer_norm |
Layer normalization applied after upscaling.
TYPE:
|
activation |
Activation function used in the decoder.
TYPE:
|
output_hypernetworks_mlps |
List of feedforward networks for output hypernetworks.
TYPE:
|
iou_prediction_head |
Feedforward network for IOU prediction.
TYPE:
|
| 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 | |
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:
TYPE:
|
| 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 | |
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:
|
image_positional_embedding |
positional encoding with the shape of image_embeddings
TYPE:
|
sparse_prompt_embeddings |
The embeddings of the points and boxes
TYPE:
|
dense_prompt_embeddings |
the embeddings of the mask inputs
TYPE:
|
multimask_output |
Whether to return multiple masks or a single mask.
TYPE:
|
output_attentions |
Whether or not to return the attentions tensors of all attention layers.
TYPE:
|
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 | |
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:
|
activation |
Activation function used in the module
TYPE:
|
conv1 |
Convolutional layer 1
TYPE:
|
conv2 |
Convolutional layer 2
TYPE:
|
conv3 |
Convolutional layer 3
TYPE:
|
layer_norm1 |
Layer normalization for the first layer
TYPE:
|
layer_norm2 |
Layer normalization for the second layer
TYPE:
|
| 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 | |
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:
|
| 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 | |
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:
- Convolution 1: Applies a 2D convolutional operation to the masks tensor, resulting in hidden states.
- Layer Normalization 1: Performs layer normalization on the hidden states.
- Activation: Applies an activation function to the normalized hidden states.
- Convolution 2: Applies another 2D convolutional operation to the activated hidden states.
- Layer Normalization 2: Performs layer normalization on the hidden states from the second convolution.
- Activation: Applies the activation function to the normalized hidden states from the second convolution.
- 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 | |
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 | |
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:
|
config |
Configuration object containing various settings for the model.
TYPE:
|
| 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 | |
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 | |
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:
|
output_attentions |
Whether or not to return the attentions tensors of all attention layers.
TYPE:
|
output_hidden_states |
Whether or not to return the hidden states of all layers.
TYPE:
|
return_dict |
Whether or not to return a [
TYPE:
|
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 | |
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:
|
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 | |
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 | |
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.
TYPE:
|
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:
|
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:
|
input_masks |
Optional input masks for the prompt encoder.
TYPE:
|
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 | |
mindnlp.transformers.models.sam.modeling_sam.SamPatchEmbeddings
¶
Bases: Module
This class turns pixel_values of shape (batch_size, num_channels, height, width) into the initial
hidden_states (patch embeddings) of shape (batch_size, seq_length, hidden_size) to be consumed by a
Transformer.
Source code in mindnlp/transformers/models/sam/modeling_sam.py
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 | |
mindnlp.transformers.models.sam.modeling_sam.SamPatchEmbeddings.__init__(config)
¶
Initializes an instance of the SamPatchEmbeddings class.
| PARAMETER | DESCRIPTION |
|---|---|
self |
The object instance.
|
config |
An object that stores configuration parameters for the SamPatchEmbeddings class.
|
| RETURNS | DESCRIPTION |
|---|---|
|
None. |
Source code in mindnlp/transformers/models/sam/modeling_sam.py
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 | |
mindnlp.transformers.models.sam.modeling_sam.SamPatchEmbeddings.forward(pixel_values)
¶
Construct method in the SamPatchEmbeddings class.
This method forwards embeddings for a given set of pixel values.
| PARAMETER | DESCRIPTION |
|---|---|
self |
An instance of the SamPatchEmbeddings class.
|
pixel_values |
A 4-dimensional array representing the pixel values of the input images.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
|
None |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
|
Source code in mindnlp/transformers/models/sam/modeling_sam.py
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 | |
mindnlp.transformers.models.sam.modeling_sam.SamPositionalEmbedding
¶
Bases: Module
The SamPositionalEmbedding class represents a positional encoding module that inherits from nn.Module. It provides functionality to positionally encode points normalized to the range [0,1] using sinusoidal and cosine functions.
| ATTRIBUTE | DESCRIPTION |
|---|---|
scale |
The scale value calculated as config.hidden_size // 2.
TYPE:
|
positional_embedding |
The positional embedding parameter calculated using random values with specified shape and no gradient.
TYPE:
|
| METHOD | DESCRIPTION |
|---|---|
forward |
Positionally encodes normalized points and returns the encoded coordinates as a concatenation of sinusoidal and cosine functions. |
Source code in mindnlp/transformers/models/sam/modeling_sam.py
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 | |
mindnlp.transformers.models.sam.modeling_sam.SamPositionalEmbedding.__init__(config)
¶
Initializes an instance of the SamPositionalEmbedding class.
| PARAMETER | DESCRIPTION |
|---|---|
self |
The current instance of the SamPositionalEmbedding class.
TYPE:
|
config |
The configuration object that holds various settings.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
|
None |
Source code in mindnlp/transformers/models/sam/modeling_sam.py
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 | |
mindnlp.transformers.models.sam.modeling_sam.SamPositionalEmbedding.forward(input_coords, input_shape=None)
¶
Positionally encode points that are normalized to [0,1].
Source code in mindnlp/transformers/models/sam/modeling_sam.py
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 | |
mindnlp.transformers.models.sam.modeling_sam.SamPreTrainedModel
¶
Bases: PreTrainedModel
A class representing a pretrained model in the Sam library.
This class, 'SamPreTrainedModel', is a subclass of the 'PreTrainedModel' class in the Sam library. It provides functionality for initializing the weights of different types of cells in the model. The weights are initialized using a normal distribution with a standard deviation specified in the configuration. If a bias term is present in the cell, it is initialized to zeros. For embedding cells, the weights are initialized using a normal distribution and a padding index, if provided, is set to zero.
| ATTRIBUTE | DESCRIPTION |
|---|---|
config |
The configuration object for the pretrained model.
TYPE:
|
| METHOD | DESCRIPTION |
|---|---|
_init_weights |
Initializes the weights of different types of cells in the model. |
Note
This class assumes that the model is built using cells from the Sam library, such as nn.Linear, nn.Conv2d, nn.Conv2dTranspose, and nn.Embedding.
Example
>>> model = SamPreTrainedModel(config)
>>> model._init_weights(cell)
Source code in mindnlp/transformers/models/sam/modeling_sam.py
1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 | |
mindnlp.transformers.models.sam.modeling_sam.SamPromptEncoder
¶
Bases: Module
A prompt encoder for sparse and dense embeddings.
This class represents a prompt encoder that embeds different types of prompts, returning both sparse and dense embeddings.
| PARAMETER | DESCRIPTION |
|---|---|
config |
The configuration for the prompt encoder.
TYPE:
|
shared_patch_embedding |
A shared patch embedding.
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
shared_embedding |
The shared patch embedding for the prompt encoder.
|
mask_embed |
The mask embedding for the prompt encoder.
|
no_mask_embed |
A tensor for no mask embedding.
|
image_embedding_size |
The size of the image embedding.
|
input_image_size |
The size of the input image.
|
point_embed |
A list of point embeddings.
|
hidden_size |
The hidden size for the prompt encoder.
|
not_a_point_embed |
The embedding for non-point prompts.
|
| METHOD | DESCRIPTION |
|---|---|
_embed_points |
Embeds point prompts. |
_embed_boxes |
Embeds box prompts. |
forward |
Embeds different types of prompts, |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If points are provided, labels must also be provided. |
Source code in mindnlp/transformers/models/sam/modeling_sam.py
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 | |
mindnlp.transformers.models.sam.modeling_sam.SamPromptEncoder.__init__(config, shared_patch_embedding)
¶
Initializes a new instance of SamPromptEncoder.
| PARAMETER | DESCRIPTION |
|---|---|
self |
The instance of the class.
|
config |
An instance of SamPromptEncoderConfig containing configuration parameters.
TYPE:
|
shared_patch_embedding |
The shared patch embedding used in the encoder.
|
| RETURNS | DESCRIPTION |
|---|---|
|
None. |
Source code in mindnlp/transformers/models/sam/modeling_sam.py
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 | |
mindnlp.transformers.models.sam.modeling_sam.SamPromptEncoder.forward(input_points, input_labels, input_boxes, input_masks)
¶
Embeds different types of prompts, returning both sparse and dense embeddings.
| PARAMETER | DESCRIPTION |
|---|---|
points |
point coordinates and labels to embed.
TYPE:
|
boxes |
boxes to embed
TYPE:
|
masks |
masks to embed
TYPE:
|
Source code in mindnlp/transformers/models/sam/modeling_sam.py
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 | |
mindnlp.transformers.models.sam.modeling_sam.SamTwoWayAttentionBlock
¶
Bases: Module
A transformer block with four layers:
- self-attention of sparse inputs
- cross attention of sparse inputs -> dense inputs
- mlp block on sparse inputs
- cross attention of dense inputs -> sparse inputs
This class represents a SamTwoWayAttentionBlock that implements a transformer block with the above-described layers. It inherits from nn.Module and is designed to handle attention mechanisms between sparse and dense inputs.
| PARAMETER | DESCRIPTION |
|---|---|
config |
The configuration file used to instantiate the block.
TYPE:
|
attention_downsample_rate |
The downsample ratio of the block used to reduce the inner dimension of the attention.
TYPE:
|
skip_first_layer_pe |
Whether or not to skip the addition of the query_point_embedding on the first layer.
TYPE:
|
| ATTRIBUTE | DESCRIPTION |
|---|---|
hidden_size |
The size of the hidden layers in the block.
TYPE:
|
layer_norm_eps |
The epsilon value for layer normalization.
TYPE:
|
self_attn |
The self-attention mechanism for sparse inputs.
TYPE:
|
layer_norm1 |
Layer normalization for the first layer.
TYPE:
|
cross_attn_token_to_image |
Cross-attention from token to image inputs.
TYPE:
|
layer_norm2 |
Layer normalization for the second layer.
TYPE:
|
mlp |
Multi-Layer Perceptron block for processing inputs.
TYPE:
|
layer_norm3 |
Layer normalization for the third layer.
TYPE:
|
layer_norm4 |
Layer normalization for the fourth layer.
TYPE:
|
cross_attn_image_to_token |
Cross-attention from image to token inputs.
TYPE:
|
Note
This class is specialized for two-way attention mechanisms in transformer architectures and is used to process sparse and dense inputs efficiently.
Source code in mindnlp/transformers/models/sam/modeling_sam.py
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 | |
mindnlp.transformers.models.sam.modeling_sam.SamTwoWayAttentionBlock.__init__(config, attention_downsample_rate=2, skip_first_layer_pe=False)
¶
A transformer block with four layers
(1) self-attention of sparse inputs (2) cross attention of sparse inputs -> dense inputs (3) mlp block on sparse inputs (4) cross attention of dense inputs -> sparse inputs
| PARAMETER | DESCRIPTION |
|---|---|
config |
The configuration file used to instantiate the block
TYPE:
|
attention_downsample_rate |
The downsample ratio of the block used to reduce the inner dim of the attention.
TYPE:
|
skip_first_layer_pe |
Whether or not to skip the addition of the query_point_embedding on the first layer.
TYPE:
|
Source code in mindnlp/transformers/models/sam/modeling_sam.py
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 | |
mindnlp.transformers.models.sam.modeling_sam.SamTwoWayAttentionBlock.forward(queries, keys, query_point_embedding, key_point_embedding, attention_similarity, output_attentions=False)
¶
This method forwards a two-way attention block for processing queries and keys in a neural network model.
| PARAMETER | DESCRIPTION |
|---|---|
self |
The instance of the class.
|
queries |
The input tensor representing queries for attention mechanism.
TYPE:
|
keys |
The input tensor representing keys for attention mechanism.
TYPE:
|
query_point_embedding |
The embedding tensor for query points.
TYPE:
|
key_point_embedding |
The embedding tensor for key points.
TYPE:
|
attention_similarity |
The tensor representing attention similarity scores.
TYPE:
|
output_attentions |
A flag indicating whether to output attention values. Defaults to False.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
|
Tuple[Tensor, Tensor, Tensor]: A tuple containing processed queries and keys, and optionally attention values. |
Source code in mindnlp/transformers/models/sam/modeling_sam.py
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 | |
mindnlp.transformers.models.sam.modeling_sam.SamTwoWayTransformer
¶
Bases: Module
This class represents a two-way transformer model called SamTwoWayTransformer. It is a subclass of nn.Module.
SamTwoWayTransformer is designed to perform two-way attention between point embeddings and image embeddings. It consists of multiple layers of SamTwoWayAttentionBlock, followed by a final attention step using SamAttention. The class also includes a layer normalization step.
The main purpose of this class is to forward the transformer model and generate the outputs based on the given inputs. The inputs include point embeddings, image embeddings, image positional embeddings, attention similarity, target embeddings (optional), and various optional parameters to control the output format.
The forwardor (init) initializes the SamTwoWayTransformer instance with a configuration object (config) of type SamMaskDecoderConfig. It sets the configuration, number of hidden layers, and initializes the list of layers.
The forward method takes the point embeddings, image embeddings, image positional embeddings, attention similarity, target embedding, and optional parameters as inputs. It performs the necessary computations to generate the outputs of the transformer model. The method supports optional arguments to control the output format, such as output_attentions, output_hidden_states, and return_dict. The method returns a tuple containing the queries, keys, and optionally, all the attention outputs.
Please note that this class requires the image_embeddings parameter to be specified. If it is not provided, a ValueError will be raised.
Source code in mindnlp/transformers/models/sam/modeling_sam.py
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 | |
mindnlp.transformers.models.sam.modeling_sam.SamTwoWayTransformer.__init__(config)
¶
Initializes a new instance of the SamTwoWayTransformer class.
| PARAMETER | DESCRIPTION |
|---|---|
self |
The instance of the class.
|
config |
The configuration object containing the parameters for the transformer.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
|
None |
Source code in mindnlp/transformers/models/sam/modeling_sam.py
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 | |
mindnlp.transformers.models.sam.modeling_sam.SamTwoWayTransformer.forward(point_embeddings, image_embeddings, image_positional_embeddings, attention_similarity, target_embedding=None, output_attentions=None, output_hidden_states=None, return_dict=None)
¶
Constructs the SamTwoWayTransformer.
This method initializes and forwards the SamTwoWayTransformer model by taking in various input parameters.
| PARAMETER | DESCRIPTION |
|---|---|
self |
The object instance.
|
point_embeddings |
The tensor representing the point embeddings.
TYPE:
|
image_embeddings |
The tensor representing the image embeddings.
TYPE:
|
image_positional_embeddings |
The tensor representing the positional embeddings of the images.
TYPE:
|
attention_similarity |
The tensor representing the attention similarity.
TYPE:
|
target_embedding |
The tensor representing the target embedding (default: None).
TYPE:
|
output_attentions |
Whether to output attentions (default: None).
TYPE:
|
output_hidden_states |
Whether to output hidden states (default: None).
TYPE:
|
return_dict |
Whether to use return dict (default: None).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Union[Tuple, BaseModelOutput]
|
Union[Tuple, BaseModelOutput]: The output of the SamTwoWayTransformer model. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
This exception is raised if the image_embeddings parameter is not specified. |
Note
- The output_attentions, output_hidden_states, and return_dict parameters will take values from the self.config object if not explicitly provided.
- This method performs various computations and transformations on the input tensors to forward the SamTwoWayTransformer model.
- The forwarded model is returned as an output.
Source code in mindnlp/transformers/models/sam/modeling_sam.py
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 | |
mindnlp.transformers.models.sam.modeling_sam.SamVisionAttention
¶
Bases: Module
Multi-head Attention block with relative position embeddings.
Source code in mindnlp/transformers/models/sam/modeling_sam.py
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 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 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 | |
mindnlp.transformers.models.sam.modeling_sam.SamVisionAttention.__init__(config, window_size)
¶
Initializes a SamVisionAttention object.
| PARAMETER | DESCRIPTION |
|---|---|
self |
The object itself.
|
config |
An instance of a configuration class containing various parameters. It specifies the configuration settings for the attention mechanism.
|
window_size |
An integer representing the size of the window. If set to 0, the window size is determined based on the config's image size. It determines the size of the attention window.
|
| RETURNS | DESCRIPTION |
|---|---|
|
None |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If input_size is None and use_rel_pos is True. |
Source code in mindnlp/transformers/models/sam/modeling_sam.py
1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 | |
mindnlp.transformers.models.sam.modeling_sam.SamVisionAttention.add_decomposed_rel_pos(attn, query, rel_pos_h, rel_pos_w, q_size, k_size)
¶
Calculate decomposed Relative Positional Embeddings from :paper:mvitv2.
https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py
| PARAMETER | DESCRIPTION |
|---|---|
attn |
attention map.
TYPE:
|
query |
query q in the attention layer with shape (batch_size, query_height * query_width, channel).
TYPE:
|
rel_pos_h |
relative position embeddings (Lh, channel) for height axis.
TYPE:
|
rel_pos_w |
relative position embeddings (Lw, channel) for width axis.
TYPE:
|
q_size |
spatial sequence size of query q with (query_height, query_width).
TYPE:
|
k_size |
spatial sequence size of key k with (key_height, key_width).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
attn
|
attention map with added relative positional embeddings.
TYPE:
|
Source code in mindnlp/transformers/models/sam/modeling_sam.py
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 | |
mindnlp.transformers.models.sam.modeling_sam.SamVisionAttention.forward(hidden_states, output_attentions=False)
¶
Method 'forward' in the class 'SamVisionAttention'.
| PARAMETER | DESCRIPTION |
|---|---|
self |
SamVisionAttention object. Represents the instance of the SamVisionAttention class.
|
hidden_states |
mindspore.Tensor. Input tensor of shape (batch_size, height, width, _), where _ represents a dimension. Contains the hidden states to be processed.
TYPE:
|
output_attentions |
bool. Indicates whether to output the attention weights. Default is False. If True, the attention weights will be included in the return value.
DEFAULT:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Tuple[Tensor]: Tuple of two elements - attn_output: mindspore.Tensor. Output tensor after attention mechanism processing. If output_attentions is True, the second element is attn_weights: mindspore.Tensor. Attention weights tensor. The return value represents the result of applying the attention mechanism on the hidden_states input. |
Source code in mindnlp/transformers/models/sam/modeling_sam.py
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 | |
mindnlp.transformers.models.sam.modeling_sam.SamVisionAttention.get_rel_pos(q_size, k_size, rel_pos)
¶
Get relative positional embeddings according to the relative positions of query and key sizes.
| PARAMETER | DESCRIPTION |
|---|---|
q_size |
size of the query.
TYPE:
|
k_size |
size of key k.
TYPE:
|
rel_pos |
relative position embeddings (L, channel).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
Extracted positional embeddings according to relative positions. |
Source code in mindnlp/transformers/models/sam/modeling_sam.py
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 | |
mindnlp.transformers.models.sam.modeling_sam.SamVisionEncoder
¶
Bases: Module
The SamVisionEncoder class represents a vision encoder for processing image data using the SAM (Self-Attention Model) architecture. It inherits from the nn.Module class and is designed to be used within the MindSpore framework for deep learning applications.
The class initializes with a SamVisionConfig object and sets various attributes based on the provided configuration. It includes methods for retrieving input embeddings and forwarding the encoder output based on the input pixel values. The forwardion process involves passing the input through the patch embeddings, applying positional embeddings if configured, processing the input through multiple vision layers, and finally passing the output through a vision neck module.
The class also provides options for controlling the output of attentions and hidden states, as well as the ability to return the output as a dictionary. Additionally, it supports gradient checkpointing during training for efficient memory usage.
Overall, the SamVisionEncoder class encapsulates the functionality for encoding image data using the SAM architecture, providing a flexible and configurable interface for vision processing tasks within the MindSpore framework.
Source code in mindnlp/transformers/models/sam/modeling_sam.py
1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 | |
mindnlp.transformers.models.sam.modeling_sam.SamVisionEncoder.__init__(config)
¶
Initializes a SamVisionEncoder object.
| PARAMETER | DESCRIPTION |
|---|---|
self |
The object itself.
|
config |
An instance of SamVisionConfig containing configuration parameters.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
|
None |
Source code in mindnlp/transformers/models/sam/modeling_sam.py
1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 | |
mindnlp.transformers.models.sam.modeling_sam.SamVisionEncoder.forward(pixel_values=None, output_attentions=None, output_hidden_states=None, return_dict=None)
¶
Constructs the SamVisionEncoder.
| PARAMETER | DESCRIPTION |
|---|---|
self |
The instance of the SamVisionEncoder class.
TYPE:
|
pixel_values |
The input pixel values. Default is None.
TYPE:
|
output_attentions |
Whether to output attentions. Default is None.
TYPE:
|
output_hidden_states |
Whether to output hidden states. Default is None.
TYPE:
|
return_dict |
Whether to return a dictionary. Default is None.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Union[Tuple, SamVisionEncoderOutput]
|
Union[Tuple, SamVisionEncoderOutput]: The output of the SamVisionEncoder. |
Union[Tuple, SamVisionEncoderOutput]
|
If return_dict is False, returns a tuple containing the hidden states, |
Union[Tuple, SamVisionEncoderOutput]
|
all_hidden_states (if output_hidden_states is True), and all_self_attentions (if output_attentions is True). |
Union[Tuple, SamVisionEncoderOutput]
|
If return_dict is True, returns a SamVisionEncoderOutput object containing the last hidden state, |
Union[Tuple, SamVisionEncoderOutput]
|
all_hidden_states, and all_self_attentions. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If pixel_values is None. |
Source code in mindnlp/transformers/models/sam/modeling_sam.py
1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 | |
mindnlp.transformers.models.sam.modeling_sam.SamVisionEncoder.get_input_embeddings()
¶
Retrieves the input embeddings of the SamVisionEncoder.
| PARAMETER | DESCRIPTION |
|---|---|
self |
An instance of the SamVisionEncoder class.
|
| RETURNS | DESCRIPTION |
|---|---|
|
None. |
This method retrieves the input embeddings used by the SamVisionEncoder. The input embeddings are obtained from the patch embedding process performed by the 'patch_embed' method.
Source code in mindnlp/transformers/models/sam/modeling_sam.py
1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 | |
mindnlp.transformers.models.sam.modeling_sam.SamVisionEncoderOutput
dataclass
¶
Bases: ModelOutput
Base class for sam vision model's outputs that also contains image embeddings obtained by applying the projection layer to the pooler_output.
| PARAMETER | DESCRIPTION |
|---|---|
last_hidden_state |
Sequence of hidden-states at the output of the last layer of the model.
TYPE:
|
Source code in mindnlp/transformers/models/sam/modeling_sam.py
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 | |
mindnlp.transformers.models.sam.modeling_sam.SamVisionLayer
¶
Bases: Module
This class represents a vision layer in the SamVision model. It inherits from the nn.Module class and implements the necessary methods and functionality for performing attention-based operations on input image tokens.
| ATTRIBUTE | DESCRIPTION |
|---|---|
layer_norm1 |
An instance of nn.LayerNorm which applies layer normalization to the input hidden states.
|
attn |
An instance of the SamVisionAttention class which performs attention computation on the hidden states.
|
layer_norm2 |
An instance of nn.LayerNorm which applies layer normalization to the output hidden states.
|
mlp |
An instance of the SamMLPBlock class which applies multi-layer perceptron operations to the output hidden states.
|
window_size |
An integer representing the size of the attention windows.
|
| METHOD | DESCRIPTION |
|---|---|
window_partition |
Partitions the input hidden states into non-overlapping windows with padding if needed. |
window_unpartition |
Unpartitions the windows into original sequences, removing padding. |
forward |
Constructs the output hidden states by applying layer normalization, attention, and MLP operations. |
Example
>>> config = Configuration()
>>> window_size = 16
>>> vision_layer = SamVisionLayer(config, window_size)
>>> hidden_states = torch.randn(batch_size, height, width, channel)
>>> output = vision_layer.forward(hidden_states)
Source code in mindnlp/transformers/models/sam/modeling_sam.py
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 | |
mindnlp.transformers.models.sam.modeling_sam.SamVisionLayer.__init__(config, window_size)
¶
Initializes a new instance of SamVisionLayer.
| PARAMETER | DESCRIPTION |
|---|---|
self |
The instance of the class.
|
config |
A configuration object containing the hidden size and layer normalization epsilon.
|
window_size |
An integer specifying the size of the vision window.
|
| RETURNS | DESCRIPTION |
|---|---|
|
None. |
Source code in mindnlp/transformers/models/sam/modeling_sam.py
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 | |
mindnlp.transformers.models.sam.modeling_sam.SamVisionLayer.forward(hidden_states, output_attentions=False)
¶
This method forwards the SamVisionLayer by applying attention mechanism and multi-layer perceptron (MLP) to the input hidden states.
| PARAMETER | DESCRIPTION |
|---|---|
self |
The instance of the SamVisionLayer class.
|
hidden_states |
The input tensor representing the hidden states. It is expected to be a tensor of shape (batch_size, sequence_length, hidden_size).
TYPE:
|
output_attentions |
A flag indicating whether to output the attention weights. Default is False.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tuple[Tensor]
|
Tuple[mindspore.Tensor]: A tuple containing the output hidden states tensor after applying attention mechanism and MLP. |
Source code in mindnlp/transformers/models/sam/modeling_sam.py
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 | |
mindnlp.transformers.models.sam.modeling_sam.SamVisionLayer.window_partition(hidden_states, window_size)
¶
Partition into non-overlapping windows with padding if needed.
| PARAMETER | DESCRIPTION |
|---|---|
hidden_states |
input tokens with [batch_size, height, width, channel]. window_size (int): window size.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
windows
|
windows after partition with [batch_size * num_windows, window_size, window_size, channel]. (pad_height, pad_width): padded height and width before partition
TYPE:
|
Source code in mindnlp/transformers/models/sam/modeling_sam.py
1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 | |
mindnlp.transformers.models.sam.modeling_sam.SamVisionLayer.window_unpartition(windows, window_size, padding_shape, original_shape)
¶
Window unpartition into original sequences and removing padding.
| PARAMETER | DESCRIPTION |
|---|---|
hidden_states |
input tokens with [batch_size * num_windows, window_size, window_size, channel].
TYPE:
|
window_size |
window size.
TYPE:
|
padding_shape |
padded height and width (pad_height, pad_width).
TYPE:
|
original_shape |
original height and width (height, width) before padding.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
hidden_states
|
unpartitioned sequences with [batch_size, height, width, channel].
TYPE:
|
Source code in mindnlp/transformers/models/sam/modeling_sam.py
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 | |
mindnlp.transformers.models.sam.modeling_sam.SamVisionNeck
¶
Bases: Module
This class represents the SamVisionNeck module, which is a component of a vision model that performs operations on hidden states.
SamVisionNeck inherits from the nn.Module class and includes two convolutional layers with layer normalization. The hidden states are passed through these layers to extract relevant features.
| ATTRIBUTE | DESCRIPTION |
|---|---|
config |
The configuration object that defines the parameters for the SamVisionNeck module.
TYPE:
|
conv1 |
The first convolutional layer that processes the hidden states.
TYPE:
|
layer_norm1 |
The first layer normalization module that normalizes the output of the first convolutional layer.
TYPE:
|
conv2 |
The second convolutional layer that further processes the hidden states.
TYPE:
|
layer_norm2 |
The second layer normalization module that normalizes the output of the second convolutional layer.
TYPE:
|
| METHOD | DESCRIPTION |
|---|---|
__init__ |
Initializes a new instance of the SamVisionNeck class with the given configuration. |
forward |
Processes the hidden states through the convolutional and layer normalization layers. |
Source code in mindnlp/transformers/models/sam/modeling_sam.py
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 | |
mindnlp.transformers.models.sam.modeling_sam.SamVisionNeck.__init__(config)
¶
Initialize the SamVisionNeck class.
| PARAMETER | DESCRIPTION |
|---|---|
self |
The instance of the class.
|
config |
An instance of SamVisionConfig containing the configuration for the SamVisionNeck. It defines the parameters required for the layers in the network.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
|
None. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the configuration provided is invalid or incomplete. |
TypeError
|
If the configuration data type is not as expected. |
RuntimeError
|
If there is an issue during the initialization of the layers. |
Source code in mindnlp/transformers/models/sam/modeling_sam.py
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 | |
mindnlp.transformers.models.sam.modeling_sam.SamVisionNeck.forward(hidden_states)
¶
Constructs the hidden states in the SamVisionNeck class.
This method takes in two parameters: self and hidden_states. The hidden_states parameter represents the input hidden states and should be a tensor. The purpose of this parameter is to provide the input for forwarding the hidden states. There are no restrictions on the shape or size of the hidden_states tensor.
The method performs the following operations on the hidden_states:
- Permute the dimensions of the hidden_states tensor using the permute() function, with the dimensions permuted as (0, 3, 1, 2).
- Apply the conv1 layer to the permuted hidden_states tensor.
- Apply the layer_norm1 layer to the output of the conv1 layer.
- Apply the conv2 layer to the output of the layer_norm1 layer.
- Apply the layer_norm2 layer to the output of the conv2 layer.
The method returns the final forwarded hidden states tensor.
| PARAMETER | DESCRIPTION |
|---|---|
self |
An instance of the SamVisionNeck class.
|
hidden_states |
A tensor representing the input hidden states.
|
| RETURNS | DESCRIPTION |
|---|---|
hidden_states
|
The method returns the forwarded hidden states as a tensor. |
Source code in mindnlp/transformers/models/sam/modeling_sam.py
1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 | |
mindnlp.transformers.models.sam.processing_sam
¶
Processor class for SAM.
mindnlp.transformers.models.sam.processing_sam.SamProcessor
¶
Bases: ProcessorMixin
Constructs a SAM processor which wraps a SAM image processor and an 2D points & Bounding boxes processor into a single processor.
[SamProcessor] offers all the functionalities of [SamImageProcessor]. See the docstring of
[~SamImageProcessor.__call__] for more information.
| PARAMETER | DESCRIPTION |
|---|---|
image_processor |
An instance of [
TYPE:
|
Source code in mindnlp/transformers/models/sam/processing_sam.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 | |
mindnlp.transformers.models.sam.processing_sam.SamProcessor.model_input_names
property
¶
This method returns a list of unique model input names used in the SamProcessor class.
| PARAMETER | DESCRIPTION |
|---|---|
self |
The instance of the SamProcessor class.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list
|
A list of unique model input names extracted from the image processor. |
mindnlp.transformers.models.sam.processing_sam.SamProcessor.__call__(images=None, segmentation_maps=None, input_points=None, input_labels=None, input_boxes=None, return_tensors=None, **kwargs)
¶
This method uses [SamImageProcessor.__call__] method to prepare image(s) for the model. It also prepares 2D
points and bounding boxes for the model if they are provided.
Source code in mindnlp/transformers/models/sam/processing_sam.py
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 | |
mindnlp.transformers.models.sam.processing_sam.SamProcessor.__init__(image_processor)
¶
Initializes a new instance of the SamProcessor class.
| PARAMETER | DESCRIPTION |
|---|---|
self |
The instance of the SamProcessor class.
|
image_processor |
An image processor object used for image processing operations.
|
| RETURNS | DESCRIPTION |
|---|---|
|
None. |
Source code in mindnlp/transformers/models/sam/processing_sam.py
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | |
mindnlp.transformers.models.sam.processing_sam.SamProcessor.post_process_masks(*args, **kwargs)
¶
Post-processes masks using the image processor.
| PARAMETER | DESCRIPTION |
|---|---|
self |
The instance of the SamProcessor class.
|
| RETURNS | DESCRIPTION |
|---|---|
|
None. |
Source code in mindnlp/transformers/models/sam/processing_sam.py
298 299 300 301 302 303 304 305 306 307 308 309 310 311 | |