Skip to content

blenderbot_small

mindnlp.transformers.models.blenderbot_small.configuration_blenderbot_small.BlenderbotSmallConfig

Bases: PretrainedConfig

This is the configuration class to store the configuration of a [BlenderbotSmallModel]. It is used to instantiate an BlenderbotSmall model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the BlenderbotSmall facebook/blenderbot_small-90M 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
vocab_size

Vocabulary size of the BlenderbotSmall model. Defines the number of different tokens that can be represented by the inputs_ids passed when calling [BlenderbotSmallModel] or [TFBlenderbotSmallModel].

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

d_model

Dimensionality of the layers and the pooler layer.

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

encoder_layers

Number of encoder layers.

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

decoder_layers

Number of decoder layers.

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

encoder_attention_heads

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

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

decoder_attention_heads

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

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

decoder_ffn_dim

Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.

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

encoder_ffn_dim

Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.

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

activation_function

The non-linear activation function (function or string) in the encoder and pooler. If string, "gelu", "relu", "silu" and "gelu_new" are supported.

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

dropout

The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.

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

attention_dropout

The dropout ratio for the attention probabilities.

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

activation_dropout

The dropout ratio for activations inside the fully connected layer.

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

max_position_embeddings

The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048).

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

init_std

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

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

encoder_layerdrop

The LayerDrop probability for the encoder. See the LayerDrop paper for more details.

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

decoder_layerdrop

The LayerDrop probability for the decoder. See the LayerDrop paper for more details.

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

scale_embedding

Scale embeddings by diving by sqrt(d_model).

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

use_cache

Whether or not the model should return the last key/values attentions (not used by all models)

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

forced_eos_token_id

The id of the token to force as the last generated token when max_length is reached. Usually set to eos_token_id.

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

Example
>>> from transformers import BlenderbotSmallConfig, BlenderbotSmallModel
...
>>> # Initializing a BlenderbotSmall facebook/blenderbot_small-90M style configuration
>>> configuration = BlenderbotSmallConfig()
...
>>> # Initializing a model (with random weights) from the facebook/blenderbot_small-90M style configuration
>>> model = BlenderbotSmallModel(configuration)
...
>>> # Accessing the model configuration
>>> configuration = model.config
Source code in mindnlp/transformers/models/blenderbot_small/configuration_blenderbot_small.py
 23
 24
 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
 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
class BlenderbotSmallConfig(PretrainedConfig):
    r"""
    This is the configuration class to store the configuration of a [`BlenderbotSmallModel`]. It is used to instantiate
    an BlenderbotSmall model according to the specified arguments, defining the model architecture. Instantiating a
    configuration with the defaults will yield a similar configuration to that of the BlenderbotSmall
    [facebook/blenderbot_small-90M](https://huggingface.co/facebook/blenderbot_small-90M) architecture.

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


    Args:
        vocab_size (`int`, *optional*, defaults to 50265):
            Vocabulary size of the BlenderbotSmall model. Defines the number of different tokens that can be
            represented by the `inputs_ids` passed when calling [`BlenderbotSmallModel`] or [`TFBlenderbotSmallModel`].
        d_model (`int`, *optional*, defaults to 512):
            Dimensionality of the layers and the pooler layer.
        encoder_layers (`int`, *optional*, defaults to 8):
            Number of encoder layers.
        decoder_layers (`int`, *optional*, defaults to 8):
            Number of decoder layers.
        encoder_attention_heads (`int`, *optional*, defaults to 16):
            Number of attention heads for each attention layer in the Transformer encoder.
        decoder_attention_heads (`int`, *optional*, defaults to 16):
            Number of attention heads for each attention layer in the Transformer decoder.
        decoder_ffn_dim (`int`, *optional*, defaults to 2048):
            Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
        encoder_ffn_dim (`int`, *optional*, defaults to 2048):
            Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
        activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
            The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
            `"relu"`, `"silu"` and `"gelu_new"` are supported.
        dropout (`float`, *optional*, defaults to 0.1):
            The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
        attention_dropout (`float`, *optional*, defaults to 0.0):
            The dropout ratio for the attention probabilities.
        activation_dropout (`float`, *optional*, defaults to 0.0):
            The dropout ratio for activations inside the fully connected layer.
        max_position_embeddings (`int`, *optional*, defaults to 512):
            The maximum sequence length that this model might ever be used with. Typically set this to something large
            just in case (e.g., 512 or 1024 or 2048).
        init_std (`float`, *optional*, defaults to 0.02):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
        encoder_layerdrop (`float`, *optional*, defaults to 0.0):
            The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
            for more details.
        decoder_layerdrop (`float`, *optional*, defaults to 0.0):
            The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
            for more details.
        scale_embedding (`bool`, *optional*, defaults to `False`):
            Scale embeddings by diving by sqrt(d_model).
        use_cache (`bool`, *optional*, defaults to `True`):
            Whether or not the model should return the last key/values attentions (not used by all models)
        forced_eos_token_id (`int`, *optional*, defaults to 2):
            The id of the token to force as the last generated token when `max_length` is reached. Usually set to
            `eos_token_id`.

    Example:
        ```python
        >>> from transformers import BlenderbotSmallConfig, BlenderbotSmallModel
        ...
        >>> # Initializing a BlenderbotSmall facebook/blenderbot_small-90M style configuration
        >>> configuration = BlenderbotSmallConfig()
        ...
        >>> # Initializing a model (with random weights) from the facebook/blenderbot_small-90M style configuration
        >>> model = BlenderbotSmallModel(configuration)
        ...
        >>> # Accessing the model configuration
        >>> configuration = model.config
        ```
    """
    model_type = "blenderbot-small"
    keys_to_ignore_at_inference = ["past_key_values"]
    attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}

    def __init__(
        self,
        vocab_size=50265,
        max_position_embeddings=512,
        encoder_layers=8,
        encoder_ffn_dim=2048,
        encoder_attention_heads=16,
        decoder_layers=8,
        decoder_ffn_dim=2048,
        decoder_attention_heads=16,
        encoder_layerdrop=0.0,
        decoder_layerdrop=0.0,
        use_cache=True,
        is_encoder_decoder=True,
        activation_function="gelu",
        d_model=512,
        dropout=0.1,
        attention_dropout=0.0,
        activation_dropout=0.0,
        init_std=0.02,
        decoder_start_token_id=1,
        scale_embedding=False,
        pad_token_id=0,
        bos_token_id=1,
        eos_token_id=2,
        forced_eos_token_id=2,
        **kwargs,
    ):
        """
        Initializes a new instance of the BlenderbotSmallConfig class.

        Args:
            vocab_size (int, optional): The size of the vocabulary. Defaults to 50265.
            max_position_embeddings (int, optional): The maximum position of the embeddings. Defaults to 512.
            encoder_layers (int, optional): The number of encoder layers. Defaults to 8.
            encoder_ffn_dim (int, optional): The dimension of the encoder feed-forward network. Defaults to 2048.
            encoder_attention_heads (int, optional): The number of attention heads for the encoder. Defaults to 16.
            decoder_layers (int, optional): The number of decoder layers. Defaults to 8.
            decoder_ffn_dim (int, optional): The dimension of the decoder feed-forward network. Defaults to 2048.
            decoder_attention_heads (int, optional): The number of attention heads for the decoder. Defaults to 16.
            encoder_layerdrop (float, optional): The probability of dropping an encoder layer. Defaults to 0.0.
            decoder_layerdrop (float, optional): The probability of dropping a decoder layer. Defaults to 0.0.
            use_cache (bool, optional): Whether to use cache. Defaults to True.
            is_encoder_decoder (bool, optional): Determines if the model is an encoder-decoder. Defaults to True.
            activation_function (str, optional): The activation function to be used. Defaults to 'gelu'.
            d_model (int, optional): The dimension of the model. Defaults to 512.
            dropout (float, optional): The dropout probability. Defaults to 0.1.
            attention_dropout (float, optional): The dropout probability for attention layers. Defaults to 0.0.
            activation_dropout (float, optional): The dropout probability for activation layers. Defaults to 0.0.
            init_std (float, optional): The standard deviation for weight initialization. Defaults to 0.02.
            decoder_start_token_id (int, optional): The ID of the start token for the decoder. Defaults to 1.
            scale_embedding (bool, optional): Whether to scale the embeddings. Defaults to False.
            pad_token_id (int, optional): The ID of the padding token. Defaults to 0.
            bos_token_id (int, optional): The ID of the beginning-of-sequence token. Defaults to 1.
            eos_token_id (int, optional): The ID of the end-of-sequence token. Defaults to 2.
            forced_eos_token_id (int, optional): The ID of the forced end-of-sequence token. Defaults to 2.
            kwargs (dict, optional): Additional keyword arguments.

        Returns:
            None.

        Raises:
            None.
        """
        self.vocab_size = vocab_size
        self.max_position_embeddings = max_position_embeddings
        self.d_model = d_model
        self.encoder_ffn_dim = encoder_ffn_dim
        self.encoder_layers = encoder_layers
        self.encoder_attention_heads = encoder_attention_heads
        self.decoder_ffn_dim = decoder_ffn_dim
        self.decoder_layers = decoder_layers
        self.decoder_attention_heads = decoder_attention_heads
        self.dropout = dropout
        self.attention_dropout = attention_dropout
        self.activation_dropout = activation_dropout
        self.activation_function = activation_function
        self.init_std = init_std
        self.encoder_layerdrop = encoder_layerdrop
        self.decoder_layerdrop = decoder_layerdrop
        self.use_cache = use_cache
        self.num_hidden_layers = encoder_layers
        self.scale_embedding = scale_embedding  # scale factor will be sqrt(d_model) if True

        super().__init__(
            pad_token_id=pad_token_id,
            bos_token_id=bos_token_id,
            eos_token_id=eos_token_id,
            is_encoder_decoder=is_encoder_decoder,
            decoder_start_token_id=decoder_start_token_id,
            forced_eos_token_id=forced_eos_token_id,
            **kwargs,
        )

mindnlp.transformers.models.blenderbot_small.configuration_blenderbot_small.BlenderbotSmallConfig.__init__(vocab_size=50265, max_position_embeddings=512, encoder_layers=8, encoder_ffn_dim=2048, encoder_attention_heads=16, decoder_layers=8, decoder_ffn_dim=2048, decoder_attention_heads=16, encoder_layerdrop=0.0, decoder_layerdrop=0.0, use_cache=True, is_encoder_decoder=True, activation_function='gelu', d_model=512, dropout=0.1, attention_dropout=0.0, activation_dropout=0.0, init_std=0.02, decoder_start_token_id=1, scale_embedding=False, pad_token_id=0, bos_token_id=1, eos_token_id=2, forced_eos_token_id=2, **kwargs)

Initializes a new instance of the BlenderbotSmallConfig class.

PARAMETER DESCRIPTION
vocab_size

The size of the vocabulary. Defaults to 50265.

TYPE: int DEFAULT: 50265

max_position_embeddings

The maximum position of the embeddings. Defaults to 512.

TYPE: int DEFAULT: 512

encoder_layers

The number of encoder layers. Defaults to 8.

TYPE: int DEFAULT: 8

encoder_ffn_dim

The dimension of the encoder feed-forward network. Defaults to 2048.

TYPE: int DEFAULT: 2048

encoder_attention_heads

The number of attention heads for the encoder. Defaults to 16.

TYPE: int DEFAULT: 16

decoder_layers

The number of decoder layers. Defaults to 8.

TYPE: int DEFAULT: 8

decoder_ffn_dim

The dimension of the decoder feed-forward network. Defaults to 2048.

TYPE: int DEFAULT: 2048

decoder_attention_heads

The number of attention heads for the decoder. Defaults to 16.

TYPE: int DEFAULT: 16

encoder_layerdrop

The probability of dropping an encoder layer. Defaults to 0.0.

TYPE: float DEFAULT: 0.0

decoder_layerdrop

The probability of dropping a decoder layer. Defaults to 0.0.

TYPE: float DEFAULT: 0.0

use_cache

Whether to use cache. Defaults to True.

TYPE: bool DEFAULT: True

is_encoder_decoder

Determines if the model is an encoder-decoder. Defaults to True.

TYPE: bool DEFAULT: True

activation_function

The activation function to be used. Defaults to 'gelu'.

TYPE: str DEFAULT: 'gelu'

d_model

The dimension of the model. Defaults to 512.

TYPE: int DEFAULT: 512

dropout

The dropout probability. Defaults to 0.1.

TYPE: float DEFAULT: 0.1

attention_dropout

The dropout probability for attention layers. Defaults to 0.0.

TYPE: float DEFAULT: 0.0

activation_dropout

The dropout probability for activation layers. Defaults to 0.0.

TYPE: float DEFAULT: 0.0

init_std

The standard deviation for weight initialization. Defaults to 0.02.

TYPE: float DEFAULT: 0.02

decoder_start_token_id

The ID of the start token for the decoder. Defaults to 1.

TYPE: int DEFAULT: 1

scale_embedding

Whether to scale the embeddings. Defaults to False.

TYPE: bool DEFAULT: False

pad_token_id

The ID of the padding token. Defaults to 0.

TYPE: int DEFAULT: 0

bos_token_id

The ID of the beginning-of-sequence token. Defaults to 1.

TYPE: int DEFAULT: 1

eos_token_id

The ID of the end-of-sequence token. Defaults to 2.

TYPE: int DEFAULT: 2

forced_eos_token_id

The ID of the forced end-of-sequence token. Defaults to 2.

TYPE: int DEFAULT: 2

kwargs

Additional keyword arguments.

TYPE: dict DEFAULT: {}

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/blenderbot_small/configuration_blenderbot_small.py
 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
def __init__(
    self,
    vocab_size=50265,
    max_position_embeddings=512,
    encoder_layers=8,
    encoder_ffn_dim=2048,
    encoder_attention_heads=16,
    decoder_layers=8,
    decoder_ffn_dim=2048,
    decoder_attention_heads=16,
    encoder_layerdrop=0.0,
    decoder_layerdrop=0.0,
    use_cache=True,
    is_encoder_decoder=True,
    activation_function="gelu",
    d_model=512,
    dropout=0.1,
    attention_dropout=0.0,
    activation_dropout=0.0,
    init_std=0.02,
    decoder_start_token_id=1,
    scale_embedding=False,
    pad_token_id=0,
    bos_token_id=1,
    eos_token_id=2,
    forced_eos_token_id=2,
    **kwargs,
):
    """
    Initializes a new instance of the BlenderbotSmallConfig class.

    Args:
        vocab_size (int, optional): The size of the vocabulary. Defaults to 50265.
        max_position_embeddings (int, optional): The maximum position of the embeddings. Defaults to 512.
        encoder_layers (int, optional): The number of encoder layers. Defaults to 8.
        encoder_ffn_dim (int, optional): The dimension of the encoder feed-forward network. Defaults to 2048.
        encoder_attention_heads (int, optional): The number of attention heads for the encoder. Defaults to 16.
        decoder_layers (int, optional): The number of decoder layers. Defaults to 8.
        decoder_ffn_dim (int, optional): The dimension of the decoder feed-forward network. Defaults to 2048.
        decoder_attention_heads (int, optional): The number of attention heads for the decoder. Defaults to 16.
        encoder_layerdrop (float, optional): The probability of dropping an encoder layer. Defaults to 0.0.
        decoder_layerdrop (float, optional): The probability of dropping a decoder layer. Defaults to 0.0.
        use_cache (bool, optional): Whether to use cache. Defaults to True.
        is_encoder_decoder (bool, optional): Determines if the model is an encoder-decoder. Defaults to True.
        activation_function (str, optional): The activation function to be used. Defaults to 'gelu'.
        d_model (int, optional): The dimension of the model. Defaults to 512.
        dropout (float, optional): The dropout probability. Defaults to 0.1.
        attention_dropout (float, optional): The dropout probability for attention layers. Defaults to 0.0.
        activation_dropout (float, optional): The dropout probability for activation layers. Defaults to 0.0.
        init_std (float, optional): The standard deviation for weight initialization. Defaults to 0.02.
        decoder_start_token_id (int, optional): The ID of the start token for the decoder. Defaults to 1.
        scale_embedding (bool, optional): Whether to scale the embeddings. Defaults to False.
        pad_token_id (int, optional): The ID of the padding token. Defaults to 0.
        bos_token_id (int, optional): The ID of the beginning-of-sequence token. Defaults to 1.
        eos_token_id (int, optional): The ID of the end-of-sequence token. Defaults to 2.
        forced_eos_token_id (int, optional): The ID of the forced end-of-sequence token. Defaults to 2.
        kwargs (dict, optional): Additional keyword arguments.

    Returns:
        None.

    Raises:
        None.
    """
    self.vocab_size = vocab_size
    self.max_position_embeddings = max_position_embeddings
    self.d_model = d_model
    self.encoder_ffn_dim = encoder_ffn_dim
    self.encoder_layers = encoder_layers
    self.encoder_attention_heads = encoder_attention_heads
    self.decoder_ffn_dim = decoder_ffn_dim
    self.decoder_layers = decoder_layers
    self.decoder_attention_heads = decoder_attention_heads
    self.dropout = dropout
    self.attention_dropout = attention_dropout
    self.activation_dropout = activation_dropout
    self.activation_function = activation_function
    self.init_std = init_std
    self.encoder_layerdrop = encoder_layerdrop
    self.decoder_layerdrop = decoder_layerdrop
    self.use_cache = use_cache
    self.num_hidden_layers = encoder_layers
    self.scale_embedding = scale_embedding  # scale factor will be sqrt(d_model) if True

    super().__init__(
        pad_token_id=pad_token_id,
        bos_token_id=bos_token_id,
        eos_token_id=eos_token_id,
        is_encoder_decoder=is_encoder_decoder,
        decoder_start_token_id=decoder_start_token_id,
        forced_eos_token_id=forced_eos_token_id,
        **kwargs,
    )

mindnlp.transformers.models.blenderbot_small.modeling_blenderbot_small.BlenderbotSmallForCausalLM

Bases: BlenderbotSmallPreTrainedModel

Represents the BlenderbotSmallForCausalLM class, which is designed for causal language modeling with the BlenderbotSmall model architecture. This class inherits from BlenderbotSmallPreTrainedModel and provides methods for initializing the model, setting and getting input and output embeddings, setting and getting the decoder, forwarding the model, and preparing inputs for generation. It also includes a method for reordering cache during generation. The class includes detailed information about the arguments and returns for the 'forward' and 'prepare_inputs_for_generation' methods. Additionally, example usage and expected outputs are provided for the 'forward' method.

This class encapsulates the functionality for utilizing the BlenderbotSmall model for causal language modeling tasks and provides a comprehensive interface for model manipulation and generation.

Source code in mindnlp/transformers/models/blenderbot_small/modeling_blenderbot_small.py
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
1893
1894
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
1954
1955
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
class BlenderbotSmallForCausalLM(BlenderbotSmallPreTrainedModel):

    """
    Represents the BlenderbotSmallForCausalLM class, which is designed for causal language modeling with the
    BlenderbotSmall model architecture.
    This class inherits from BlenderbotSmallPreTrainedModel and  provides methods for initializing the model,
    setting and getting input and output embeddings, setting and getting the decoder, forwarding the model,
    and preparing inputs for generation.
    It also includes a method for reordering cache during generation.
    The class includes detailed information about the arguments and returns for the 'forward' and
    'prepare_inputs_for_generation' methods. Additionally, example usage and expected outputs are provided for
    the 'forward' method.

    This class encapsulates the functionality for utilizing the BlenderbotSmall model for causal language modeling
    tasks and provides a comprehensive interface for model manipulation and generation.
    """
    _tied_weights_keys = ["lm_head.weight"]

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

        Args:
            self (BlenderbotSmallForCausalLM): The instance of the class itself.
            config (object):
                The configuration object containing settings for the model.

                - This object is deep copied to ensure immutability.
                - It must have the 'is_decoder' attribute set to True.
                - It must have the 'is_encoder_decoder' attribute set to False.

        Returns:
            None.

        Raises:
            TypeError: If the config parameter is not of the expected type.
            AttributeError: If the config parameter does not have the required attributes.
        """
        config = copy.deepcopy(config)
        config.is_decoder = True
        config.is_encoder_decoder = False
        super().__init__(config)
        self.model = BlenderbotSmallDecoderWrapper(config)

        self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)

        # Initialize weights and apply final processing
        self.post_init()

    def get_input_embeddings(self):
        """
        This method retrieves the input embeddings from the BlenderbotSmallForCausalLM model.

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

        Returns:
            None: This method returns None as it retrieves the input embeddings from the model and does not perform any additional processing.

        Raises:
            None
        """
        return self.model.decoder.embed_tokens

    def set_input_embeddings(self, value):
        """
        Set the input embeddings for the BlenderbotSmallForCausalLM model.

        Args:
            self (BlenderbotSmallForCausalLM): The instance of the BlenderbotSmallForCausalLM class.
            value (torch.Tensor): The input embeddings to be set for the model. It should be a torch.Tensor of appropriate shape and size.

        Returns:
            None.

        Raises:
            None.
        """
        self.model.decoder.embed_tokens = value

    def get_output_embeddings(self):
        """
        Returns the output embeddings for the BlenderbotSmallForCausalLM model.

        Args:
            self: An instance of the BlenderbotSmallForCausalLM class.

        Returns:
            lm_head: The method returns the output embeddings for the model, which are used for downstream tasks or further analysis.

        Raises:
            None.

        Note:
            The output embeddings are a representation of the model's internal hidden states after processing the input data.
            They capture the semantic information learned by the model during training and can be useful for various
            natural language processing tasks.
        """
        return self.lm_head

    def set_output_embeddings(self, new_embeddings):
        """
        Sets the output embeddings for the BlenderbotSmallForCausalLM model.

        Args:
            self (BlenderbotSmallForCausalLM): The instance of the BlenderbotSmallForCausalLM class.
            new_embeddings (Tensor): The new output embeddings to be set for the model.
                It should be a tensor representing the new embeddings.

        Returns:
            None.

        Raises:
            TypeError: If the new_embeddings is not of type Tensor.
        """
        self.lm_head = new_embeddings

    def set_decoder(self, decoder):
        """
        Sets the decoder for the BlenderbotSmallForCausalLM model.

        Args:
            self (BlenderbotSmallForCausalLM): The instance of the BlenderbotSmallForCausalLM class.
            decoder (object): The decoder object to be set for the model.

        Returns:
            None.

        Raises:
            None.
        """
        self.model.decoder = decoder

    def get_decoder(self):
        """
        This method returns the decoder component of the BlenderbotSmallForCausalLM model.

        Args:
            self: The instance of the BlenderbotSmallForCausalLM class.

        Returns:
            None: The method returns the decoder component of the BlenderbotSmallForCausalLM model.

        Raises:
            This method does not raise any exceptions.
        """
        return self.model.decoder

    def forward(
        self,
        input_ids: mindspore.Tensor = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        encoder_hidden_states: Optional[mindspore.Tensor] = None,
        encoder_attention_mask: Optional[mindspore.Tensor] = None,
        head_mask: Optional[mindspore.Tensor] = None,
        cross_attn_head_mask: Optional[mindspore.Tensor] = None,
        past_key_values: Optional[List[mindspore.Tensor]] = None,
        inputs_embeds: Optional[mindspore.Tensor] = None,
        labels: Optional[mindspore.Tensor] = None,
        use_cache: Optional[bool] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
        r"""
        Args:
            input_ids (`mindspore.Tensor` of shape `(batch_size, sequence_length)`):
                Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
                provide it.

                Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
                [`PreTrainedTokenizer.__call__`] for details.

                [What are input IDs?](../glossary#input-ids)
            attention_mask (`mindspore.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

                - 1 for tokens that are **not masked**,
                - 0 for tokens that are **masked**.

                [What are attention masks?](../glossary#attention-mask)
            encoder_hidden_states  (`mindspore.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
                Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
                if the model is configured as a decoder.
            encoder_attention_mask (`mindspore.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used
                in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
            head_mask (`mindspore.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
                Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:

                - 1 indicates the head is **not masked**,
                - 0 indicates the head is **masked**.

            cross_attn_head_mask (`mindspore.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
                Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:

                - 1 indicates the head is **not masked**,
                - 0 indicates the head is **masked**.
            past_key_values (`tuple(tuple(mindspore.Tensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
                Tuple of `tuple(mindspore.Tensor)` of length `config.n_layers`, with each tuple having 2 tensors of
                shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
                shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional
                tensors are only required when the model is used as a decoder in a Sequence to Sequence model.

                Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
                cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.

                If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
                that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
                all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
            labels (`mindspore.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
                config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
                (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
            use_cache (`bool`, *optional*):

                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
                (see `past_key_values`).

                - 1 for tokens that are **not masked**,
                - 0 for tokens that are **masked**.
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            output_hidden_states (`bool`, *optional*):
                Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
                for more detail.
            return_dict (`bool`, *optional*):
                Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.

        Returns:
            Union[Tuple, CausalLMOutputWithCrossAttentions]

        Example:
            ```python
            >>> from transformers import AutoTokenizer, BlenderbotSmallForCausalLM
            ...
            >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
            >>> model = BlenderbotSmallForCausalLM.from_pretrained("facebook/blenderbot_small-90M", add_cross_attention=False)
            >>> assert model.config.is_decoder, f"{model.__class__} has to be configured as a decoder."
            >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
            >>> outputs = model(**inputs)
            ...
            >>> logits = outputs.logits
            >>> expected_shape = [1, inputs.input_ids.shape[-1], model.config.vocab_size]
            >>> list(logits.shape) == expected_shape
            True
            ```
        """
        output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
        output_hidden_states = (
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
        outputs = self.model.decoder(
            input_ids=input_ids,
            attention_mask=attention_mask,
            encoder_hidden_states=encoder_hidden_states,
            encoder_attention_mask=encoder_attention_mask,
            head_mask=head_mask,
            cross_attn_head_mask=cross_attn_head_mask,
            past_key_values=past_key_values,
            inputs_embeds=inputs_embeds,
            use_cache=use_cache,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )

        logits = self.lm_head(outputs[0])

        loss = None
        if labels is not None:
            loss = F.cross_entropy(logits.view(-1, self.config.vocab_size), labels.view(-1))

        if not return_dict:
            output = (logits,) + outputs[1:]
            return (loss,) + output if loss is not None else output

        return CausalLMOutputWithCrossAttentions(
            loss=loss,
            logits=logits,
            past_key_values=outputs.past_key_values,
            hidden_states=outputs.hidden_states,
            attentions=outputs.attentions,
            cross_attentions=outputs.cross_attentions,
        )

    def prepare_inputs_for_generation(
        self, input_ids, past_key_values=None, attention_mask=None, use_cache=None, **kwargs
    ):
        """
        This method prepares inputs for generation in the BlenderbotSmallForCausalLM class.

        Args:
            self: The instance of the class.
            input_ids (torch.Tensor): The input tensor containing token IDs for the input sequence.
            past_key_values (tuple, optional): A tuple of past key values used in model inference.
            attention_mask (torch.Tensor, optional): A tensor specifying which elements in the input sequence should be attended to.
            use_cache (bool, optional): A flag indicating whether to use caching for faster generation.

        Returns:
            dict: A dictionary containing the prepared inputs for generation including 'input_ids', 'attention_mask', 'past_key_values', and 'use_cache'.

        Raises:
            ValueError: If the input_ids shape is incompatible with past_key_values.
            IndexError: If an index error occurs during input_ids manipulation.
        """
        # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
        if attention_mask is None:
            attention_mask = input_ids.new_ones(input_ids.shape)

        if past_key_values:
            past_length = past_key_values[0][0].shape[2]

            # Some generation methods already pass only the last input ID
            if input_ids.shape[1] > past_length:
                remove_prefix_length = past_length
            else:
                # Default to old behavior: keep only final ID
                remove_prefix_length = input_ids.shape[1] - 1

            input_ids = input_ids[:, remove_prefix_length:]
        # first step, decoder_cached_states are empty
        return {
            "input_ids": input_ids,  # encoder_outputs is defined. input_ids not needed
            "attention_mask": attention_mask,
            "past_key_values": past_key_values,
            "use_cache": use_cache,
        }

    @staticmethod
    def _reorder_cache(past_key_values, beam_idx):
        """
        Reorders the cache based on the provided beam index.

        Args:
            past_key_values (tuple): A tuple containing the past key-values to be reordered.
                Each element in the tuple represents the past key-values for a layer.
            beam_idx (Tensor): A tensor representing the indices of the beams to use for reordering the past key-values.

        Returns:
            None: This method does not return anything but modifies the past key-values in place.

        Raises:
            None.
        """
        reordered_past = ()
        for layer_past in past_key_values:
            reordered_past += (
                tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),
            )
        return reordered_past

mindnlp.transformers.models.blenderbot_small.modeling_blenderbot_small.BlenderbotSmallForCausalLM.__init__(config)

Initializes a new instance of the BlenderbotSmallForCausalLM class.

PARAMETER DESCRIPTION
self

The instance of the class itself.

TYPE: BlenderbotSmallForCausalLM

config

The configuration object containing settings for the model.

  • This object is deep copied to ensure immutability.
  • It must have the 'is_decoder' attribute set to True.
  • It must have the 'is_encoder_decoder' attribute set to False.

TYPE: object

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the config parameter is not of the expected type.

AttributeError

If the config parameter does not have the required attributes.

Source code in mindnlp/transformers/models/blenderbot_small/modeling_blenderbot_small.py
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
def __init__(self, config):
    """
    Initializes a new instance of the BlenderbotSmallForCausalLM class.

    Args:
        self (BlenderbotSmallForCausalLM): The instance of the class itself.
        config (object):
            The configuration object containing settings for the model.

            - This object is deep copied to ensure immutability.
            - It must have the 'is_decoder' attribute set to True.
            - It must have the 'is_encoder_decoder' attribute set to False.

    Returns:
        None.

    Raises:
        TypeError: If the config parameter is not of the expected type.
        AttributeError: If the config parameter does not have the required attributes.
    """
    config = copy.deepcopy(config)
    config.is_decoder = True
    config.is_encoder_decoder = False
    super().__init__(config)
    self.model = BlenderbotSmallDecoderWrapper(config)

    self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)

    # Initialize weights and apply final processing
    self.post_init()

mindnlp.transformers.models.blenderbot_small.modeling_blenderbot_small.BlenderbotSmallForCausalLM.forward(input_ids=None, attention_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, head_mask=None, cross_attn_head_mask=None, past_key_values=None, inputs_embeds=None, labels=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None)

PARAMETER DESCRIPTION
input_ids

Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it.

Indices can be obtained using [AutoTokenizer]. See [PreTrainedTokenizer.encode] and [PreTrainedTokenizer.__call__] for details.

What are input IDs?

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

attention_mask

Mask to avoid performing attention on padding token indices. Mask values selected in [0, 1]:

  • 1 for tokens that are not masked,
  • 0 for tokens that are masked.

What are attention masks?

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

encoder_hidden_states

Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if the model is configured as a decoder.

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

encoder_attention_mask

Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in the cross-attention if the model is configured as a decoder. Mask values selected in [0, 1]:

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

head_mask

Mask to nullify selected heads of the attention modules. Mask values selected in [0, 1]:

  • 1 indicates the head is not masked,
  • 0 indicates the head is masked.

TYPE: `mindspore.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional* DEFAULT: None

cross_attn_head_mask

Mask to nullify selected heads of the cross-attention modules. Mask values selected in [0, 1]:

  • 1 indicates the head is not masked,
  • 0 indicates the head is masked.

TYPE: `mindspore.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional* DEFAULT: None

past_key_values

Tuple of tuple(mindspore.Tensor) of length config.n_layers, with each tuple having 2 tensors of shape (batch_size, num_heads, sequence_length, embed_size_per_head)) and 2 additional tensors of shape (batch_size, num_heads, encoder_sequence_length, embed_size_per_head). The two additional tensors are only required when the model is used as a decoder in a Sequence to Sequence model.

Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used (see past_key_values input) to speed up sequential decoding.

If past_key_values are used, the user can optionally input only the last decoder_input_ids (those that don't have their past key value states given to this model) of shape (batch_size, 1) instead of all decoder_input_ids of shape (batch_size, sequence_length).

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

labels

Labels for computing the masked language modeling loss. Indices should either be in [0, ..., config.vocab_size] or -100 (see input_ids docstring). Tokens with indices set to -100 are ignored (masked), the loss is only computed for the tokens with labels in [0, ..., config.vocab_size].

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

use_cache

If set to True, past_key_values key value states are returned and can be used to speed up decoding (see past_key_values).

  • 1 for tokens that are not masked,
  • 0 for tokens that are masked.

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

output_attentions

Whether or not to return the attentions tensors of all attention layers. See attentions under returned tensors for more detail.

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

output_hidden_states

Whether or not to return the hidden states of all layers. See hidden_states under returned tensors for more detail.

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

return_dict

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

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

RETURNS DESCRIPTION
Union[Tuple, CausalLMOutputWithCrossAttentions]

Union[Tuple, CausalLMOutputWithCrossAttentions]

Example
>>> from transformers import AutoTokenizer, BlenderbotSmallForCausalLM
...
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
>>> model = BlenderbotSmallForCausalLM.from_pretrained("facebook/blenderbot_small-90M", add_cross_attention=False)
>>> assert model.config.is_decoder, f"{model.__class__} has to be configured as a decoder."
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
>>> outputs = model(**inputs)
...
>>> logits = outputs.logits
>>> expected_shape = [1, inputs.input_ids.shape[-1], model.config.vocab_size]
>>> list(logits.shape) == expected_shape
True
Source code in mindnlp/transformers/models/blenderbot_small/modeling_blenderbot_small.py
1887
1888
1889
1890
1891
1892
1893
1894
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
1954
1955
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
def forward(
    self,
    input_ids: mindspore.Tensor = None,
    attention_mask: Optional[mindspore.Tensor] = None,
    encoder_hidden_states: Optional[mindspore.Tensor] = None,
    encoder_attention_mask: Optional[mindspore.Tensor] = None,
    head_mask: Optional[mindspore.Tensor] = None,
    cross_attn_head_mask: Optional[mindspore.Tensor] = None,
    past_key_values: Optional[List[mindspore.Tensor]] = None,
    inputs_embeds: Optional[mindspore.Tensor] = None,
    labels: Optional[mindspore.Tensor] = None,
    use_cache: Optional[bool] = None,
    output_attentions: Optional[bool] = None,
    output_hidden_states: Optional[bool] = None,
    return_dict: Optional[bool] = None,
) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
    r"""
    Args:
        input_ids (`mindspore.Tensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
            provide it.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`mindspore.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)
        encoder_hidden_states  (`mindspore.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
            Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
            if the model is configured as a decoder.
        encoder_attention_mask (`mindspore.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used
            in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
        head_mask (`mindspore.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
            Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.

        cross_attn_head_mask (`mindspore.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
            Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.
        past_key_values (`tuple(tuple(mindspore.Tensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            Tuple of `tuple(mindspore.Tensor)` of length `config.n_layers`, with each tuple having 2 tensors of
            shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
            shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional
            tensors are only required when the model is used as a decoder in a Sequence to Sequence model.

            Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
            cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.

            If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
            that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
            all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
        labels (`mindspore.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
            config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
            (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
        use_cache (`bool`, *optional*):

            If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
            (see `past_key_values`).

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under
            returned tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
            for more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.

    Returns:
        Union[Tuple, CausalLMOutputWithCrossAttentions]

    Example:
        ```python
        >>> from transformers import AutoTokenizer, BlenderbotSmallForCausalLM
        ...
        >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
        >>> model = BlenderbotSmallForCausalLM.from_pretrained("facebook/blenderbot_small-90M", add_cross_attention=False)
        >>> assert model.config.is_decoder, f"{model.__class__} has to be configured as a decoder."
        >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
        >>> outputs = model(**inputs)
        ...
        >>> logits = outputs.logits
        >>> expected_shape = [1, inputs.input_ids.shape[-1], model.config.vocab_size]
        >>> list(logits.shape) == expected_shape
        True
        ```
    """
    output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
    output_hidden_states = (
        output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
    )
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict

    # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
    outputs = self.model.decoder(
        input_ids=input_ids,
        attention_mask=attention_mask,
        encoder_hidden_states=encoder_hidden_states,
        encoder_attention_mask=encoder_attention_mask,
        head_mask=head_mask,
        cross_attn_head_mask=cross_attn_head_mask,
        past_key_values=past_key_values,
        inputs_embeds=inputs_embeds,
        use_cache=use_cache,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )

    logits = self.lm_head(outputs[0])

    loss = None
    if labels is not None:
        loss = F.cross_entropy(logits.view(-1, self.config.vocab_size), labels.view(-1))

    if not return_dict:
        output = (logits,) + outputs[1:]
        return (loss,) + output if loss is not None else output

    return CausalLMOutputWithCrossAttentions(
        loss=loss,
        logits=logits,
        past_key_values=outputs.past_key_values,
        hidden_states=outputs.hidden_states,
        attentions=outputs.attentions,
        cross_attentions=outputs.cross_attentions,
    )

mindnlp.transformers.models.blenderbot_small.modeling_blenderbot_small.BlenderbotSmallForCausalLM.get_decoder()

This method returns the decoder component of the BlenderbotSmallForCausalLM model.

PARAMETER DESCRIPTION
self

The instance of the BlenderbotSmallForCausalLM class.

RETURNS DESCRIPTION
None

The method returns the decoder component of the BlenderbotSmallForCausalLM model.

Source code in mindnlp/transformers/models/blenderbot_small/modeling_blenderbot_small.py
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
def get_decoder(self):
    """
    This method returns the decoder component of the BlenderbotSmallForCausalLM model.

    Args:
        self: The instance of the BlenderbotSmallForCausalLM class.

    Returns:
        None: The method returns the decoder component of the BlenderbotSmallForCausalLM model.

    Raises:
        This method does not raise any exceptions.
    """
    return self.model.decoder

mindnlp.transformers.models.blenderbot_small.modeling_blenderbot_small.BlenderbotSmallForCausalLM.get_input_embeddings()

This method retrieves the input embeddings from the BlenderbotSmallForCausalLM model.

PARAMETER DESCRIPTION
self

The instance of the BlenderbotSmallForCausalLM class.

TYPE: BlenderbotSmallForCausalLM

RETURNS DESCRIPTION
None

This method returns None as it retrieves the input embeddings from the model and does not perform any additional processing.

Source code in mindnlp/transformers/models/blenderbot_small/modeling_blenderbot_small.py
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
def get_input_embeddings(self):
    """
    This method retrieves the input embeddings from the BlenderbotSmallForCausalLM model.

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

    Returns:
        None: This method returns None as it retrieves the input embeddings from the model and does not perform any additional processing.

    Raises:
        None
    """
    return self.model.decoder.embed_tokens

mindnlp.transformers.models.blenderbot_small.modeling_blenderbot_small.BlenderbotSmallForCausalLM.get_output_embeddings()

Returns the output embeddings for the BlenderbotSmallForCausalLM model.

PARAMETER DESCRIPTION
self

An instance of the BlenderbotSmallForCausalLM class.

RETURNS DESCRIPTION
lm_head

The method returns the output embeddings for the model, which are used for downstream tasks or further analysis.

Note

The output embeddings are a representation of the model's internal hidden states after processing the input data. They capture the semantic information learned by the model during training and can be useful for various natural language processing tasks.

Source code in mindnlp/transformers/models/blenderbot_small/modeling_blenderbot_small.py
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
def get_output_embeddings(self):
    """
    Returns the output embeddings for the BlenderbotSmallForCausalLM model.

    Args:
        self: An instance of the BlenderbotSmallForCausalLM class.

    Returns:
        lm_head: The method returns the output embeddings for the model, which are used for downstream tasks or further analysis.

    Raises:
        None.

    Note:
        The output embeddings are a representation of the model's internal hidden states after processing the input data.
        They capture the semantic information learned by the model during training and can be useful for various
        natural language processing tasks.
    """
    return self.lm_head

mindnlp.transformers.models.blenderbot_small.modeling_blenderbot_small.BlenderbotSmallForCausalLM.prepare_inputs_for_generation(input_ids, past_key_values=None, attention_mask=None, use_cache=None, **kwargs)

This method prepares inputs for generation in the BlenderbotSmallForCausalLM class.

PARAMETER DESCRIPTION
self

The instance of the class.

input_ids

The input tensor containing token IDs for the input sequence.

TYPE: Tensor

past_key_values

A tuple of past key values used in model inference.

TYPE: tuple DEFAULT: None

attention_mask

A tensor specifying which elements in the input sequence should be attended to.

TYPE: Tensor DEFAULT: None

use_cache

A flag indicating whether to use caching for faster generation.

TYPE: bool DEFAULT: None

RETURNS DESCRIPTION
dict

A dictionary containing the prepared inputs for generation including 'input_ids', 'attention_mask', 'past_key_values', and 'use_cache'.

RAISES DESCRIPTION
ValueError

If the input_ids shape is incompatible with past_key_values.

IndexError

If an index error occurs during input_ids manipulation.

Source code in mindnlp/transformers/models/blenderbot_small/modeling_blenderbot_small.py
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
def prepare_inputs_for_generation(
    self, input_ids, past_key_values=None, attention_mask=None, use_cache=None, **kwargs
):
    """
    This method prepares inputs for generation in the BlenderbotSmallForCausalLM class.

    Args:
        self: The instance of the class.
        input_ids (torch.Tensor): The input tensor containing token IDs for the input sequence.
        past_key_values (tuple, optional): A tuple of past key values used in model inference.
        attention_mask (torch.Tensor, optional): A tensor specifying which elements in the input sequence should be attended to.
        use_cache (bool, optional): A flag indicating whether to use caching for faster generation.

    Returns:
        dict: A dictionary containing the prepared inputs for generation including 'input_ids', 'attention_mask', 'past_key_values', and 'use_cache'.

    Raises:
        ValueError: If the input_ids shape is incompatible with past_key_values.
        IndexError: If an index error occurs during input_ids manipulation.
    """
    # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
    if attention_mask is None:
        attention_mask = input_ids.new_ones(input_ids.shape)

    if past_key_values:
        past_length = past_key_values[0][0].shape[2]

        # Some generation methods already pass only the last input ID
        if input_ids.shape[1] > past_length:
            remove_prefix_length = past_length
        else:
            # Default to old behavior: keep only final ID
            remove_prefix_length = input_ids.shape[1] - 1

        input_ids = input_ids[:, remove_prefix_length:]
    # first step, decoder_cached_states are empty
    return {
        "input_ids": input_ids,  # encoder_outputs is defined. input_ids not needed
        "attention_mask": attention_mask,
        "past_key_values": past_key_values,
        "use_cache": use_cache,
    }

mindnlp.transformers.models.blenderbot_small.modeling_blenderbot_small.BlenderbotSmallForCausalLM.set_decoder(decoder)

Sets the decoder for the BlenderbotSmallForCausalLM model.

PARAMETER DESCRIPTION
self

The instance of the BlenderbotSmallForCausalLM class.

TYPE: BlenderbotSmallForCausalLM

decoder

The decoder object to be set for the model.

TYPE: object

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/blenderbot_small/modeling_blenderbot_small.py
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
def set_decoder(self, decoder):
    """
    Sets the decoder for the BlenderbotSmallForCausalLM model.

    Args:
        self (BlenderbotSmallForCausalLM): The instance of the BlenderbotSmallForCausalLM class.
        decoder (object): The decoder object to be set for the model.

    Returns:
        None.

    Raises:
        None.
    """
    self.model.decoder = decoder

mindnlp.transformers.models.blenderbot_small.modeling_blenderbot_small.BlenderbotSmallForCausalLM.set_input_embeddings(value)

Set the input embeddings for the BlenderbotSmallForCausalLM model.

PARAMETER DESCRIPTION
self

The instance of the BlenderbotSmallForCausalLM class.

TYPE: BlenderbotSmallForCausalLM

value

The input embeddings to be set for the model. It should be a torch.Tensor of appropriate shape and size.

TYPE: Tensor

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/blenderbot_small/modeling_blenderbot_small.py
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
def set_input_embeddings(self, value):
    """
    Set the input embeddings for the BlenderbotSmallForCausalLM model.

    Args:
        self (BlenderbotSmallForCausalLM): The instance of the BlenderbotSmallForCausalLM class.
        value (torch.Tensor): The input embeddings to be set for the model. It should be a torch.Tensor of appropriate shape and size.

    Returns:
        None.

    Raises:
        None.
    """
    self.model.decoder.embed_tokens = value

mindnlp.transformers.models.blenderbot_small.modeling_blenderbot_small.BlenderbotSmallForCausalLM.set_output_embeddings(new_embeddings)

Sets the output embeddings for the BlenderbotSmallForCausalLM model.

PARAMETER DESCRIPTION
self

The instance of the BlenderbotSmallForCausalLM class.

TYPE: BlenderbotSmallForCausalLM

new_embeddings

The new output embeddings to be set for the model. It should be a tensor representing the new embeddings.

TYPE: Tensor

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the new_embeddings is not of type Tensor.

Source code in mindnlp/transformers/models/blenderbot_small/modeling_blenderbot_small.py
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
def set_output_embeddings(self, new_embeddings):
    """
    Sets the output embeddings for the BlenderbotSmallForCausalLM model.

    Args:
        self (BlenderbotSmallForCausalLM): The instance of the BlenderbotSmallForCausalLM class.
        new_embeddings (Tensor): The new output embeddings to be set for the model.
            It should be a tensor representing the new embeddings.

    Returns:
        None.

    Raises:
        TypeError: If the new_embeddings is not of type Tensor.
    """
    self.lm_head = new_embeddings

mindnlp.transformers.models.blenderbot_small.modeling_blenderbot_small.BlenderbotSmallForConditionalGeneration

Bases: BlenderbotSmallPreTrainedModel

This class represents a small Blenderbot model for conditional generation tasks. It is designed to generate responses based on given inputs in a conversational setting. The class provides methods for initializing the model, resizing token embeddings, forwarding the model output, preparing inputs for generation, and reordering cache during inference. It inherits from BlenderbotSmallPreTrainedModel and includes functionalities such as getting encoder and decoder, setting output embeddings, and manipulating final logits bias. The class is equipped to handle various input parameters for generating responses and computing loss during training.

Source code in mindnlp/transformers/models/blenderbot_small/modeling_blenderbot_small.py
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
1478
1479
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
1646
1647
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
class BlenderbotSmallForConditionalGeneration(BlenderbotSmallPreTrainedModel):

    """
    This class represents a small Blenderbot model for conditional generation tasks. It is designed to generate
    responses based on given inputs in a conversational setting.
    The class provides methods for initializing the model, resizing token embeddings, forwarding the model output,
    preparing inputs for generation, and reordering cache during inference.
    It inherits from BlenderbotSmallPreTrainedModel and includes functionalities such as getting encoder and decoder,
    setting output embeddings, and manipulating final logits bias. The class is equipped to handle various input
    parameters for generating responses and computing loss during training.
    """
    base_model_prefix = "model"
    _keys_to_ignore_on_load_unexpected = ["final_logits_bias"]
    _tied_weights_keys = ["decoder.embed_tokens.weight", "encoder.embed_tokens.weight", "lm_head.weight"]

    def __init__(self, config: BlenderbotSmallConfig):
        """
        __init__

        Initialize the BlenderbotSmallForConditionalGeneration class.

        Args:
            self: The instance of the BlenderbotSmallForConditionalGeneration class.
            config (BlenderbotSmallConfig): An instance of the BlenderbotSmallConfig class
                containing the configuration parameters for the model.

        Returns:
            None.

        Raises:
            None
        """
        super().__init__(config)
        self.model = BlenderbotSmallModel(config)
        self.final_logits_bias = ops.zeros(1, self.model.shared.num_embeddings)
        self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False)

        # Initialize weights and apply final processing
        self.post_init()

    def get_encoder(self):
        """
        Method: get_encoder

        Description:
        Returns the encoder component of the BlenderbotSmallForConditionalGeneration model.

        Args:
            self: BlenderbotSmallForConditionalGeneration
                The instance of the BlenderbotSmallForConditionalGeneration class.

        Returns:
            None

        Raises:
            None
        """
        return self.model.get_encoder()

    def get_decoder(self):
        '''
        This method returns the decoder component from the BlenderbotSmallForConditionalGeneration model.

        Args:
            self (BlenderbotSmallForConditionalGeneration): An instance of the BlenderbotSmallForConditionalGeneration class.

        Returns:
            None: The decoder component retrieved from the model.

        Raises:
            This method does not raise any exceptions.
        '''
        return self.model.get_decoder()

    def resize_token_embeddings(self, new_num_tokens: int, pad_to_multiple_of: Optional[int] = None) -> nn.Embedding:
        """
        Resize the token embeddings for the BlenderbotSmallForConditionalGeneration model.

        Args:
            self: The instance of the class BlenderbotSmallForConditionalGeneration.
            new_num_tokens (int): The new number of tokens to resize the embedding to.
            pad_to_multiple_of (Optional[int]): If provided, the new embedding size will be padded to a multiple of this value.

        Returns:
            nn.Embedding: The resized token embeddings as an instance of nn.Embedding.

        Raises:
            None.
        """
        new_embeddings = super().resize_token_embeddings(new_num_tokens, pad_to_multiple_of)
        self._resize_final_logits_bias(new_embeddings.weight.shape[0])
        return new_embeddings

    def _resize_final_logits_bias(self, new_num_tokens: int) -> None:
        """
        Resizes the final logits bias based on the number of tokens in the input.

        Args:
            self (BlenderbotSmallForConditionalGeneration): The instance of the BlenderbotSmallForConditionalGeneration class.
            new_num_tokens (int): The desired number of tokens in the input. It should be a positive integer.

        Returns:
            None: This method modifies the final_logits_bias attribute of the instance.

        Raises:
            None.
        """
        old_num_tokens = self.final_logits_bias.shape[-1]
        if new_num_tokens <= old_num_tokens:
            new_bias = self.final_logits_bias[:, :new_num_tokens]
        else:
            extra_bias = ops.zeros(1, new_num_tokens - old_num_tokens)
            new_bias = ops.cat([self.final_logits_bias, extra_bias], dim=1)
        self.final_logits_bias = new_bias

    def get_output_embeddings(self):
        """
        Method to retrieve the output embeddings of the model.

        Args:
            self: Instance of the BlenderbotSmallForConditionalGeneration class.

        Returns:
            None: This method returns the output embeddings of the model stored in the 'lm_head' attribute.

        Raises:
            None.
        """
        return self.lm_head

    def set_output_embeddings(self, new_embeddings):
        """
        Sets the output embeddings for the BlenderbotSmallForConditionalGeneration model.

        Args:
            self (BlenderbotSmallForConditionalGeneration): The instance of the BlenderbotSmallForConditionalGeneration class.
            new_embeddings (torch.Tensor): The new output embeddings to be set for the model.
                It should be a tensor of shape (vocab_size, hidden_size).

        Returns:
            None.

        Raises:
            TypeError: If the new_embeddings parameter is not a torch.Tensor.
            ValueError: If the shape of new_embeddings does not match the expected shape (vocab_size, hidden_size).
        """
        self.lm_head = new_embeddings

    def forward(
        self,
        input_ids: Optional[mindspore.Tensor] = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        decoder_input_ids: Optional[mindspore.Tensor] = None,
        decoder_attention_mask: Optional[mindspore.Tensor] = None,
        head_mask: Optional[mindspore.Tensor] = None,
        decoder_head_mask: Optional[mindspore.Tensor] = None,
        cross_attn_head_mask: Optional[mindspore.Tensor] = None,
        encoder_outputs: Optional[Union[Tuple, BaseModelOutput]] = None,
        past_key_values: Optional[List[mindspore.Tensor]] = None,
        inputs_embeds: Optional[mindspore.Tensor] = None,
        decoder_inputs_embeds: Optional[mindspore.Tensor] = None,
        labels: Optional[mindspore.Tensor] = None,
        use_cache: Optional[bool] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple[mindspore.Tensor], Seq2SeqLMOutput]:
        r"""
        Args:
            labels (`mindspore.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
                config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
                (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

        Returns:
            `Union[Tuple[mindspore.Tensor], Seq2SeqLMOutput]`
        """
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        if labels is not None:
            if use_cache:
                logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
            use_cache = False
            if decoder_input_ids is None and decoder_inputs_embeds is None:
                decoder_input_ids = shift_tokens_right(
                    labels, self.config.pad_token_id, self.config.decoder_start_token_id
                )

        outputs = self.model(
            input_ids,
            attention_mask=attention_mask,
            decoder_input_ids=decoder_input_ids,
            encoder_outputs=encoder_outputs,
            decoder_attention_mask=decoder_attention_mask,
            head_mask=head_mask,
            decoder_head_mask=decoder_head_mask,
            cross_attn_head_mask=cross_attn_head_mask,
            past_key_values=past_key_values,
            inputs_embeds=inputs_embeds,
            decoder_inputs_embeds=decoder_inputs_embeds,
            use_cache=use_cache,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )
        lm_logits = self.lm_head(outputs[0]) + self.final_logits_bias

        masked_lm_loss = None
        if labels is not None:
            masked_lm_loss = F.cross_entropy(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))

        if not return_dict:
            output = (lm_logits,) + outputs[1:]
            return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output

        return Seq2SeqLMOutput(
            loss=masked_lm_loss,
            logits=lm_logits,
            past_key_values=outputs.past_key_values,
            decoder_hidden_states=outputs.decoder_hidden_states,
            decoder_attentions=outputs.decoder_attentions,
            cross_attentions=outputs.cross_attentions,
            encoder_last_hidden_state=outputs.encoder_last_hidden_state,
            encoder_hidden_states=outputs.encoder_hidden_states,
            encoder_attentions=outputs.encoder_attentions,
        )

    def prepare_inputs_for_generation(
        self,
        decoder_input_ids,
        past_key_values=None,
        attention_mask=None,
        head_mask=None,
        decoder_head_mask=None,
        cross_attn_head_mask=None,
        use_cache=None,
        encoder_outputs=None,
        **kwargs,
    ):
        '''
        Prepare inputs for generation.

        Args:
            self (BlenderbotSmallForConditionalGeneration): An instance of the BlenderbotSmallForConditionalGeneration class.
            decoder_input_ids (torch.Tensor): The input tensor of decoder tokens. Shape: (batch_size, sequence_length).
            past_key_values (Tuple[Tuple[torch.Tensor]]): The cached key-value states of the decoder. Default: None.
            attention_mask (torch.Tensor): The attention mask tensor. Shape: (batch_size, sequence_length).
            head_mask (torch.Tensor): The mask tensor for hiding heads of the encoder. Shape: (num_layers, num_heads).
            decoder_head_mask (torch.Tensor): The mask tensor for hiding heads of the decoder. Shape: (num_layers, num_heads).
            cross_attn_head_mask (torch.Tensor): The mask tensor for hiding heads of the cross-attention. Shape: (num_layers, num_heads).
            use_cache (bool): Whether to use cache for decoding. Default: None.
            encoder_outputs (Tuple[torch.Tensor]): The output tensor of the encoder. Default: None.

        Returns:
            dict: A dictionary containing the prepared inputs for generation.
                The keys are as follows:

                - 'input_ids' (None): Placeholder for input ids.
                - 'encoder_outputs' (Tuple[torch.Tensor]): The output tensor of the encoder.
                - 'past_key_values' (Tuple[Tuple[torch.Tensor]]): The cached key-value states of the decoder.
                - 'decoder_input_ids' (torch.Tensor): The modified input tensor of decoder tokens.
                - 'attention_mask' (torch.Tensor): The attention mask tensor.
                - 'head_mask' (torch.Tensor): The mask tensor for hiding heads of the encoder.
                - 'decoder_head_mask' (torch.Tensor): The mask tensor for hiding heads of the decoder.
                - 'cross_attn_head_mask' (torch.Tensor): The mask tensor for hiding heads of the cross-attention.
                - 'use_cache' (bool): Whether to use cache for decoding.

        Raises:
            None.
        '''
        # cut decoder_input_ids if past is used
        if past_key_values is not None:
            past_length = past_key_values[0][0].shape[2]

            # Some generation methods already pass only the last input ID
            if decoder_input_ids.shape[1] > past_length:
                remove_prefix_length = past_length
            else:
                # Default to old behavior: keep only final ID
                remove_prefix_length = decoder_input_ids.shape[1] - 1

            decoder_input_ids = decoder_input_ids[:, remove_prefix_length:]

        return {
            "input_ids": None,  # encoder_outputs is defined. input_ids not needed
            "encoder_outputs": encoder_outputs,
            "past_key_values": past_key_values,
            "decoder_input_ids": decoder_input_ids,
            "attention_mask": attention_mask,
            "head_mask": head_mask,
            "decoder_head_mask": decoder_head_mask,
            "cross_attn_head_mask": cross_attn_head_mask,
            "use_cache": use_cache,  # change this to avoid caching (presumably for debugging)
        }

    @staticmethod
    def _reorder_cache(past_key_values, beam_idx):
        """
        Reorders the cache for a specific beam index in the BlenderbotSmallForConditionalGeneration class.

        Args:
            past_key_values (tuple): A tuple containing past key-value pairs for each layer.
                Each layer's past consists of a tuple of two tensors and an additional tensor.
            beam_idx (int): The index of the beam for which the cache needs to be reordered.

        Returns:
            None.

        Raises:
            None.
        """
        reordered_past = ()
        for layer_past in past_key_values:
            # cached cross_attention states don't have to be reordered -> they are always the same
            reordered_past += (
                tuple(past_state.index_select(0, beam_idx) for past_state in layer_past[:2])
                + layer_past[2:],
            )
        return reordered_past

mindnlp.transformers.models.blenderbot_small.modeling_blenderbot_small.BlenderbotSmallForConditionalGeneration.__init__(config)

init

Initialize the BlenderbotSmallForConditionalGeneration class.

PARAMETER DESCRIPTION
self

The instance of the BlenderbotSmallForConditionalGeneration class.

config

An instance of the BlenderbotSmallConfig class containing the configuration parameters for the model.

TYPE: BlenderbotSmallConfig

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/blenderbot_small/modeling_blenderbot_small.py
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
def __init__(self, config: BlenderbotSmallConfig):
    """
    __init__

    Initialize the BlenderbotSmallForConditionalGeneration class.

    Args:
        self: The instance of the BlenderbotSmallForConditionalGeneration class.
        config (BlenderbotSmallConfig): An instance of the BlenderbotSmallConfig class
            containing the configuration parameters for the model.

    Returns:
        None.

    Raises:
        None
    """
    super().__init__(config)
    self.model = BlenderbotSmallModel(config)
    self.final_logits_bias = ops.zeros(1, self.model.shared.num_embeddings)
    self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False)

    # Initialize weights and apply final processing
    self.post_init()

mindnlp.transformers.models.blenderbot_small.modeling_blenderbot_small.BlenderbotSmallForConditionalGeneration.forward(input_ids=None, attention_mask=None, decoder_input_ids=None, decoder_attention_mask=None, head_mask=None, decoder_head_mask=None, cross_attn_head_mask=None, encoder_outputs=None, past_key_values=None, inputs_embeds=None, decoder_inputs_embeds=None, labels=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None)

PARAMETER DESCRIPTION
labels

Labels for computing the masked language modeling loss. Indices should either be in [0, ..., config.vocab_size] or -100 (see input_ids docstring). Tokens with indices set to -100 are ignored (masked), the loss is only computed for the tokens with labels in [0, ..., config.vocab_size].

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

RETURNS DESCRIPTION
Union[Tuple[Tensor], Seq2SeqLMOutput]

Union[Tuple[mindspore.Tensor], Seq2SeqLMOutput]

Source code in mindnlp/transformers/models/blenderbot_small/modeling_blenderbot_small.py
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
def forward(
    self,
    input_ids: Optional[mindspore.Tensor] = None,
    attention_mask: Optional[mindspore.Tensor] = None,
    decoder_input_ids: Optional[mindspore.Tensor] = None,
    decoder_attention_mask: Optional[mindspore.Tensor] = None,
    head_mask: Optional[mindspore.Tensor] = None,
    decoder_head_mask: Optional[mindspore.Tensor] = None,
    cross_attn_head_mask: Optional[mindspore.Tensor] = None,
    encoder_outputs: Optional[Union[Tuple, BaseModelOutput]] = None,
    past_key_values: Optional[List[mindspore.Tensor]] = None,
    inputs_embeds: Optional[mindspore.Tensor] = None,
    decoder_inputs_embeds: Optional[mindspore.Tensor] = None,
    labels: Optional[mindspore.Tensor] = None,
    use_cache: Optional[bool] = None,
    output_attentions: Optional[bool] = None,
    output_hidden_states: Optional[bool] = None,
    return_dict: Optional[bool] = None,
) -> Union[Tuple[mindspore.Tensor], Seq2SeqLMOutput]:
    r"""
    Args:
        labels (`mindspore.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
            config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
            (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

    Returns:
        `Union[Tuple[mindspore.Tensor], Seq2SeqLMOutput]`
    """
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict

    if labels is not None:
        if use_cache:
            logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
        use_cache = False
        if decoder_input_ids is None and decoder_inputs_embeds is None:
            decoder_input_ids = shift_tokens_right(
                labels, self.config.pad_token_id, self.config.decoder_start_token_id
            )

    outputs = self.model(
        input_ids,
        attention_mask=attention_mask,
        decoder_input_ids=decoder_input_ids,
        encoder_outputs=encoder_outputs,
        decoder_attention_mask=decoder_attention_mask,
        head_mask=head_mask,
        decoder_head_mask=decoder_head_mask,
        cross_attn_head_mask=cross_attn_head_mask,
        past_key_values=past_key_values,
        inputs_embeds=inputs_embeds,
        decoder_inputs_embeds=decoder_inputs_embeds,
        use_cache=use_cache,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )
    lm_logits = self.lm_head(outputs[0]) + self.final_logits_bias

    masked_lm_loss = None
    if labels is not None:
        masked_lm_loss = F.cross_entropy(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))

    if not return_dict:
        output = (lm_logits,) + outputs[1:]
        return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output

    return Seq2SeqLMOutput(
        loss=masked_lm_loss,
        logits=lm_logits,
        past_key_values=outputs.past_key_values,
        decoder_hidden_states=outputs.decoder_hidden_states,
        decoder_attentions=outputs.decoder_attentions,
        cross_attentions=outputs.cross_attentions,
        encoder_last_hidden_state=outputs.encoder_last_hidden_state,
        encoder_hidden_states=outputs.encoder_hidden_states,
        encoder_attentions=outputs.encoder_attentions,
    )

mindnlp.transformers.models.blenderbot_small.modeling_blenderbot_small.BlenderbotSmallForConditionalGeneration.get_decoder()

This method returns the decoder component from the BlenderbotSmallForConditionalGeneration model.

PARAMETER DESCRIPTION
self

An instance of the BlenderbotSmallForConditionalGeneration class.

TYPE: BlenderbotSmallForConditionalGeneration

RETURNS DESCRIPTION
None

The decoder component retrieved from the model.

Source code in mindnlp/transformers/models/blenderbot_small/modeling_blenderbot_small.py
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
def get_decoder(self):
    '''
    This method returns the decoder component from the BlenderbotSmallForConditionalGeneration model.

    Args:
        self (BlenderbotSmallForConditionalGeneration): An instance of the BlenderbotSmallForConditionalGeneration class.

    Returns:
        None: The decoder component retrieved from the model.

    Raises:
        This method does not raise any exceptions.
    '''
    return self.model.get_decoder()

mindnlp.transformers.models.blenderbot_small.modeling_blenderbot_small.BlenderbotSmallForConditionalGeneration.get_encoder()

Description: Returns the encoder component of the BlenderbotSmallForConditionalGeneration model.

PARAMETER DESCRIPTION
self

BlenderbotSmallForConditionalGeneration The instance of the BlenderbotSmallForConditionalGeneration class.

RETURNS DESCRIPTION

None

Source code in mindnlp/transformers/models/blenderbot_small/modeling_blenderbot_small.py
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
def get_encoder(self):
    """
    Method: get_encoder

    Description:
    Returns the encoder component of the BlenderbotSmallForConditionalGeneration model.

    Args:
        self: BlenderbotSmallForConditionalGeneration
            The instance of the BlenderbotSmallForConditionalGeneration class.

    Returns:
        None

    Raises:
        None
    """
    return self.model.get_encoder()

mindnlp.transformers.models.blenderbot_small.modeling_blenderbot_small.BlenderbotSmallForConditionalGeneration.get_output_embeddings()

Method to retrieve the output embeddings of the model.

PARAMETER DESCRIPTION
self

Instance of the BlenderbotSmallForConditionalGeneration class.

RETURNS DESCRIPTION
None

This method returns the output embeddings of the model stored in the 'lm_head' attribute.

Source code in mindnlp/transformers/models/blenderbot_small/modeling_blenderbot_small.py
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
def get_output_embeddings(self):
    """
    Method to retrieve the output embeddings of the model.

    Args:
        self: Instance of the BlenderbotSmallForConditionalGeneration class.

    Returns:
        None: This method returns the output embeddings of the model stored in the 'lm_head' attribute.

    Raises:
        None.
    """
    return self.lm_head

mindnlp.transformers.models.blenderbot_small.modeling_blenderbot_small.BlenderbotSmallForConditionalGeneration.prepare_inputs_for_generation(decoder_input_ids, past_key_values=None, attention_mask=None, head_mask=None, decoder_head_mask=None, cross_attn_head_mask=None, use_cache=None, encoder_outputs=None, **kwargs)

Prepare inputs for generation.

PARAMETER DESCRIPTION
self

An instance of the BlenderbotSmallForConditionalGeneration class.

TYPE: BlenderbotSmallForConditionalGeneration

decoder_input_ids

The input tensor of decoder tokens. Shape: (batch_size, sequence_length).

TYPE: Tensor

past_key_values

The cached key-value states of the decoder. Default: None.

TYPE: Tuple[Tuple[Tensor]] DEFAULT: None

attention_mask

The attention mask tensor. Shape: (batch_size, sequence_length).

TYPE: Tensor DEFAULT: None

head_mask

The mask tensor for hiding heads of the encoder. Shape: (num_layers, num_heads).

TYPE: Tensor DEFAULT: None

decoder_head_mask

The mask tensor for hiding heads of the decoder. Shape: (num_layers, num_heads).

TYPE: Tensor DEFAULT: None

cross_attn_head_mask

The mask tensor for hiding heads of the cross-attention. Shape: (num_layers, num_heads).

TYPE: Tensor DEFAULT: None

use_cache

Whether to use cache for decoding. Default: None.

TYPE: bool DEFAULT: None

encoder_outputs

The output tensor of the encoder. Default: None.

TYPE: Tuple[Tensor] DEFAULT: None

RETURNS DESCRIPTION
dict

A dictionary containing the prepared inputs for generation. The keys are as follows:

  • 'input_ids' (None): Placeholder for input ids.
  • 'encoder_outputs' (Tuple[torch.Tensor]): The output tensor of the encoder.
  • 'past_key_values' (Tuple[Tuple[torch.Tensor]]): The cached key-value states of the decoder.
  • 'decoder_input_ids' (torch.Tensor): The modified input tensor of decoder tokens.
  • 'attention_mask' (torch.Tensor): The attention mask tensor.
  • 'head_mask' (torch.Tensor): The mask tensor for hiding heads of the encoder.
  • 'decoder_head_mask' (torch.Tensor): The mask tensor for hiding heads of the decoder.
  • 'cross_attn_head_mask' (torch.Tensor): The mask tensor for hiding heads of the cross-attention.
  • 'use_cache' (bool): Whether to use cache for decoding.
Source code in mindnlp/transformers/models/blenderbot_small/modeling_blenderbot_small.py
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
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
def prepare_inputs_for_generation(
    self,
    decoder_input_ids,
    past_key_values=None,
    attention_mask=None,
    head_mask=None,
    decoder_head_mask=None,
    cross_attn_head_mask=None,
    use_cache=None,
    encoder_outputs=None,
    **kwargs,
):
    '''
    Prepare inputs for generation.

    Args:
        self (BlenderbotSmallForConditionalGeneration): An instance of the BlenderbotSmallForConditionalGeneration class.
        decoder_input_ids (torch.Tensor): The input tensor of decoder tokens. Shape: (batch_size, sequence_length).
        past_key_values (Tuple[Tuple[torch.Tensor]]): The cached key-value states of the decoder. Default: None.
        attention_mask (torch.Tensor): The attention mask tensor. Shape: (batch_size, sequence_length).
        head_mask (torch.Tensor): The mask tensor for hiding heads of the encoder. Shape: (num_layers, num_heads).
        decoder_head_mask (torch.Tensor): The mask tensor for hiding heads of the decoder. Shape: (num_layers, num_heads).
        cross_attn_head_mask (torch.Tensor): The mask tensor for hiding heads of the cross-attention. Shape: (num_layers, num_heads).
        use_cache (bool): Whether to use cache for decoding. Default: None.
        encoder_outputs (Tuple[torch.Tensor]): The output tensor of the encoder. Default: None.

    Returns:
        dict: A dictionary containing the prepared inputs for generation.
            The keys are as follows:

            - 'input_ids' (None): Placeholder for input ids.
            - 'encoder_outputs' (Tuple[torch.Tensor]): The output tensor of the encoder.
            - 'past_key_values' (Tuple[Tuple[torch.Tensor]]): The cached key-value states of the decoder.
            - 'decoder_input_ids' (torch.Tensor): The modified input tensor of decoder tokens.
            - 'attention_mask' (torch.Tensor): The attention mask tensor.
            - 'head_mask' (torch.Tensor): The mask tensor for hiding heads of the encoder.
            - 'decoder_head_mask' (torch.Tensor): The mask tensor for hiding heads of the decoder.
            - 'cross_attn_head_mask' (torch.Tensor): The mask tensor for hiding heads of the cross-attention.
            - 'use_cache' (bool): Whether to use cache for decoding.

    Raises:
        None.
    '''
    # cut decoder_input_ids if past is used
    if past_key_values is not None:
        past_length = past_key_values[0][0].shape[2]

        # Some generation methods already pass only the last input ID
        if decoder_input_ids.shape[1] > past_length:
            remove_prefix_length = past_length
        else:
            # Default to old behavior: keep only final ID
            remove_prefix_length = decoder_input_ids.shape[1] - 1

        decoder_input_ids = decoder_input_ids[:, remove_prefix_length:]

    return {
        "input_ids": None,  # encoder_outputs is defined. input_ids not needed
        "encoder_outputs": encoder_outputs,
        "past_key_values": past_key_values,
        "decoder_input_ids": decoder_input_ids,
        "attention_mask": attention_mask,
        "head_mask": head_mask,
        "decoder_head_mask": decoder_head_mask,
        "cross_attn_head_mask": cross_attn_head_mask,
        "use_cache": use_cache,  # change this to avoid caching (presumably for debugging)
    }

mindnlp.transformers.models.blenderbot_small.modeling_blenderbot_small.BlenderbotSmallForConditionalGeneration.resize_token_embeddings(new_num_tokens, pad_to_multiple_of=None)

Resize the token embeddings for the BlenderbotSmallForConditionalGeneration model.

PARAMETER DESCRIPTION
self

The instance of the class BlenderbotSmallForConditionalGeneration.

new_num_tokens

The new number of tokens to resize the embedding to.

TYPE: int

pad_to_multiple_of

If provided, the new embedding size will be padded to a multiple of this value.

TYPE: Optional[int] DEFAULT: None

RETURNS DESCRIPTION
Embedding

nn.Embedding: The resized token embeddings as an instance of nn.Embedding.

Source code in mindnlp/transformers/models/blenderbot_small/modeling_blenderbot_small.py
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
def resize_token_embeddings(self, new_num_tokens: int, pad_to_multiple_of: Optional[int] = None) -> nn.Embedding:
    """
    Resize the token embeddings for the BlenderbotSmallForConditionalGeneration model.

    Args:
        self: The instance of the class BlenderbotSmallForConditionalGeneration.
        new_num_tokens (int): The new number of tokens to resize the embedding to.
        pad_to_multiple_of (Optional[int]): If provided, the new embedding size will be padded to a multiple of this value.

    Returns:
        nn.Embedding: The resized token embeddings as an instance of nn.Embedding.

    Raises:
        None.
    """
    new_embeddings = super().resize_token_embeddings(new_num_tokens, pad_to_multiple_of)
    self._resize_final_logits_bias(new_embeddings.weight.shape[0])
    return new_embeddings

mindnlp.transformers.models.blenderbot_small.modeling_blenderbot_small.BlenderbotSmallForConditionalGeneration.set_output_embeddings(new_embeddings)

Sets the output embeddings for the BlenderbotSmallForConditionalGeneration model.

PARAMETER DESCRIPTION
self

The instance of the BlenderbotSmallForConditionalGeneration class.

TYPE: BlenderbotSmallForConditionalGeneration

new_embeddings

The new output embeddings to be set for the model. It should be a tensor of shape (vocab_size, hidden_size).

TYPE: Tensor

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the new_embeddings parameter is not a torch.Tensor.

ValueError

If the shape of new_embeddings does not match the expected shape (vocab_size, hidden_size).

Source code in mindnlp/transformers/models/blenderbot_small/modeling_blenderbot_small.py
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
def set_output_embeddings(self, new_embeddings):
    """
    Sets the output embeddings for the BlenderbotSmallForConditionalGeneration model.

    Args:
        self (BlenderbotSmallForConditionalGeneration): The instance of the BlenderbotSmallForConditionalGeneration class.
        new_embeddings (torch.Tensor): The new output embeddings to be set for the model.
            It should be a tensor of shape (vocab_size, hidden_size).

    Returns:
        None.

    Raises:
        TypeError: If the new_embeddings parameter is not a torch.Tensor.
        ValueError: If the shape of new_embeddings does not match the expected shape (vocab_size, hidden_size).
    """
    self.lm_head = new_embeddings

mindnlp.transformers.models.blenderbot_small.modeling_blenderbot_small.BlenderbotSmallModel

Bases: BlenderbotSmallPreTrainedModel

This class represents the BlenderbotSmallModel, which is a Python implementation of the Blenderbot Small model for chat-based language generation.

The BlenderbotSmallModel is a Seq2Seq model that consists of an encoder and a decoder. The encoder encodes the input text into hidden states, while the decoder generates the output text based on the encoded information. The model uses shared embeddings for both the encoder and the decoder.

This class inherits from the BlenderbotSmallPreTrainedModel.

Example
>>> from transformers import AutoTokenizer, BlenderbotSmallModel
...
>>> model = BlenderbotSmallModel.from_pretrained("facebook/blenderbot_small-90M")
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
...
>>> inputs = tokenizer("Studies have been shown that owning a dog is good for you", return_tensors="pt")
>>> decoder_inputs = tokenizer("Studies show that", return_tensors="pt")  # Batch size 1
>>> outputs = model(input_ids=inputs.input_ids, decoder_input_ids=decoder_inputs.input_ids)
...
>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 3, 512]
METHOD DESCRIPTION
__init__

BlenderbotSmallConfig): Initializes the BlenderbotSmallModel with the provided configuration.

get_input_embeddings

Returns the shared input embeddings.

set_input_embeddings

Sets the shared input embeddings.

get_encoder

Returns the encoder of the model.

get_decoder

Returns the decoder of the model.

Source code in mindnlp/transformers/models/blenderbot_small/modeling_blenderbot_small.py
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
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
class BlenderbotSmallModel(BlenderbotSmallPreTrainedModel):

    """
        This class represents the BlenderbotSmallModel, which is a Python implementation of the Blenderbot Small model for chat-based language generation.

        The BlenderbotSmallModel is a Seq2Seq model that consists of an encoder and a decoder.
        The encoder encodes the input text into hidden states, while the decoder generates the output text based on the
        encoded information. The model uses shared embeddings for both the encoder and the decoder.

        This class inherits from the BlenderbotSmallPreTrainedModel.

        Example:
            ```python
            >>> from transformers import AutoTokenizer, BlenderbotSmallModel
            ...
            >>> model = BlenderbotSmallModel.from_pretrained("facebook/blenderbot_small-90M")
            >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
            ...
            >>> inputs = tokenizer("Studies have been shown that owning a dog is good for you", return_tensors="pt")
            >>> decoder_inputs = tokenizer("Studies show that", return_tensors="pt")  # Batch size 1
            >>> outputs = model(input_ids=inputs.input_ids, decoder_input_ids=decoder_inputs.input_ids)
            ...
            >>> last_hidden_states = outputs.last_hidden_state
            >>> list(last_hidden_states.shape)
            [1, 3, 512]
            ```

        Methods:
            __init__(self, config: BlenderbotSmallConfig): 
                Initializes the BlenderbotSmallModel with the provided configuration.
            get_input_embeddings(self): Returns the shared input embeddings.
            set_input_embeddings(self, value): Sets the shared input embeddings.
            get_encoder(self): Returns the encoder of the model.
            get_decoder(self): Returns the decoder of the model.
            forward(self, input_ids, attention_mask, decoder_input_ids, decoder_attention_mask, head_mask, 
                decoder_head_mask, cross_attn_head_mask, encoder_outputs, past_key_values, inputs_embeds,
                decoder_inputs_embeds, use_cache, output_attentions, output_hidden_states, return_dict): 
                Constructs the model with the given inputs and returns the output.

        """
    _tied_weights_keys = ["decoder.embed_tokens.weight", "encoder.embed_tokens.weight"]

    def __init__(self, config: BlenderbotSmallConfig):
        """
        Initializes a new instance of BlenderbotSmallModel with the provided configuration.

        Args:
            self (BlenderbotSmallModel): The instance of the BlenderbotSmallModel class.
            config (BlenderbotSmallConfig): The configuration object containing model settings.
                It must be an instance of BlenderbotSmallConfig class.

        Returns:
            None.

        Raises:
            TypeError: If the config parameter is not of type BlenderbotSmallConfig.
            ValueError: If any of the required parameters from the config object are missing or invalid.
        """
        super().__init__(config)

        padding_idx, vocab_size = config.pad_token_id, config.vocab_size
        self.shared = nn.Embedding(vocab_size, config.d_model, padding_idx)

        self.encoder = BlenderbotSmallEncoder(config, self.shared)
        self.decoder = BlenderbotSmallDecoder(config, self.shared)

        # Initialize weights and apply final processing
        self.post_init()

    def get_input_embeddings(self):
        """
        Method to retrieve the input embeddings from the BlenderbotSmallModel.

        Args:
            self: The instance of the BlenderbotSmallModel class.
                Type: class instance.
                Purpose: Represents the current instance of the BlenderbotSmallModel class.
                Restrictions: None.

        Returns:
            None.

        Raises:
            None.
        """
        return self.shared

    def set_input_embeddings(self, value):
        """
        Sets the input embeddings for the BlenderbotSmallModel.

        Args:
            self (BlenderbotSmallModel): The instance of the BlenderbotSmallModel class.
            value: The input embeddings to be set. It should be a tensor of shape [vocab_size, embedding_dim].

        Returns:
            None.

        Raises:
            None.
        """
        self.shared = value
        self.encoder.embed_tokens = self.shared
        self.decoder.embed_tokens = self.shared

    def get_encoder(self):
        """
        Method to retrieve the encoder of the BlenderbotSmallModel instance.

        Args:
            self: The instance of the BlenderbotSmallModel class. It is required to access the encoder.

        Returns:
            NoneType: The method returns the encoder associated with the BlenderbotSmallModel instance.
                The encoder is used for encoding input data in the model.

        Raises:
            None
        """
        return self.encoder

    def get_decoder(self):
        """
        This method returns the decoder attribute of the BlenderbotSmallModel.

        Args:
            self: BlenderbotSmallModel - The instance of the BlenderbotSmallModel class.

        Returns:
            None: This method returns the decoder attribute of the BlenderbotSmallModel.

        Raises:
            None.
        """
        return self.decoder

    def forward(
        self,
        input_ids: Optional[mindspore.Tensor] = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        decoder_input_ids: Optional[mindspore.Tensor] = None,
        decoder_attention_mask: Optional[mindspore.Tensor] = None,
        head_mask: Optional[mindspore.Tensor] = None,
        decoder_head_mask: Optional[mindspore.Tensor] = None,
        cross_attn_head_mask: Optional[mindspore.Tensor] = None,
        encoder_outputs: Optional[Union[Tuple, BaseModelOutput]] = None,
        past_key_values: Optional[List[mindspore.Tensor]] = None,
        inputs_embeds: Optional[mindspore.Tensor] = None,
        decoder_inputs_embeds: Optional[mindspore.Tensor] = None,
        use_cache: Optional[bool] = None,
        output_attentions: Optional[bool] = None,
        output_hidden_states: Optional[bool] = None,
        return_dict: Optional[bool] = None,
    ) -> Union[Tuple[mindspore.Tensor], Seq2SeqModelOutput]:
        r"""
        Returns:
            Union[Tuple[mindspore.Tensor], Seq2SeqModelOutput]

        Example:
            ```python
            >>> from transformers import AutoTokenizer, BlenderbotSmallModel
            ...
            >>> model = BlenderbotSmallModel.from_pretrained("facebook/blenderbot_small-90M")
            >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
            ...
            >>> inputs = tokenizer("Studies have been shown that owning a dog is good for you", return_tensors="pt")
            >>> decoder_inputs = tokenizer("Studies show that", return_tensors="pt")  # Batch size 1
            >>> outputs = model(input_ids=inputs.input_ids, decoder_input_ids=decoder_inputs.input_ids)
            ...
            >>> last_hidden_states = outputs.last_hidden_state
            >>> list(last_hidden_states.shape)
            [1, 3, 512]
            ```
        """
        output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
        output_hidden_states = (
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )
        use_cache = use_cache if use_cache is not None else self.config.use_cache
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        if encoder_outputs is None:
            encoder_outputs = self.encoder(
                input_ids=input_ids,
                attention_mask=attention_mask,
                head_mask=head_mask,
                inputs_embeds=inputs_embeds,
                output_attentions=output_attentions,
                output_hidden_states=output_hidden_states,
                return_dict=return_dict,
            )
        # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
        elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
            encoder_outputs = BaseModelOutput(
                last_hidden_state=encoder_outputs[0],
                hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
                attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
            )

        # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)
        decoder_outputs = self.decoder(
            input_ids=decoder_input_ids,
            attention_mask=decoder_attention_mask,
            encoder_hidden_states=encoder_outputs[0],
            encoder_attention_mask=attention_mask,
            head_mask=decoder_head_mask,
            cross_attn_head_mask=cross_attn_head_mask,
            past_key_values=past_key_values,
            inputs_embeds=decoder_inputs_embeds,
            use_cache=use_cache,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )

        if not return_dict:
            return decoder_outputs + encoder_outputs

        return Seq2SeqModelOutput(
            last_hidden_state=decoder_outputs.last_hidden_state,
            past_key_values=decoder_outputs.past_key_values,
            decoder_hidden_states=decoder_outputs.hidden_states,
            decoder_attentions=decoder_outputs.attentions,
            cross_attentions=decoder_outputs.cross_attentions,
            encoder_last_hidden_state=encoder_outputs.last_hidden_state,
            encoder_hidden_states=encoder_outputs.hidden_states,
            encoder_attentions=encoder_outputs.attentions,
        )

mindnlp.transformers.models.blenderbot_small.modeling_blenderbot_small.BlenderbotSmallModel.__init__(config)

Initializes a new instance of BlenderbotSmallModel with the provided configuration.

PARAMETER DESCRIPTION
self

The instance of the BlenderbotSmallModel class.

TYPE: BlenderbotSmallModel

config

The configuration object containing model settings. It must be an instance of BlenderbotSmallConfig class.

TYPE: BlenderbotSmallConfig

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the config parameter is not of type BlenderbotSmallConfig.

ValueError

If any of the required parameters from the config object are missing or invalid.

Source code in mindnlp/transformers/models/blenderbot_small/modeling_blenderbot_small.py
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
def __init__(self, config: BlenderbotSmallConfig):
    """
    Initializes a new instance of BlenderbotSmallModel with the provided configuration.

    Args:
        self (BlenderbotSmallModel): The instance of the BlenderbotSmallModel class.
        config (BlenderbotSmallConfig): The configuration object containing model settings.
            It must be an instance of BlenderbotSmallConfig class.

    Returns:
        None.

    Raises:
        TypeError: If the config parameter is not of type BlenderbotSmallConfig.
        ValueError: If any of the required parameters from the config object are missing or invalid.
    """
    super().__init__(config)

    padding_idx, vocab_size = config.pad_token_id, config.vocab_size
    self.shared = nn.Embedding(vocab_size, config.d_model, padding_idx)

    self.encoder = BlenderbotSmallEncoder(config, self.shared)
    self.decoder = BlenderbotSmallDecoder(config, self.shared)

    # Initialize weights and apply final processing
    self.post_init()

mindnlp.transformers.models.blenderbot_small.modeling_blenderbot_small.BlenderbotSmallModel.forward(input_ids=None, attention_mask=None, decoder_input_ids=None, decoder_attention_mask=None, head_mask=None, decoder_head_mask=None, cross_attn_head_mask=None, encoder_outputs=None, past_key_values=None, inputs_embeds=None, decoder_inputs_embeds=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None)

RETURNS DESCRIPTION
Union[Tuple[Tensor], Seq2SeqModelOutput]

Union[Tuple[mindspore.Tensor], Seq2SeqModelOutput]

Example
>>> from transformers import AutoTokenizer, BlenderbotSmallModel
...
>>> model = BlenderbotSmallModel.from_pretrained("facebook/blenderbot_small-90M")
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
...
>>> inputs = tokenizer("Studies have been shown that owning a dog is good for you", return_tensors="pt")
>>> decoder_inputs = tokenizer("Studies show that", return_tensors="pt")  # Batch size 1
>>> outputs = model(input_ids=inputs.input_ids, decoder_input_ids=decoder_inputs.input_ids)
...
>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 3, 512]
Source code in mindnlp/transformers/models/blenderbot_small/modeling_blenderbot_small.py
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
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
def forward(
    self,
    input_ids: Optional[mindspore.Tensor] = None,
    attention_mask: Optional[mindspore.Tensor] = None,
    decoder_input_ids: Optional[mindspore.Tensor] = None,
    decoder_attention_mask: Optional[mindspore.Tensor] = None,
    head_mask: Optional[mindspore.Tensor] = None,
    decoder_head_mask: Optional[mindspore.Tensor] = None,
    cross_attn_head_mask: Optional[mindspore.Tensor] = None,
    encoder_outputs: Optional[Union[Tuple, BaseModelOutput]] = None,
    past_key_values: Optional[List[mindspore.Tensor]] = None,
    inputs_embeds: Optional[mindspore.Tensor] = None,
    decoder_inputs_embeds: Optional[mindspore.Tensor] = None,
    use_cache: Optional[bool] = None,
    output_attentions: Optional[bool] = None,
    output_hidden_states: Optional[bool] = None,
    return_dict: Optional[bool] = None,
) -> Union[Tuple[mindspore.Tensor], Seq2SeqModelOutput]:
    r"""
    Returns:
        Union[Tuple[mindspore.Tensor], Seq2SeqModelOutput]

    Example:
        ```python
        >>> from transformers import AutoTokenizer, BlenderbotSmallModel
        ...
        >>> model = BlenderbotSmallModel.from_pretrained("facebook/blenderbot_small-90M")
        >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
        ...
        >>> inputs = tokenizer("Studies have been shown that owning a dog is good for you", return_tensors="pt")
        >>> decoder_inputs = tokenizer("Studies show that", return_tensors="pt")  # Batch size 1
        >>> outputs = model(input_ids=inputs.input_ids, decoder_input_ids=decoder_inputs.input_ids)
        ...
        >>> last_hidden_states = outputs.last_hidden_state
        >>> list(last_hidden_states.shape)
        [1, 3, 512]
        ```
    """
    output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
    output_hidden_states = (
        output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
    )
    use_cache = use_cache if use_cache is not None else self.config.use_cache
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict

    if encoder_outputs is None:
        encoder_outputs = self.encoder(
            input_ids=input_ids,
            attention_mask=attention_mask,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )
    # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
    elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
        encoder_outputs = BaseModelOutput(
            last_hidden_state=encoder_outputs[0],
            hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
            attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
        )

    # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)
    decoder_outputs = self.decoder(
        input_ids=decoder_input_ids,
        attention_mask=decoder_attention_mask,
        encoder_hidden_states=encoder_outputs[0],
        encoder_attention_mask=attention_mask,
        head_mask=decoder_head_mask,
        cross_attn_head_mask=cross_attn_head_mask,
        past_key_values=past_key_values,
        inputs_embeds=decoder_inputs_embeds,
        use_cache=use_cache,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )

    if not return_dict:
        return decoder_outputs + encoder_outputs

    return Seq2SeqModelOutput(
        last_hidden_state=decoder_outputs.last_hidden_state,
        past_key_values=decoder_outputs.past_key_values,
        decoder_hidden_states=decoder_outputs.hidden_states,
        decoder_attentions=decoder_outputs.attentions,
        cross_attentions=decoder_outputs.cross_attentions,
        encoder_last_hidden_state=encoder_outputs.last_hidden_state,
        encoder_hidden_states=encoder_outputs.hidden_states,
        encoder_attentions=encoder_outputs.attentions,
    )

mindnlp.transformers.models.blenderbot_small.modeling_blenderbot_small.BlenderbotSmallModel.get_decoder()

This method returns the decoder attribute of the BlenderbotSmallModel.

PARAMETER DESCRIPTION
self

BlenderbotSmallModel - The instance of the BlenderbotSmallModel class.

RETURNS DESCRIPTION
None

This method returns the decoder attribute of the BlenderbotSmallModel.

Source code in mindnlp/transformers/models/blenderbot_small/modeling_blenderbot_small.py
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
def get_decoder(self):
    """
    This method returns the decoder attribute of the BlenderbotSmallModel.

    Args:
        self: BlenderbotSmallModel - The instance of the BlenderbotSmallModel class.

    Returns:
        None: This method returns the decoder attribute of the BlenderbotSmallModel.

    Raises:
        None.
    """
    return self.decoder

mindnlp.transformers.models.blenderbot_small.modeling_blenderbot_small.BlenderbotSmallModel.get_encoder()

Method to retrieve the encoder of the BlenderbotSmallModel instance.

PARAMETER DESCRIPTION
self

The instance of the BlenderbotSmallModel class. It is required to access the encoder.

RETURNS DESCRIPTION
NoneType

The method returns the encoder associated with the BlenderbotSmallModel instance. The encoder is used for encoding input data in the model.

Source code in mindnlp/transformers/models/blenderbot_small/modeling_blenderbot_small.py
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
def get_encoder(self):
    """
    Method to retrieve the encoder of the BlenderbotSmallModel instance.

    Args:
        self: The instance of the BlenderbotSmallModel class. It is required to access the encoder.

    Returns:
        NoneType: The method returns the encoder associated with the BlenderbotSmallModel instance.
            The encoder is used for encoding input data in the model.

    Raises:
        None
    """
    return self.encoder

mindnlp.transformers.models.blenderbot_small.modeling_blenderbot_small.BlenderbotSmallModel.get_input_embeddings()

Method to retrieve the input embeddings from the BlenderbotSmallModel.

PARAMETER DESCRIPTION
self

The instance of the BlenderbotSmallModel class. Type: class instance. Purpose: Represents the current instance of the BlenderbotSmallModel class. Restrictions: None.

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/blenderbot_small/modeling_blenderbot_small.py
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
def get_input_embeddings(self):
    """
    Method to retrieve the input embeddings from the BlenderbotSmallModel.

    Args:
        self: The instance of the BlenderbotSmallModel class.
            Type: class instance.
            Purpose: Represents the current instance of the BlenderbotSmallModel class.
            Restrictions: None.

    Returns:
        None.

    Raises:
        None.
    """
    return self.shared

mindnlp.transformers.models.blenderbot_small.modeling_blenderbot_small.BlenderbotSmallModel.set_input_embeddings(value)

Sets the input embeddings for the BlenderbotSmallModel.

PARAMETER DESCRIPTION
self

The instance of the BlenderbotSmallModel class.

TYPE: BlenderbotSmallModel

value

The input embeddings to be set. It should be a tensor of shape [vocab_size, embedding_dim].

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/blenderbot_small/modeling_blenderbot_small.py
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
def set_input_embeddings(self, value):
    """
    Sets the input embeddings for the BlenderbotSmallModel.

    Args:
        self (BlenderbotSmallModel): The instance of the BlenderbotSmallModel class.
        value: The input embeddings to be set. It should be a tensor of shape [vocab_size, embedding_dim].

    Returns:
        None.

    Raises:
        None.
    """
    self.shared = value
    self.encoder.embed_tokens = self.shared
    self.decoder.embed_tokens = self.shared

mindnlp.transformers.models.blenderbot_small.modeling_blenderbot_small.BlenderbotSmallPreTrainedModel

Bases: PreTrainedModel

This class represents a small version of the Blenderbot model that has been pre-trained on a specific task. It is a subclass of the PreTrainedModel class.

The BlenderbotSmallPreTrainedModel class provides methods for initializing the weights of the model and generating dummy inputs for testing purposes.

To initialize the weights, the _init_weights method is called with a specified cell object. If the cell is of type nn.Linear, the weights are initialized using the normal distribution with a standard deviation of self.config.init_std. If the cell has biases, they are initialized to zeros. If the cell is of type nn.Embedding, the weights are initialized using a normal distribution with a mean of 0.0 and a standard deviation of self.config.init_std. If a padding index is provided, the corresponding weights are set to 0.

The dummy_inputs property returns a dictionary of dummy inputs that can be used for testing. It includes 'attention_mask', 'input_ids', and 'decoder_input_ids'. The 'input_ids' tensor contains two rows, with the second row having a padding token represented by self.config.pad_token_id. The 'attention_mask' tensor is obtained by checking if each element of 'input_ids' is not equal to the padding token. The 'decoder_input_ids' tensor is the same as the 'input_ids' tensor.

Note

This docstring does not include signatures or any other code.

Source code in mindnlp/transformers/models/blenderbot_small/modeling_blenderbot_small.py
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
class BlenderbotSmallPreTrainedModel(PreTrainedModel):

    """
    This class represents a small version of the Blenderbot model that has been pre-trained on a specific task.
    It is a subclass of the `PreTrainedModel` class.

    The `BlenderbotSmallPreTrainedModel` class provides methods for initializing the weights of the model
    and generating dummy inputs for testing purposes.

    To initialize the weights, the `_init_weights` method is called with a specified `cell` object.
    If the `cell` is of type `nn.Linear`, the weights are initialized using the normal distribution with a
    standard deviation of `self.config.init_std`.
    If the `cell` has biases, they are initialized to zeros.
    If the `cell` is of type `nn.Embedding`, the weights are initialized using a normal distribution with a
    mean of 0.0 and a standard deviation of `self.config.init_std`.
    If a padding index is provided, the corresponding weights are set to 0.

    The `dummy_inputs` property returns a dictionary of dummy inputs that can be used for testing.
    It includes 'attention_mask', 'input_ids', and 'decoder_input_ids'. The 'input_ids' tensor contains two rows,
    with the second row having a padding token represented by `self.config.pad_token_id`.
    The 'attention_mask' tensor is obtained by checking if each element of 'input_ids' is not equal to the padding token.
    The 'decoder_input_ids' tensor is the same as the 'input_ids' tensor.

    Note:
        This docstring does not include signatures or any other code.
    """
    config_class = BlenderbotSmallConfig
    base_model_prefix = "model"
    supports_gradient_checkpointing = True

    def _init_weights(self, cell):
        """Initialize the weights"""
        std = self.config.init_std
        if isinstance(cell, nn.Linear):
            # Slightly different from the TF version which uses truncated_normal for initialization
            # cf https://github.com/pytorch/pytorch/pull/5617
            cell.weight.set_data(initializer(Normal(std),
                                                    cell.weight.shape, cell.weight.dtype))
            if cell.bias is not None:
                cell.bias.set_data(initializer('zeros', cell.bias.shape, cell.bias.dtype))
        elif isinstance(cell, nn.Embedding):
            weight = np.random.normal(0.0, std, cell.weight.shape)
            if cell.padding_idx:
                weight[cell.padding_idx] = 0

            cell.weight.set_data(Tensor(weight, cell.weight.dtype))

    @property
    def dummy_inputs(self):
        """
        This method returns a dictionary of dummy inputs for the BlenderbotSmallPreTrainedModel.

        Args:
            self: BlenderbotSmallPreTrainedModel
                The instance of the BlenderbotSmallPreTrainedModel class.

        Returns:
            dict:
                A dictionary containing dummy inputs with the following keys:

                - 'attention_mask': A tensor representing the attention mask for the input_ids.
                - 'input_ids': A tensor containing the input token IDs.
                - 'decoder_input_ids': A tensor containing the decoder input token IDs.

        Raises:
            None
        """
        pad_token = self.config.pad_token_id
        input_ids = mindspore.tensor([[0, 6, 10, 4, 2], [0, 8, 12, 2, pad_token]])
        dummy_inputs = {
            "attention_mask": input_ids.ne(pad_token),
            "input_ids": input_ids,
            "decoder_input_ids": input_ids,
        }
        return dummy_inputs

mindnlp.transformers.models.blenderbot_small.modeling_blenderbot_small.BlenderbotSmallPreTrainedModel.dummy_inputs property

This method returns a dictionary of dummy inputs for the BlenderbotSmallPreTrainedModel.

PARAMETER DESCRIPTION
self

BlenderbotSmallPreTrainedModel The instance of the BlenderbotSmallPreTrainedModel class.

RETURNS DESCRIPTION
dict

A dictionary containing dummy inputs with the following keys:

  • 'attention_mask': A tensor representing the attention mask for the input_ids.
  • 'input_ids': A tensor containing the input token IDs.
  • 'decoder_input_ids': A tensor containing the decoder input token IDs.

mindnlp.transformers.models.blenderbot_small.tokenization_blenderbot_small.BlenderbotSmallTokenizer

Bases: PreTrainedTokenizer

Constructs a Blenderbot-90M tokenizer based on BPE (Byte-Pair-Encoding)

This tokenizer inherits from [PreTrainedTokenizer] which contains most of the main methods. Users should refer to the superclass for more information regarding methods.

PARAMETER DESCRIPTION
vocab_file

File containing the vocabulary.

TYPE: `str`

merges_file

Path to the merges file.

TYPE: `str`

bos_token

The beginning of sentence token.

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

eos_token

The end of sentence token.

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

unk_token

The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this token instead.

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

pad_token

The token used for padding, for example when batching sequences of different lengths.

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

kwargs

Additional keyword arguments passed along to [PreTrainedTokenizer]

TYPE: *optional* DEFAULT: {}

Source code in mindnlp/transformers/models/blenderbot_small/tokenization_blenderbot_small.py
 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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
class BlenderbotSmallTokenizer(PreTrainedTokenizer):
    """
    Constructs a Blenderbot-90M tokenizer based on BPE (Byte-Pair-Encoding)

    This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
    the superclass for more information regarding methods.

    Args:
        vocab_file (`str`):
            File containing the vocabulary.
        merges_file (`str`):
            Path to the merges file.
        bos_token (`str`, *optional*, defaults to `"__start__"`):
            The beginning of sentence token.
        eos_token (`str`, *optional*, defaults to `"__end__"`):
            The end of sentence token.
        unk_token (`str`, *optional*, defaults to `"__unk__"`):
            The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
            token instead.
        pad_token (`str`, *optional*, defaults to `"__null__"`):
            The token used for padding, for example when batching sequences of different lengths.
        kwargs (*optional*):
            Additional keyword arguments passed along to [`PreTrainedTokenizer`]
    """
    vocab_files_names = VOCAB_FILES_NAMES
    model_input_names = ["input_ids", "attention_mask"]

    def __init__(
        self,
        vocab_file,
        merges_file,
        bos_token="__start__",
        eos_token="__end__",
        unk_token="__unk__",
        pad_token="__null__",
        **kwargs,
    ):
        """
        Initializes a BlenderbotSmallTokenizer instance with the provided parameters.

        Args:
            self (BlenderbotSmallTokenizer): The instance of the BlenderbotSmallTokenizer class.
            vocab_file (str): The file path to the vocabulary file containing encoding information.
            merges_file (str): The file path to the merges file containing BPE merges information.
            bos_token (str, optional): The beginning of sentence token. Defaults to '__start__'.
            eos_token (str, optional): The end of sentence token. Defaults to '__end__'.
            unk_token (str, optional): The unknown token. Defaults to '__unk__'.
            pad_token (str, optional): The padding token. Defaults to '__null__'.
            **kwargs: Additional keyword arguments.

        Returns:
            None: This method initializes the BlenderbotSmallTokenizer instance with the provided parameters.

        Raises:
            FileNotFoundError: If either vocab_file or merges_file is not found.
            JSONDecodeError: If there is an issue decoding the vocabulary file.
            IndexError: If there is an issue accessing elements during initialization.
        """
        with open(vocab_file, encoding="utf-8") as vocab_handle:
            self.encoder = json.load(vocab_handle)
        self.decoder = {v: k for k, v in self.encoder.items()}
        with open(merges_file, encoding="utf-8") as merges_handle:
            merges = merges_handle.read().split("\n")[1:-1]
        merges = [tuple(merge.split()) for merge in merges]
        self.bpe_ranks = dict(zip(merges, range(len(merges))))
        self.cache = {}
        super().__init__(unk_token=unk_token, bos_token=bos_token, eos_token=eos_token, pad_token=pad_token, **kwargs)

    @property
    def vocab_size(self) -> int:
        """
        Returns the size of the vocabulary used by the BlenderbotSmallTokenizer instance.

        Args:
            self: The instance of the BlenderbotSmallTokenizer class.

        Returns:
            An integer representing the size of the vocabulary.

        Raises:
            None.
        """
        return len(self.encoder)

    def get_vocab(self) -> Dict:
        """
        Retrieve the vocabulary of the BlenderbotSmallTokenizer.

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

        Returns:
            Dict: A dictionary representing the vocabulary of the tokenizer, containing the encoder and added tokens encoder.

        Raises:
            None.
        """
        return dict(self.encoder, **self.added_tokens_encoder)

    def bpe(self, token: str) -> str:
        """
        The 'bpe' method in the 'BlenderbotSmallTokenizer' class performs Byte Pair Encoding (BPE) on a given token.

        Args:
            self (BlenderbotSmallTokenizer): An instance of the BlenderbotSmallTokenizer class.
            token (str): The input token to be processed with BPE.

        Returns:
            str: The token after BPE processing.

        Raises:
            None.

        This method applies the following steps to perform BPE:

        1. Checks if the token exists in the cache. If yes, returns the cached value.
        2. Applies regular expression substitution to separate certain punctuation marks from the token.
        3. Replaces single quotes with spaces around them.
        4. Reduces consecutive whitespace characters to a single space.
        5. If the token contains a newline character, replaces it with '__newln__'.
        6. Splits the token into a list of individual words.
        7. Processes each word in the list:

            - Converts the word to lowercase.
            - Converts the word into a tuple.
            - Appends '</w>' to the last character of the tuple.
            - Retrieves the pairs of characters in the word.
            - If no pairs are found, appends the original word to the final list and continues to the next word.
            - Continues to find and merge the most frequent pair of characters in the word until no more relevant pairs are found.
            - Joins the merged characters with '@@ ' and removes the '</w>' suffix.
            - Caches the processed word for future use.
            - Appends the processed word to the final list.

        8. Joins all the words in the final list with a space separator and returns the result.
        """
        if token in self.cache:
            return self.cache[token]
        token = re.sub("([.,!?()])", r" \1", token)
        token = re.sub("(')", r" \1 ", token)
        token = re.sub(r"\s{2,}", " ", token)
        if "\n" in token:
            token = token.replace("\n", " __newln__")

        tokens = token.split(" ")
        words = []
        for token in tokens:
            if not len(token): # pylint: disable=use-implicit-booleaness-not-len
                continue

            token = token.lower()
            word = tuple(token)
            word = tuple(list(word[:-1]) + [word[-1] + "</w>"])
            pairs = get_pairs(word)

            if not pairs:
                words.append(token)
                continue

            while True:
                bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
                if bigram not in self.bpe_ranks:
                    break
                first, second = bigram
                new_word = []
                i = 0

                while i < len(word):
                    try:
                        j = word.index(first, i)
                        new_word.extend(word[i:j])
                        i = j
                    except ValueError:
                        new_word.extend(word[i:])
                        break

                    if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
                        new_word.append(first + second)
                        i += 2
                    else:
                        new_word.append(word[i])
                        i += 1
                new_word = tuple(new_word)
                word = new_word
                if len(word) == 1:
                    break
                else:
                    pairs = get_pairs(word)
            word = "@@ ".join(word)
            word = word[:-4]

            self.cache[token] = word
            words.append(word)
        return " ".join(words)

    def _tokenize(self, text: str) -> List[str]:
        """Split a string into tokens using BPE."""
        split_tokens = []

        words = re.findall(r"\S+\n?", text)

        for token in words:
            split_tokens.extend(list(self.bpe(token).split(" ")))
        return split_tokens

    def _convert_token_to_id(self, token: str) -> int:
        """Converts a token to an id using the vocab."""
        token = token.lower()
        return self.encoder.get(token, self.encoder.get(self.unk_token))

    def _convert_id_to_token(self, index: int) -> str:
        """Converts an index (integer) in a token (str) using the vocab."""
        return self.decoder.get(index, self.unk_token)

    def convert_tokens_to_string(self, tokens: List[str]) -> str:
        """Converts a sequence of tokens in a single string."""
        out_string = " ".join(tokens).replace("@@ ", "").strip()
        return out_string

    def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
        """
        Save the vocabulary and merge files for the BlenderbotSmallTokenizer.

        Args:
            self (BlenderbotSmallTokenizer): An instance of the BlenderbotSmallTokenizer class.
            save_directory (str): The directory where the vocabulary and merge files will be saved.
            filename_prefix (Optional[str], optional): A prefix to be added to the filename. Defaults to None.

        Returns:
            Tuple[str]: A tuple containing the paths of the saved vocabulary and merge files.

        Raises:
            FileNotFoundError: If the specified save_directory does not exist.
            TypeError: If the save_directory is not of type str.
            ValueError: If the save_directory is not a valid directory path.
        """
        if not os.path.isdir(save_directory):
            logger.error(f"Vocabulary path ({save_directory}) should be a directory")
            return
        vocab_file = os.path.join(
            save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
        )
        merge_file = os.path.join(
            save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
        )

        with open(vocab_file, "w", encoding="utf-8") as f:
            f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")

        index = 0
        with open(merge_file, "w", encoding="utf-8") as writer:
            writer.write("#version: 0.2\n")
            for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
                if index != token_index:
                    logger.warning(
                        f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
                        " Please check that the tokenizer is not corrupted!"
                    )
                    index = token_index
                writer.write(" ".join(bpe_tokens) + "\n")
                index += 1

        return vocab_file, merge_file

    @property
    # Copied from transformers.models.blenderbot.tokenization_blenderbot.BlenderbotTokenizer.default_chat_template
    def default_chat_template(self):
        """
        A very simple chat template that just adds whitespace between messages.
        """
        logger.warning_once(
            "\nNo chat template is defined for this tokenizer - using the default template "
            f"for the {self.__class__.__name__} class. If the default is not appropriate for "
            "your model, please set `tokenizer.chat_template` to an appropriate template. "
            "See https://huggingface.co/docs/transformers/main/chat_templating for more information.\n"
        )
        return (
            "{% for message in messages %}"
            "{% if message['role'] == 'user' %}{{ ' ' }}{% endif %}"
            "{{ message['content'] }}"
            "{% if not loop.last %}{{ '  ' }}{% endif %}"
            "{% endfor %}"
            "{{ eos_token }}"
        )

mindnlp.transformers.models.blenderbot_small.tokenization_blenderbot_small.BlenderbotSmallTokenizer.default_chat_template property

A very simple chat template that just adds whitespace between messages.

mindnlp.transformers.models.blenderbot_small.tokenization_blenderbot_small.BlenderbotSmallTokenizer.vocab_size: int property

Returns the size of the vocabulary used by the BlenderbotSmallTokenizer instance.

PARAMETER DESCRIPTION
self

The instance of the BlenderbotSmallTokenizer class.

RETURNS DESCRIPTION
int

An integer representing the size of the vocabulary.

mindnlp.transformers.models.blenderbot_small.tokenization_blenderbot_small.BlenderbotSmallTokenizer.__init__(vocab_file, merges_file, bos_token='__start__', eos_token='__end__', unk_token='__unk__', pad_token='__null__', **kwargs)

Initializes a BlenderbotSmallTokenizer instance with the provided parameters.

PARAMETER DESCRIPTION
self

The instance of the BlenderbotSmallTokenizer class.

TYPE: BlenderbotSmallTokenizer

vocab_file

The file path to the vocabulary file containing encoding information.

TYPE: str

merges_file

The file path to the merges file containing BPE merges information.

TYPE: str

bos_token

The beginning of sentence token. Defaults to 'start'.

TYPE: str DEFAULT: '__start__'

eos_token

The end of sentence token. Defaults to 'end'.

TYPE: str DEFAULT: '__end__'

unk_token

The unknown token. Defaults to 'unk'.

TYPE: str DEFAULT: '__unk__'

pad_token

The padding token. Defaults to 'null'.

TYPE: str DEFAULT: '__null__'

**kwargs

Additional keyword arguments.

DEFAULT: {}

RETURNS DESCRIPTION
None

This method initializes the BlenderbotSmallTokenizer instance with the provided parameters.

RAISES DESCRIPTION
FileNotFoundError

If either vocab_file or merges_file is not found.

JSONDecodeError

If there is an issue decoding the vocabulary file.

IndexError

If there is an issue accessing elements during initialization.

Source code in mindnlp/transformers/models/blenderbot_small/tokenization_blenderbot_small.py
 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
def __init__(
    self,
    vocab_file,
    merges_file,
    bos_token="__start__",
    eos_token="__end__",
    unk_token="__unk__",
    pad_token="__null__",
    **kwargs,
):
    """
    Initializes a BlenderbotSmallTokenizer instance with the provided parameters.

    Args:
        self (BlenderbotSmallTokenizer): The instance of the BlenderbotSmallTokenizer class.
        vocab_file (str): The file path to the vocabulary file containing encoding information.
        merges_file (str): The file path to the merges file containing BPE merges information.
        bos_token (str, optional): The beginning of sentence token. Defaults to '__start__'.
        eos_token (str, optional): The end of sentence token. Defaults to '__end__'.
        unk_token (str, optional): The unknown token. Defaults to '__unk__'.
        pad_token (str, optional): The padding token. Defaults to '__null__'.
        **kwargs: Additional keyword arguments.

    Returns:
        None: This method initializes the BlenderbotSmallTokenizer instance with the provided parameters.

    Raises:
        FileNotFoundError: If either vocab_file or merges_file is not found.
        JSONDecodeError: If there is an issue decoding the vocabulary file.
        IndexError: If there is an issue accessing elements during initialization.
    """
    with open(vocab_file, encoding="utf-8") as vocab_handle:
        self.encoder = json.load(vocab_handle)
    self.decoder = {v: k for k, v in self.encoder.items()}
    with open(merges_file, encoding="utf-8") as merges_handle:
        merges = merges_handle.read().split("\n")[1:-1]
    merges = [tuple(merge.split()) for merge in merges]
    self.bpe_ranks = dict(zip(merges, range(len(merges))))
    self.cache = {}
    super().__init__(unk_token=unk_token, bos_token=bos_token, eos_token=eos_token, pad_token=pad_token, **kwargs)

mindnlp.transformers.models.blenderbot_small.tokenization_blenderbot_small.BlenderbotSmallTokenizer.bpe(token)

The 'bpe' method in the 'BlenderbotSmallTokenizer' class performs Byte Pair Encoding (BPE) on a given token.

PARAMETER DESCRIPTION
self

An instance of the BlenderbotSmallTokenizer class.

TYPE: BlenderbotSmallTokenizer

token

The input token to be processed with BPE.

TYPE: str

RETURNS DESCRIPTION
str

The token after BPE processing.

TYPE: str

This method applies the following steps to perform BPE:

  1. Checks if the token exists in the cache. If yes, returns the cached value.
  2. Applies regular expression substitution to separate certain punctuation marks from the token.
  3. Replaces single quotes with spaces around them.
  4. Reduces consecutive whitespace characters to a single space.
  5. If the token contains a newline character, replaces it with 'newln'.
  6. Splits the token into a list of individual words.
  7. Processes each word in the list:

    • Converts the word to lowercase.
    • Converts the word into a tuple.
    • Appends '' to the last character of the tuple.
    • Retrieves the pairs of characters in the word.
    • If no pairs are found, appends the original word to the final list and continues to the next word.
    • Continues to find and merge the most frequent pair of characters in the word until no more relevant pairs are found.
    • Joins the merged characters with '@@ ' and removes the '' suffix.
    • Caches the processed word for future use.
    • Appends the processed word to the final list.
  8. Joins all the words in the final list with a space separator and returns the result.

Source code in mindnlp/transformers/models/blenderbot_small/tokenization_blenderbot_small.py
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
def bpe(self, token: str) -> str:
    """
    The 'bpe' method in the 'BlenderbotSmallTokenizer' class performs Byte Pair Encoding (BPE) on a given token.

    Args:
        self (BlenderbotSmallTokenizer): An instance of the BlenderbotSmallTokenizer class.
        token (str): The input token to be processed with BPE.

    Returns:
        str: The token after BPE processing.

    Raises:
        None.

    This method applies the following steps to perform BPE:

    1. Checks if the token exists in the cache. If yes, returns the cached value.
    2. Applies regular expression substitution to separate certain punctuation marks from the token.
    3. Replaces single quotes with spaces around them.
    4. Reduces consecutive whitespace characters to a single space.
    5. If the token contains a newline character, replaces it with '__newln__'.
    6. Splits the token into a list of individual words.
    7. Processes each word in the list:

        - Converts the word to lowercase.
        - Converts the word into a tuple.
        - Appends '</w>' to the last character of the tuple.
        - Retrieves the pairs of characters in the word.
        - If no pairs are found, appends the original word to the final list and continues to the next word.
        - Continues to find and merge the most frequent pair of characters in the word until no more relevant pairs are found.
        - Joins the merged characters with '@@ ' and removes the '</w>' suffix.
        - Caches the processed word for future use.
        - Appends the processed word to the final list.

    8. Joins all the words in the final list with a space separator and returns the result.
    """
    if token in self.cache:
        return self.cache[token]
    token = re.sub("([.,!?()])", r" \1", token)
    token = re.sub("(')", r" \1 ", token)
    token = re.sub(r"\s{2,}", " ", token)
    if "\n" in token:
        token = token.replace("\n", " __newln__")

    tokens = token.split(" ")
    words = []
    for token in tokens:
        if not len(token): # pylint: disable=use-implicit-booleaness-not-len
            continue

        token = token.lower()
        word = tuple(token)
        word = tuple(list(word[:-1]) + [word[-1] + "</w>"])
        pairs = get_pairs(word)

        if not pairs:
            words.append(token)
            continue

        while True:
            bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
            if bigram not in self.bpe_ranks:
                break
            first, second = bigram
            new_word = []
            i = 0

            while i < len(word):
                try:
                    j = word.index(first, i)
                    new_word.extend(word[i:j])
                    i = j
                except ValueError:
                    new_word.extend(word[i:])
                    break

                if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
                    new_word.append(first + second)
                    i += 2
                else:
                    new_word.append(word[i])
                    i += 1
            new_word = tuple(new_word)
            word = new_word
            if len(word) == 1:
                break
            else:
                pairs = get_pairs(word)
        word = "@@ ".join(word)
        word = word[:-4]

        self.cache[token] = word
        words.append(word)
    return " ".join(words)

mindnlp.transformers.models.blenderbot_small.tokenization_blenderbot_small.BlenderbotSmallTokenizer.convert_tokens_to_string(tokens)

Converts a sequence of tokens in a single string.

Source code in mindnlp/transformers/models/blenderbot_small/tokenization_blenderbot_small.py
266
267
268
269
def convert_tokens_to_string(self, tokens: List[str]) -> str:
    """Converts a sequence of tokens in a single string."""
    out_string = " ".join(tokens).replace("@@ ", "").strip()
    return out_string

mindnlp.transformers.models.blenderbot_small.tokenization_blenderbot_small.BlenderbotSmallTokenizer.get_vocab()

Retrieve the vocabulary of the BlenderbotSmallTokenizer.

PARAMETER DESCRIPTION
self

The instance of the BlenderbotSmallTokenizer class.

TYPE: BlenderbotSmallTokenizer

RETURNS DESCRIPTION
Dict

A dictionary representing the vocabulary of the tokenizer, containing the encoder and added tokens encoder.

TYPE: Dict

Source code in mindnlp/transformers/models/blenderbot_small/tokenization_blenderbot_small.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
def get_vocab(self) -> Dict:
    """
    Retrieve the vocabulary of the BlenderbotSmallTokenizer.

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

    Returns:
        Dict: A dictionary representing the vocabulary of the tokenizer, containing the encoder and added tokens encoder.

    Raises:
        None.
    """
    return dict(self.encoder, **self.added_tokens_encoder)

mindnlp.transformers.models.blenderbot_small.tokenization_blenderbot_small.BlenderbotSmallTokenizer.save_vocabulary(save_directory, filename_prefix=None)

Save the vocabulary and merge files for the BlenderbotSmallTokenizer.

PARAMETER DESCRIPTION
self

An instance of the BlenderbotSmallTokenizer class.

TYPE: BlenderbotSmallTokenizer

save_directory

The directory where the vocabulary and merge files will be saved.

TYPE: str

filename_prefix

A prefix to be added to the filename. Defaults to None.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION
Tuple[str]

Tuple[str]: A tuple containing the paths of the saved vocabulary and merge files.

RAISES DESCRIPTION
FileNotFoundError

If the specified save_directory does not exist.

TypeError

If the save_directory is not of type str.

ValueError

If the save_directory is not a valid directory path.

Source code in mindnlp/transformers/models/blenderbot_small/tokenization_blenderbot_small.py
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
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
    """
    Save the vocabulary and merge files for the BlenderbotSmallTokenizer.

    Args:
        self (BlenderbotSmallTokenizer): An instance of the BlenderbotSmallTokenizer class.
        save_directory (str): The directory where the vocabulary and merge files will be saved.
        filename_prefix (Optional[str], optional): A prefix to be added to the filename. Defaults to None.

    Returns:
        Tuple[str]: A tuple containing the paths of the saved vocabulary and merge files.

    Raises:
        FileNotFoundError: If the specified save_directory does not exist.
        TypeError: If the save_directory is not of type str.
        ValueError: If the save_directory is not a valid directory path.
    """
    if not os.path.isdir(save_directory):
        logger.error(f"Vocabulary path ({save_directory}) should be a directory")
        return
    vocab_file = os.path.join(
        save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
    )
    merge_file = os.path.join(
        save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
    )

    with open(vocab_file, "w", encoding="utf-8") as f:
        f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")

    index = 0
    with open(merge_file, "w", encoding="utf-8") as writer:
        writer.write("#version: 0.2\n")
        for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
            if index != token_index:
                logger.warning(
                    f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
                    " Please check that the tokenizer is not corrupted!"
                )
                index = token_index
            writer.write(" ".join(bpe_tokens) + "\n")
            index += 1

    return vocab_file, merge_file

mindnlp.transformers.models.blenderbot_small.tokenization_blenderbot_small_fast.BlenderbotSmallTokenizerFast

Bases: PreTrainedTokenizerFast

Construct a "fast" BlenderbotSmall tokenizer (backed by HuggingFace's tokenizers library).

PARAMETER DESCRIPTION
vocab_file

Path to the vocabulary file.

TYPE: `str` DEFAULT: None

Source code in mindnlp/transformers/models/blenderbot_small/tokenization_blenderbot_small_fast.py
 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
class BlenderbotSmallTokenizerFast(PreTrainedTokenizerFast):
    """
    Construct a "fast" BlenderbotSmall tokenizer (backed by HuggingFace's *tokenizers* library).

    Args:
        vocab_file (`str`):
            Path to the vocabulary file.
    """
    vocab_files_names = VOCAB_FILES_NAMES
    slow_tokenizer_class = BlenderbotSmallTokenizer

    def __init__(
        self,
        vocab_file=None,
        merges_file=None,
        unk_token="<|endoftext|>",
        bos_token="<|endoftext|>",
        eos_token="<|endoftext|>",
        add_prefix_space=False,
        trim_offsets=True,
        **kwargs,
    ):
        """
        Initializes a BlenderbotSmallTokenizerFast object.

        Args:
            self: The instance of the class.
            vocab_file (str): Path to the vocabulary file. Default is None.
            merges_file (str): Path to the merges file. Default is None.
            unk_token (str): The unknown token. Default is 'endoftext'.
            bos_token (str): The beginning of sentence token. Default is 'endoftext'.
            eos_token (str): The end of sentence token. Default is 'endoftext'.
            add_prefix_space (bool): Whether to add prefix space. Default is False.
            trim_offsets (bool): Whether to trim offsets. Default is True.
            **kwargs: Additional keyword arguments.

        Returns:
            None.

        Raises:
            ValueError: If the vocab_file or merges_file is not provided.
            TypeError: If unk_token, bos_token, eos_token are not strings.
            ValueError: If add_prefix_space or trim_offsets are not boolean values.
        """
        super().__init__(
            ByteLevelBPETokenizer(
                vocab=vocab_file,
                merges=merges_file,
                add_prefix_space=add_prefix_space,
                trim_offsets=trim_offsets,
            ),
            bos_token=bos_token,
            eos_token=eos_token,
            unk_token=unk_token,
            **kwargs,
        )
        self.add_prefix_space = add_prefix_space

    def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
        """
        This method builds inputs with special tokens for the BlenderbotSmallTokenizerFast class.

        Args:
            self: The instance of the class.
            token_ids_0 (list): The token IDs for the first input sequence.
            token_ids_1 (list, optional): The token IDs for the second input sequence. Defaults to None.

        Returns:
            None: The method modifies the input sequences by adding special tokens.

        Raises:
            None.
        """
        output = [self.bos_token_id] + token_ids_0 + [self.eos_token_id]
        if token_ids_1 is None:
            return output

        return output + [self.eos_token_id] + token_ids_1 + [self.eos_token_id]

    def create_token_type_ids_from_sequences(
        self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
    ) -> List[int]:
        """
        Create a mask from the two sequences passed to be used in a sequence-pair classification task. BlenderbotSmall
        does not make use of token type ids, therefore a list of zeros is returned.

        Args:
            token_ids_0 (`List[int]`):
                List of IDs.
            token_ids_1 (`List[int]`, *optional*):
                Optional second list of IDs for sequence pairs.

        Returns:
            `List[int]`: List of zeros.
        """
        sep = [self.sep_token_id]
        cls = [self.cls_token_id]

        if token_ids_1 is None:
            return len(cls + token_ids_0 + sep) * [0]
        return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]

    @property
    # Copied from transformers.models.blenderbot.tokenization_blenderbot.BlenderbotTokenizer.default_chat_template
    def default_chat_template(self):
        """
        A very simple chat template that just adds whitespace between messages.
        """
        logger.warning_once(
            "\nNo chat template is defined for this tokenizer - using the default template "
            f"for the {self.__class__.__name__} class. If the default is not appropriate for "
            "your model, please set `tokenizer.chat_template` to an appropriate template. "
            "See https://huggingface.co/docs/transformers/main/chat_templating for more information.\n"
        )
        return (
            "{% for message in messages %}"
            "{% if message['role'] == 'user' %}{{ ' ' }}{% endif %}"
            "{{ message['content'] }}"
            "{% if not loop.last %}{{ '  ' }}{% endif %}"
            "{% endfor %}"
            "{{ eos_token }}"
        )

mindnlp.transformers.models.blenderbot_small.tokenization_blenderbot_small_fast.BlenderbotSmallTokenizerFast.default_chat_template property

A very simple chat template that just adds whitespace between messages.

mindnlp.transformers.models.blenderbot_small.tokenization_blenderbot_small_fast.BlenderbotSmallTokenizerFast.__init__(vocab_file=None, merges_file=None, unk_token='<|endoftext|>', bos_token='<|endoftext|>', eos_token='<|endoftext|>', add_prefix_space=False, trim_offsets=True, **kwargs)

Initializes a BlenderbotSmallTokenizerFast object.

PARAMETER DESCRIPTION
self

The instance of the class.

vocab_file

Path to the vocabulary file. Default is None.

TYPE: str DEFAULT: None

merges_file

Path to the merges file. Default is None.

TYPE: str DEFAULT: None

unk_token

The unknown token. Default is 'endoftext'.

TYPE: str DEFAULT: '<|endoftext|>'

bos_token

The beginning of sentence token. Default is 'endoftext'.

TYPE: str DEFAULT: '<|endoftext|>'

eos_token

The end of sentence token. Default is 'endoftext'.

TYPE: str DEFAULT: '<|endoftext|>'

add_prefix_space

Whether to add prefix space. Default is False.

TYPE: bool DEFAULT: False

trim_offsets

Whether to trim offsets. Default is True.

TYPE: bool DEFAULT: True

**kwargs

Additional keyword arguments.

DEFAULT: {}

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ValueError

If the vocab_file or merges_file is not provided.

TypeError

If unk_token, bos_token, eos_token are not strings.

ValueError

If add_prefix_space or trim_offsets are not boolean values.

Source code in mindnlp/transformers/models/blenderbot_small/tokenization_blenderbot_small_fast.py
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
def __init__(
    self,
    vocab_file=None,
    merges_file=None,
    unk_token="<|endoftext|>",
    bos_token="<|endoftext|>",
    eos_token="<|endoftext|>",
    add_prefix_space=False,
    trim_offsets=True,
    **kwargs,
):
    """
    Initializes a BlenderbotSmallTokenizerFast object.

    Args:
        self: The instance of the class.
        vocab_file (str): Path to the vocabulary file. Default is None.
        merges_file (str): Path to the merges file. Default is None.
        unk_token (str): The unknown token. Default is 'endoftext'.
        bos_token (str): The beginning of sentence token. Default is 'endoftext'.
        eos_token (str): The end of sentence token. Default is 'endoftext'.
        add_prefix_space (bool): Whether to add prefix space. Default is False.
        trim_offsets (bool): Whether to trim offsets. Default is True.
        **kwargs: Additional keyword arguments.

    Returns:
        None.

    Raises:
        ValueError: If the vocab_file or merges_file is not provided.
        TypeError: If unk_token, bos_token, eos_token are not strings.
        ValueError: If add_prefix_space or trim_offsets are not boolean values.
    """
    super().__init__(
        ByteLevelBPETokenizer(
            vocab=vocab_file,
            merges=merges_file,
            add_prefix_space=add_prefix_space,
            trim_offsets=trim_offsets,
        ),
        bos_token=bos_token,
        eos_token=eos_token,
        unk_token=unk_token,
        **kwargs,
    )
    self.add_prefix_space = add_prefix_space

mindnlp.transformers.models.blenderbot_small.tokenization_blenderbot_small_fast.BlenderbotSmallTokenizerFast.build_inputs_with_special_tokens(token_ids_0, token_ids_1=None)

This method builds inputs with special tokens for the BlenderbotSmallTokenizerFast class.

PARAMETER DESCRIPTION
self

The instance of the class.

token_ids_0

The token IDs for the first input sequence.

TYPE: list

token_ids_1

The token IDs for the second input sequence. Defaults to None.

TYPE: list DEFAULT: None

RETURNS DESCRIPTION
None

The method modifies the input sequences by adding special tokens.

Source code in mindnlp/transformers/models/blenderbot_small/tokenization_blenderbot_small_fast.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
    """
    This method builds inputs with special tokens for the BlenderbotSmallTokenizerFast class.

    Args:
        self: The instance of the class.
        token_ids_0 (list): The token IDs for the first input sequence.
        token_ids_1 (list, optional): The token IDs for the second input sequence. Defaults to None.

    Returns:
        None: The method modifies the input sequences by adding special tokens.

    Raises:
        None.
    """
    output = [self.bos_token_id] + token_ids_0 + [self.eos_token_id]
    if token_ids_1 is None:
        return output

    return output + [self.eos_token_id] + token_ids_1 + [self.eos_token_id]

mindnlp.transformers.models.blenderbot_small.tokenization_blenderbot_small_fast.BlenderbotSmallTokenizerFast.create_token_type_ids_from_sequences(token_ids_0, token_ids_1=None)

Create a mask from the two sequences passed to be used in a sequence-pair classification task. BlenderbotSmall does not make use of token type ids, therefore a list of zeros is returned.

PARAMETER DESCRIPTION
token_ids_0

List of IDs.

TYPE: `List[int]`

token_ids_1

Optional second list of IDs for sequence pairs.

TYPE: `List[int]`, *optional* DEFAULT: None

RETURNS DESCRIPTION
List[int]

List[int]: List of zeros.

Source code in mindnlp/transformers/models/blenderbot_small/tokenization_blenderbot_small_fast.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
def create_token_type_ids_from_sequences(
    self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
    """
    Create a mask from the two sequences passed to be used in a sequence-pair classification task. BlenderbotSmall
    does not make use of token type ids, therefore a list of zeros is returned.

    Args:
        token_ids_0 (`List[int]`):
            List of IDs.
        token_ids_1 (`List[int]`, *optional*):
            Optional second list of IDs for sequence pairs.

    Returns:
        `List[int]`: List of zeros.
    """
    sep = [self.sep_token_id]
    cls = [self.cls_token_id]

    if token_ids_1 is None:
        return len(cls + token_ids_0 + sep) * [0]
    return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]