Skip to content

biogpt

mindnlp.transformers.models.biogpt.configuration_biogpt.BioGptConfig

Bases: PretrainedConfig

This is the configuration class to store the configuration of a [BioGptModel]. It is used to instantiate an BioGPT 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 BioGPT microsoft/biogpt 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 BioGPT model. Defines the number of different tokens that can be represented by the inputs_ids passed when calling [BioGptModel].

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

hidden_size

Dimension of the encoder layers and the pooler layer.

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

num_hidden_layers

Number of hidden layers in the Transformer encoder.

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

num_attention_heads

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

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

intermediate_size

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

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

hidden_act

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

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

hidden_dropout_prob

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_probs_dropout_prob

The dropout ratio for the attention probabilities.

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

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 1024 DEFAULT: 1024

initializer_range

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

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

layer_norm_eps

The epsilon used by the layer normalization layers.

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

scale_embedding

Scale embeddings by diving by sqrt(d_model).

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

use_cache

Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if config.is_decoder=True.

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

layerdrop

Please refer to the paper about LayerDrop: https://arxiv.org/abs/1909.11556 for further details

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

pad_token_id

Padding token id.

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

bos_token_id

Beginning of stream token id.

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

eos_token_id

End of stream token id.

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

Example
>>> from transformers import BioGptModel, BioGptConfig
...
>>> # Initializing a BioGPT microsoft/biogpt style configuration
>>> configuration = BioGptConfig()
...
>>> # Initializing a model from the microsoft/biogpt style configuration
>>> model = BioGptModel(configuration)
...
>>> # Accessing the model configuration
>>> configuration = model.config
Source code in mindnlp/transformers/models/biogpt/configuration_biogpt.py
 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
class BioGptConfig(PretrainedConfig):
    r"""
    This is the configuration class to store the configuration of a [`BioGptModel`]. It is used to instantiate an
    BioGPT 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 BioGPT
    [microsoft/biogpt](https://hf-mirror.com/microsoft/biogpt) 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 42384):
            Vocabulary size of the BioGPT model. Defines the number of different tokens that can be represented by the
            `inputs_ids` passed when calling [`BioGptModel`].
        hidden_size (`int`, *optional*, defaults to 1024):
            Dimension of the encoder layers and the pooler layer.
        num_hidden_layers (`int`, *optional*, defaults to 24):
            Number of hidden layers in the Transformer encoder.
        num_attention_heads (`int`, *optional*, defaults to 16):
            Number of attention heads for each attention layer in the Transformer encoder.
        intermediate_size (`int`, *optional*, defaults to 4096):
            Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
        hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
            The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
            `"relu"`, `"selu"` and `"gelu_new"` are supported.
        hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
            The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
        attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
            The dropout ratio for the attention probabilities.
        max_position_embeddings (`int`, *optional*, defaults to 1024):
            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).
        initializer_range (`float`, *optional*, defaults to 0.02):
            The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
        layer_norm_eps (`float`, *optional*, defaults to 1e-12):
            The epsilon used by the layer normalization layers.
        scale_embedding (`bool`, *optional*, defaults to `True`):
            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). Only
            relevant if `config.is_decoder=True`.
        layerdrop (`float`, *optional*, defaults to 0.0):
            Please refer to the paper about LayerDrop: https://arxiv.org/abs/1909.11556 for further details
        activation_dropout (`float`, *optional*, defaults to 0.0):
            The dropout ratio for activations inside the fully connected layer.
        pad_token_id (`int`, *optional*, defaults to 1):
            Padding token id.
        bos_token_id (`int`, *optional*, defaults to 0):
            Beginning of stream token id.
        eos_token_id (`int`, *optional*, defaults to 2):
            End of stream token id.

    Example:
        ```python
        >>> from transformers import BioGptModel, BioGptConfig
        ...
        >>> # Initializing a BioGPT microsoft/biogpt style configuration
        >>> configuration = BioGptConfig()
        ...
        >>> # Initializing a model from the microsoft/biogpt style configuration
        >>> model = BioGptModel(configuration)
        ...
        >>> # Accessing the model configuration
        >>> configuration = model.config
        ```
    """
    model_type = "biogpt"

    def __init__(
        self,
        vocab_size=42384,
        hidden_size=1024,
        num_hidden_layers=24,
        num_attention_heads=16,
        intermediate_size=4096,
        hidden_act="gelu",
        hidden_dropout_prob=0.1,
        attention_probs_dropout_prob=0.1,
        max_position_embeddings=1024,
        initializer_range=0.02,
        layer_norm_eps=1e-12,
        scale_embedding=True,
        use_cache=True,
        layerdrop=0.0,
        activation_dropout=0.0,
        pad_token_id=1,
        bos_token_id=0,
        eos_token_id=2,
        **kwargs,
    ):
        """
        Initializes a new instance of the BioGptConfig class.

        Args:
            self: The instance of the class.
            vocab_size (int): The size of the vocabulary. Defaults to 42384.
            hidden_size (int): The size of the hidden layers. Defaults to 1024.
            num_hidden_layers (int): The number of hidden layers. Defaults to 24.
            num_attention_heads (int): The number of attention heads. Defaults to 16.
            intermediate_size (int): The size of the intermediate layers. Defaults to 4096.
            hidden_act (str): The activation function for the hidden layers. Defaults to 'gelu'.
            hidden_dropout_prob (float): The dropout probability for the hidden layers. Defaults to 0.1.
            attention_probs_dropout_prob (float): The dropout probability for the attention probabilities. Defaults to 0.1.
            max_position_embeddings (int): The maximum number of position embeddings. Defaults to 1024.
            initializer_range (float): The range for the initializer. Defaults to 0.02.
            layer_norm_eps (float): The epsilon value for layer normalization. Defaults to 1e-12.
            scale_embedding (bool): Whether to scale the embedding. Defaults to True.
            use_cache (bool): Whether to use caching. Defaults to True.
            layerdrop (float): The probability of dropping a layer. Defaults to 0.0.
            activation_dropout (float): The dropout probability for the activation. Defaults to 0.0.
            pad_token_id (int): The id of the padding token. Defaults to 1.
            bos_token_id (int): The id of the beginning-of-sentence token. Defaults to 0.
            eos_token_id (int): The id of the end-of-sentence token. Defaults to 2.

        Returns:
            None.

        Raises:
            None.
        """
        self.vocab_size = vocab_size
        self.max_position_embeddings = max_position_embeddings
        self.hidden_size = hidden_size
        self.num_hidden_layers = num_hidden_layers
        self.num_attention_heads = num_attention_heads
        self.intermediate_size = intermediate_size
        self.hidden_act = hidden_act
        self.hidden_dropout_prob = hidden_dropout_prob
        self.attention_probs_dropout_prob = attention_probs_dropout_prob
        self.initializer_range = initializer_range
        self.layer_norm_eps = layer_norm_eps
        self.scale_embedding = scale_embedding
        self.use_cache = use_cache
        self.layerdrop = layerdrop
        self.activation_dropout = activation_dropout
        super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)

mindnlp.transformers.models.biogpt.configuration_biogpt.BioGptConfig.__init__(vocab_size=42384, hidden_size=1024, num_hidden_layers=24, num_attention_heads=16, intermediate_size=4096, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=1024, initializer_range=0.02, layer_norm_eps=1e-12, scale_embedding=True, use_cache=True, layerdrop=0.0, activation_dropout=0.0, pad_token_id=1, bos_token_id=0, eos_token_id=2, **kwargs)

Initializes a new instance of the BioGptConfig class.

PARAMETER DESCRIPTION
self

The instance of the class.

vocab_size

The size of the vocabulary. Defaults to 42384.

TYPE: int DEFAULT: 42384

hidden_size

The size of the hidden layers. Defaults to 1024.

TYPE: int DEFAULT: 1024

num_hidden_layers

The number of hidden layers. Defaults to 24.

TYPE: int DEFAULT: 24

num_attention_heads

The number of attention heads. Defaults to 16.

TYPE: int DEFAULT: 16

intermediate_size

The size of the intermediate layers. Defaults to 4096.

TYPE: int DEFAULT: 4096

hidden_act

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

TYPE: str DEFAULT: 'gelu'

hidden_dropout_prob

The dropout probability for the hidden layers. Defaults to 0.1.

TYPE: float DEFAULT: 0.1

attention_probs_dropout_prob

The dropout probability for the attention probabilities. Defaults to 0.1.

TYPE: float DEFAULT: 0.1

max_position_embeddings

The maximum number of position embeddings. Defaults to 1024.

TYPE: int DEFAULT: 1024

initializer_range

The range for the initializer. Defaults to 0.02.

TYPE: float DEFAULT: 0.02

layer_norm_eps

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

TYPE: float DEFAULT: 1e-12

scale_embedding

Whether to scale the embedding. Defaults to True.

TYPE: bool DEFAULT: True

use_cache

Whether to use caching. Defaults to True.

TYPE: bool DEFAULT: True

layerdrop

The probability of dropping a layer. Defaults to 0.0.

TYPE: float DEFAULT: 0.0

activation_dropout

The dropout probability for the activation. Defaults to 0.0.

TYPE: float DEFAULT: 0.0

pad_token_id

The id of the padding token. Defaults to 1.

TYPE: int DEFAULT: 1

bos_token_id

The id of the beginning-of-sentence token. Defaults to 0.

TYPE: int DEFAULT: 0

eos_token_id

The id of the end-of-sentence token. Defaults to 2.

TYPE: int DEFAULT: 2

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/biogpt/configuration_biogpt.py
 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
def __init__(
    self,
    vocab_size=42384,
    hidden_size=1024,
    num_hidden_layers=24,
    num_attention_heads=16,
    intermediate_size=4096,
    hidden_act="gelu",
    hidden_dropout_prob=0.1,
    attention_probs_dropout_prob=0.1,
    max_position_embeddings=1024,
    initializer_range=0.02,
    layer_norm_eps=1e-12,
    scale_embedding=True,
    use_cache=True,
    layerdrop=0.0,
    activation_dropout=0.0,
    pad_token_id=1,
    bos_token_id=0,
    eos_token_id=2,
    **kwargs,
):
    """
    Initializes a new instance of the BioGptConfig class.

    Args:
        self: The instance of the class.
        vocab_size (int): The size of the vocabulary. Defaults to 42384.
        hidden_size (int): The size of the hidden layers. Defaults to 1024.
        num_hidden_layers (int): The number of hidden layers. Defaults to 24.
        num_attention_heads (int): The number of attention heads. Defaults to 16.
        intermediate_size (int): The size of the intermediate layers. Defaults to 4096.
        hidden_act (str): The activation function for the hidden layers. Defaults to 'gelu'.
        hidden_dropout_prob (float): The dropout probability for the hidden layers. Defaults to 0.1.
        attention_probs_dropout_prob (float): The dropout probability for the attention probabilities. Defaults to 0.1.
        max_position_embeddings (int): The maximum number of position embeddings. Defaults to 1024.
        initializer_range (float): The range for the initializer. Defaults to 0.02.
        layer_norm_eps (float): The epsilon value for layer normalization. Defaults to 1e-12.
        scale_embedding (bool): Whether to scale the embedding. Defaults to True.
        use_cache (bool): Whether to use caching. Defaults to True.
        layerdrop (float): The probability of dropping a layer. Defaults to 0.0.
        activation_dropout (float): The dropout probability for the activation. Defaults to 0.0.
        pad_token_id (int): The id of the padding token. Defaults to 1.
        bos_token_id (int): The id of the beginning-of-sentence token. Defaults to 0.
        eos_token_id (int): The id of the end-of-sentence token. Defaults to 2.

    Returns:
        None.

    Raises:
        None.
    """
    self.vocab_size = vocab_size
    self.max_position_embeddings = max_position_embeddings
    self.hidden_size = hidden_size
    self.num_hidden_layers = num_hidden_layers
    self.num_attention_heads = num_attention_heads
    self.intermediate_size = intermediate_size
    self.hidden_act = hidden_act
    self.hidden_dropout_prob = hidden_dropout_prob
    self.attention_probs_dropout_prob = attention_probs_dropout_prob
    self.initializer_range = initializer_range
    self.layer_norm_eps = layer_norm_eps
    self.scale_embedding = scale_embedding
    self.use_cache = use_cache
    self.layerdrop = layerdrop
    self.activation_dropout = activation_dropout
    super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)

mindnlp.transformers.models.biogpt.modeling_biogpt.BIOGPT_PRETRAINED_MODEL_ARCHIVE_LIST = ['microsoft/biogpt', 'microsoft/BioGPT-Large'] module-attribute

mindnlp.transformers.models.biogpt.modeling_biogpt.BioGptForCausalLM

Bases: BioGptPreTrainedModel

BioGptForCausalLM represents a BioGpt model for Causal Language Modeling. This class inherits from BioGptPreTrainedModel and provides methods for initializing the model, forwarding the model, and preparing inputs for generation.

ATTRIBUTE DESCRIPTION
config

The configuration for the BioGptForCausalLM model.

METHOD DESCRIPTION
__init__

Initializes the BioGptForCausalLM model with the given configuration.

get_output_embeddings

Returns the output projection layer for the model.

set_output_embeddings

Sets the output projection layer to the new embeddings.

prepare_inputs_for_generation

Prepares the inputs for generation based on the given parameters.

_reorder_cache

Reorders the past key values based on the given beam index.

Note

Labels for language modeling are shifted inside the model, and the loss is only computed for valid labels within the vocabulary size.

Source code in mindnlp/transformers/models/biogpt/modeling_biogpt.py
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
class BioGptForCausalLM(BioGptPreTrainedModel):

    """
    BioGptForCausalLM represents a BioGpt model for Causal Language Modeling.
    This class inherits from BioGptPreTrainedModel and provides methods for initializing the model,
    forwarding the model, and preparing inputs for generation.

    Attributes:
        config: The configuration for the BioGptForCausalLM model.

    Methods:
        __init__(config): Initializes the BioGptForCausalLM model with the given configuration.
        get_output_embeddings(): Returns the output projection layer for the model.
        set_output_embeddings(new_embeddings): Sets the output projection layer to the new embeddings.
        forward(input_ids, attention_mask, head_mask, inputs_embeds, past_key_values, labels, use_cache,
            output_attentions, output_hidden_states, return_dict):
            Constructs the BioGptForCausalLM model with the given input parameters and returns the model output.
        prepare_inputs_for_generation(input_ids, attention_mask, inputs_embeds, past_key_values, **kwargs):
            Prepares the inputs for generation based on the given parameters.
        _reorder_cache(past_key_values, beam_idx): Reorders the past key values based on the given beam index.

    Note:
        Labels for language modeling are shifted inside the model,
        and the loss is only computed for valid labels within the vocabulary size.
    """
    _tied_weights_keys = ["output_projection.weight"]

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

        Args:
            self: The instance of the BioGptForCausalLM class.
            config: An object containing configuration settings for the model.

        Returns:
            None.

        Raises:
            TypeError: If the config parameter is not provided or is not of the expected type.
            ValueError: If the config parameter does not contain the required settings for initializing the model.
        """
        super().__init__(config)

        self.biogpt = BioGptModel(config)
        self.output_projection = nn.Linear(config.hidden_size, config.vocab_size, bias=False)

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

    def get_output_embeddings(self):
        """
        This method retrieves the output embeddings from the BioGptForCausalLM model.

        Args:
            self: An instance of the BioGptForCausalLM class.

        Returns:
            None: This method returns the output projection of the model as a value of type 'None'.

        Raises:
            None.
        """
        return self.output_projection

    def set_output_embeddings(self, new_embeddings):
        """
        Method to set new output embeddings for the BioGptForCausalLM model.

        Args:
            self (BioGptForCausalLM): The instance of the BioGptForCausalLM class.
                This parameter is automatically passed and refers to the current instance.
            new_embeddings (object): New embeddings to be set as the output projections.
                This parameter should be an object representing the new embeddings to be used.

        Returns:
            None.

        Raises:
            None.
        """
        self.output_projection = new_embeddings

    def forward(
        self,
        input_ids: Optional[mindspore.Tensor] = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        head_mask: Optional[mindspore.Tensor] = None,
        inputs_embeds: Optional[mindspore.Tensor] = None,
        past_key_values: Optional[Tuple[Tuple[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:
            labels (`mindspore.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
                `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
                are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
        """
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        outputs = self.biogpt(
            input_ids,
            attention_mask=attention_mask,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
            past_key_values=past_key_values,
            use_cache=use_cache,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )

        sequence_output = outputs[0]
        prediction_scores = self.output_projection(sequence_output)

        lm_loss = None
        if labels is not None:
            # we are doing next-token prediction; shift prediction scores and input ids by one
            shifted_prediction_scores = prediction_scores[:, :-1, :]
            labels = labels[:, 1:]
            lm_loss = F.cross_entropy(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))

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

        return CausalLMOutputWithCrossAttentions(
            loss=lm_loss,
            logits=prediction_scores,
            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, attention_mask, inputs_embeds=None, past_key_values=None, **kwargs
    ):
        '''
        This method prepares inputs for generation in the BioGptForCausalLM class.

        Args:
            self (object): The instance of the class.
            input_ids (torch.Tensor): The input tensor containing the tokenized input IDs.
            attention_mask (torch.Tensor): The tensor containing the attention mask to avoid attending to padding tokens.
            inputs_embeds (torch.Tensor, optional): The tensor containing the embeddings for the input tokens. Defaults to None.
            past_key_values (tuple, optional): The tuple containing past key values for fast decoding. Defaults to None.

        Returns:
            dict: A dictionary containing the model inputs,
                including 'input_ids', 'attention_mask', 'past_key_values', and 'use_cache' (if provided).
                Returns None if past_key_values is provided and the input_ids shape is greater than the past_length.

        Raises:
            ValueError: If the input_ids shape is less than or equal to zero.
            TypeError: If the input_ids, attention_mask, or inputs_embeds are not of type torch.Tensor.
            IndexError: If the past_key_values tuple does not have the expected shape.
        '''
        # only last tokens for inputs_ids if past is defined in kwargs
        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 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:]

        if inputs_embeds is not None and past_key_values is None:
            model_inputs = {"inputs_embeds": inputs_embeds}
        else:
            model_inputs = {"input_ids": input_ids}

        model_inputs.update(
            {
                "attention_mask": attention_mask,
                "past_key_values": past_key_values,
                "use_cache": kwargs.get("use_cache"),
            }
        )

        return model_inputs

    @staticmethod
    def _reorder_cache(past_key_values, beam_idx):
        """
        Reorders the cache of past key values based on the given beam index.

        Args:
            past_key_values (tuple): A tuple containing the past key values for each layer.
                Each element in the tuple is a tensor representing the past states for the corresponding layer.
            beam_idx (tensor): A tensor containing the indices of the beams to reorder the past key values.

        Returns:
            None: This method does not return any value, as it 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.biogpt.modeling_biogpt.BioGptForCausalLM.__init__(config)

Initializes a new instance of the BioGptForCausalLM class.

PARAMETER DESCRIPTION
self

The instance of the BioGptForCausalLM class.

config

An object containing configuration settings for the model.

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the config parameter is not provided or is not of the expected type.

ValueError

If the config parameter does not contain the required settings for initializing the model.

Source code in mindnlp/transformers/models/biogpt/modeling_biogpt.py
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
def __init__(self, config):
    """
    Initializes a new instance of the BioGptForCausalLM class.

    Args:
        self: The instance of the BioGptForCausalLM class.
        config: An object containing configuration settings for the model.

    Returns:
        None.

    Raises:
        TypeError: If the config parameter is not provided or is not of the expected type.
        ValueError: If the config parameter does not contain the required settings for initializing the model.
    """
    super().__init__(config)

    self.biogpt = BioGptModel(config)
    self.output_projection = nn.Linear(config.hidden_size, config.vocab_size, bias=False)

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

mindnlp.transformers.models.biogpt.modeling_biogpt.BioGptForCausalLM.forward(input_ids=None, attention_mask=None, head_mask=None, inputs_embeds=None, past_key_values=None, labels=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None)

PARAMETER DESCRIPTION
labels

Labels for language modeling. Note that the labels are shifted inside the model, i.e. you can set labels = input_ids Indices are selected in [-100, 0, ..., config.vocab_size] All labels set to -100 are ignored (masked), the loss is only computed for labels in [0, ..., config.vocab_size]

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

Source code in mindnlp/transformers/models/biogpt/modeling_biogpt.py
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
def forward(
    self,
    input_ids: Optional[mindspore.Tensor] = None,
    attention_mask: Optional[mindspore.Tensor] = None,
    head_mask: Optional[mindspore.Tensor] = None,
    inputs_embeds: Optional[mindspore.Tensor] = None,
    past_key_values: Optional[Tuple[Tuple[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:
        labels (`mindspore.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
            `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
            are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
    """
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict

    outputs = self.biogpt(
        input_ids,
        attention_mask=attention_mask,
        head_mask=head_mask,
        inputs_embeds=inputs_embeds,
        past_key_values=past_key_values,
        use_cache=use_cache,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )

    sequence_output = outputs[0]
    prediction_scores = self.output_projection(sequence_output)

    lm_loss = None
    if labels is not None:
        # we are doing next-token prediction; shift prediction scores and input ids by one
        shifted_prediction_scores = prediction_scores[:, :-1, :]
        labels = labels[:, 1:]
        lm_loss = F.cross_entropy(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))

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

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

mindnlp.transformers.models.biogpt.modeling_biogpt.BioGptForCausalLM.get_output_embeddings()

This method retrieves the output embeddings from the BioGptForCausalLM model.

PARAMETER DESCRIPTION
self

An instance of the BioGptForCausalLM class.

RETURNS DESCRIPTION
None

This method returns the output projection of the model as a value of type 'None'.

Source code in mindnlp/transformers/models/biogpt/modeling_biogpt.py
738
739
740
741
742
743
744
745
746
747
748
749
750
751
def get_output_embeddings(self):
    """
    This method retrieves the output embeddings from the BioGptForCausalLM model.

    Args:
        self: An instance of the BioGptForCausalLM class.

    Returns:
        None: This method returns the output projection of the model as a value of type 'None'.

    Raises:
        None.
    """
    return self.output_projection

mindnlp.transformers.models.biogpt.modeling_biogpt.BioGptForCausalLM.prepare_inputs_for_generation(input_ids, attention_mask, inputs_embeds=None, past_key_values=None, **kwargs)

This method prepares inputs for generation in the BioGptForCausalLM class.

PARAMETER DESCRIPTION
self

The instance of the class.

TYPE: object

input_ids

The input tensor containing the tokenized input IDs.

TYPE: Tensor

attention_mask

The tensor containing the attention mask to avoid attending to padding tokens.

TYPE: Tensor

inputs_embeds

The tensor containing the embeddings for the input tokens. Defaults to None.

TYPE: Tensor DEFAULT: None

past_key_values

The tuple containing past key values for fast decoding. Defaults to None.

TYPE: tuple DEFAULT: None

RETURNS DESCRIPTION
dict

A dictionary containing the model inputs, including 'input_ids', 'attention_mask', 'past_key_values', and 'use_cache' (if provided). Returns None if past_key_values is provided and the input_ids shape is greater than the past_length.

RAISES DESCRIPTION
ValueError

If the input_ids shape is less than or equal to zero.

TypeError

If the input_ids, attention_mask, or inputs_embeds are not of type torch.Tensor.

IndexError

If the past_key_values tuple does not have the expected shape.

Source code in mindnlp/transformers/models/biogpt/modeling_biogpt.py
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
def prepare_inputs_for_generation(
    self, input_ids, attention_mask, inputs_embeds=None, past_key_values=None, **kwargs
):
    '''
    This method prepares inputs for generation in the BioGptForCausalLM class.

    Args:
        self (object): The instance of the class.
        input_ids (torch.Tensor): The input tensor containing the tokenized input IDs.
        attention_mask (torch.Tensor): The tensor containing the attention mask to avoid attending to padding tokens.
        inputs_embeds (torch.Tensor, optional): The tensor containing the embeddings for the input tokens. Defaults to None.
        past_key_values (tuple, optional): The tuple containing past key values for fast decoding. Defaults to None.

    Returns:
        dict: A dictionary containing the model inputs,
            including 'input_ids', 'attention_mask', 'past_key_values', and 'use_cache' (if provided).
            Returns None if past_key_values is provided and the input_ids shape is greater than the past_length.

    Raises:
        ValueError: If the input_ids shape is less than or equal to zero.
        TypeError: If the input_ids, attention_mask, or inputs_embeds are not of type torch.Tensor.
        IndexError: If the past_key_values tuple does not have the expected shape.
    '''
    # only last tokens for inputs_ids if past is defined in kwargs
    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 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:]

    if inputs_embeds is not None and past_key_values is None:
        model_inputs = {"inputs_embeds": inputs_embeds}
    else:
        model_inputs = {"input_ids": input_ids}

    model_inputs.update(
        {
            "attention_mask": attention_mask,
            "past_key_values": past_key_values,
            "use_cache": kwargs.get("use_cache"),
        }
    )

    return model_inputs

mindnlp.transformers.models.biogpt.modeling_biogpt.BioGptForCausalLM.set_output_embeddings(new_embeddings)

Method to set new output embeddings for the BioGptForCausalLM model.

PARAMETER DESCRIPTION
self

The instance of the BioGptForCausalLM class. This parameter is automatically passed and refers to the current instance.

TYPE: BioGptForCausalLM

new_embeddings

New embeddings to be set as the output projections. This parameter should be an object representing the new embeddings to be used.

TYPE: object

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/biogpt/modeling_biogpt.py
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
def set_output_embeddings(self, new_embeddings):
    """
    Method to set new output embeddings for the BioGptForCausalLM model.

    Args:
        self (BioGptForCausalLM): The instance of the BioGptForCausalLM class.
            This parameter is automatically passed and refers to the current instance.
        new_embeddings (object): New embeddings to be set as the output projections.
            This parameter should be an object representing the new embeddings to be used.

    Returns:
        None.

    Raises:
        None.
    """
    self.output_projection = new_embeddings

mindnlp.transformers.models.biogpt.modeling_biogpt.BioGptForTokenClassification

Bases: BioGptPreTrainedModel

This class represents a BioGpt model for token classification, inheriting from BioGptPreTrainedModel. It includes methods for initializing the model and forwarding token classification outputs based on input data. The model utilizes a transformer architecture for processing input sequences and generating classification predictions. The class provides functionality for computing loss based on predicted logits and actual labels, as well as handling optional parameters for caching, attention masks, and return dictionary configurations.

Source code in mindnlp/transformers/models/biogpt/modeling_biogpt.py
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
class BioGptForTokenClassification(BioGptPreTrainedModel):

    """
    This class represents a BioGpt model for token classification, inheriting from BioGptPreTrainedModel.
    It includes methods for initializing the model and forwarding token classification outputs based on input data.
    The model utilizes a transformer architecture for processing input sequences and generating classification predictions.
    The class provides functionality for computing loss based on predicted logits and actual labels, as well as
    handling optional parameters for caching, attention masks, and return dictionary configurations.
    """
    def __init__(self, config):
        """
        Initializes an instance of the BioGptForTokenClassification class.

        Args:
            self: The instance of the BioGptForTokenClassification class.
            config:
                An object containing configuration parameters for the model.

                - Type: object
                - Purpose: Configuration object that specifies model settings.
                - Restrictions: Must contain at least the 'num_labels' attribute.

        Returns:
            None

        Raises:
            TypeError: If the 'config' parameter is not provided or is invalid.
            AttributeError: If the 'config' object does not have the required 'num_labels' attribute.
            ValueError: If the 'classifier_dropout' or 'hidden_dropout_prob' attributes are invalid in the 'config' object.
        """
        super().__init__(config)
        self.num_labels = config.num_labels

        self.biogpt = BioGptModel(config)
        if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
            classifier_dropout = config.classifier_dropout
        else:
            classifier_dropout = config.hidden_dropout_prob
        self.dropout = nn.Dropout(p=classifier_dropout)
        self.classifier = nn.Linear(config.hidden_size, config.num_labels)

        self.post_init()

    def forward(
        self,
        input_ids: Optional[mindspore.Tensor] = None,
        token_type_ids: Optional[mindspore.Tensor] = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        head_mask: Optional[mindspore.Tensor] = None,
        past_key_values: Optional[Tuple[Tuple[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, TokenClassifierOutput]:
        r"""
        Args:
            labels (`mindspore.Tensor` of shape `(batch_size,)`, *optional*):
                Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
                config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
                `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        """
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        transformer_outputs = self.biogpt(
            input_ids,
            past_key_values=past_key_values,
            attention_mask=attention_mask,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
            use_cache=use_cache,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )

        hidden_states = transformer_outputs[0]
        hidden_states = self.dropout(hidden_states)
        logits = self.classifier(hidden_states)

        loss = None
        if labels is not None:
            # Only keep active parts of the loss
            if attention_mask is not None:
                active_loss = attention_mask.view(-1) == 1
                active_logits = logits.view(-1, self.num_labels)
                active_labels = ops.where(
                    active_loss, labels.view(-1), mindspore.tensor(-100).type_as(labels)
                )
                loss = F.cross_entropy(active_logits, active_labels)
            else:
                loss = F.cross_entropy(logits.view(-1, self.num_labels), labels.view(-1))

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

        return TokenClassifierOutput(
            loss=loss,
            logits=logits,
            hidden_states=transformer_outputs.hidden_states,
            attentions=transformer_outputs.attentions,
        )

mindnlp.transformers.models.biogpt.modeling_biogpt.BioGptForTokenClassification.__init__(config)

Initializes an instance of the BioGptForTokenClassification class.

PARAMETER DESCRIPTION
self

The instance of the BioGptForTokenClassification class.

config

An object containing configuration parameters for the model.

  • Type: object
  • Purpose: Configuration object that specifies model settings.
  • Restrictions: Must contain at least the 'num_labels' attribute.

RETURNS DESCRIPTION

None

RAISES DESCRIPTION
TypeError

If the 'config' parameter is not provided or is invalid.

AttributeError

If the 'config' object does not have the required 'num_labels' attribute.

ValueError

If the 'classifier_dropout' or 'hidden_dropout_prob' attributes are invalid in the 'config' object.

Source code in mindnlp/transformers/models/biogpt/modeling_biogpt.py
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
def __init__(self, config):
    """
    Initializes an instance of the BioGptForTokenClassification class.

    Args:
        self: The instance of the BioGptForTokenClassification class.
        config:
            An object containing configuration parameters for the model.

            - Type: object
            - Purpose: Configuration object that specifies model settings.
            - Restrictions: Must contain at least the 'num_labels' attribute.

    Returns:
        None

    Raises:
        TypeError: If the 'config' parameter is not provided or is invalid.
        AttributeError: If the 'config' object does not have the required 'num_labels' attribute.
        ValueError: If the 'classifier_dropout' or 'hidden_dropout_prob' attributes are invalid in the 'config' object.
    """
    super().__init__(config)
    self.num_labels = config.num_labels

    self.biogpt = BioGptModel(config)
    if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
        classifier_dropout = config.classifier_dropout
    else:
        classifier_dropout = config.hidden_dropout_prob
    self.dropout = nn.Dropout(p=classifier_dropout)
    self.classifier = nn.Linear(config.hidden_size, config.num_labels)

    self.post_init()

mindnlp.transformers.models.biogpt.modeling_biogpt.BioGptForTokenClassification.forward(input_ids=None, token_type_ids=None, attention_mask=None, 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
labels

Labels for computing the sequence classification/regression loss. Indices should be in [0, ..., config.num_labels - 1]. If config.num_labels == 1 a regression loss is computed (Mean-Square loss), If config.num_labels > 1 a classification loss is computed (Cross-Entropy).

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

Source code in mindnlp/transformers/models/biogpt/modeling_biogpt.py
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
def forward(
    self,
    input_ids: Optional[mindspore.Tensor] = None,
    token_type_ids: Optional[mindspore.Tensor] = None,
    attention_mask: Optional[mindspore.Tensor] = None,
    head_mask: Optional[mindspore.Tensor] = None,
    past_key_values: Optional[Tuple[Tuple[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, TokenClassifierOutput]:
    r"""
    Args:
        labels (`mindspore.Tensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
    """
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict

    transformer_outputs = self.biogpt(
        input_ids,
        past_key_values=past_key_values,
        attention_mask=attention_mask,
        head_mask=head_mask,
        inputs_embeds=inputs_embeds,
        use_cache=use_cache,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )

    hidden_states = transformer_outputs[0]
    hidden_states = self.dropout(hidden_states)
    logits = self.classifier(hidden_states)

    loss = None
    if labels is not None:
        # Only keep active parts of the loss
        if attention_mask is not None:
            active_loss = attention_mask.view(-1) == 1
            active_logits = logits.view(-1, self.num_labels)
            active_labels = ops.where(
                active_loss, labels.view(-1), mindspore.tensor(-100).type_as(labels)
            )
            loss = F.cross_entropy(active_logits, active_labels)
        else:
            loss = F.cross_entropy(logits.view(-1, self.num_labels), labels.view(-1))

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

    return TokenClassifierOutput(
        loss=loss,
        logits=logits,
        hidden_states=transformer_outputs.hidden_states,
        attentions=transformer_outputs.attentions,
    )

mindnlp.transformers.models.biogpt.modeling_biogpt.BioGptForSequenceClassification

Bases: BioGptPreTrainedModel

This class represents a BioGpt model for sequence classification tasks. It inherits from the BioGptPreTrainedModel and includes methods for initialization, forwarding the model, getting input embeddings, and setting input embeddings.

The init method initializes the BioGptForSequenceClassification instance with a BioGptConfig and sets the number of labels, BioGptModel, and score.

The forward method takes input tensors for the model and returns the sequence classifier output with past key values. It also handles labels for computing the sequence classification/regression loss and handles different problem types such as regression, single-label classification, and multi-label classification.

The get_input_embeddings method returns the input embeddings of the BioGpt model.

The set_input_embeddings method sets the input embeddings of the BioGpt model.

Note

The class inherits from BioGptPreTrainedModel and includes additional methods not provided in the given code snippet.

Source code in mindnlp/transformers/models/biogpt/modeling_biogpt.py
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
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
class BioGptForSequenceClassification(BioGptPreTrainedModel):

    '''
    This class represents a BioGpt model for sequence classification tasks.
    It inherits from the BioGptPreTrainedModel and includes methods for initialization,
    forwarding the model, getting input embeddings, and setting input embeddings.

    The __init__ method initializes the BioGptForSequenceClassification instance with a BioGptConfig
    and sets the number of labels, BioGptModel, and score.

    The forward method takes input tensors for the model and returns the sequence classifier output with past key values.
    It also handles labels for computing the sequence classification/regression loss and handles different problem types
    such as regression, single-label classification, and multi-label classification.

    The get_input_embeddings method returns the input embeddings of the BioGpt model.

    The set_input_embeddings method sets the input embeddings of the BioGpt model.

    Note:
        The class inherits from BioGptPreTrainedModel and includes additional methods not provided in the given code snippet.
    '''
    def __init__(self, config: BioGptConfig):
        """
        Initializes a BioGptForSequenceClassification instance.

        Args:
            self: The instance of the BioGptForSequenceClassification class.
            config (BioGptConfig): An instance of BioGptConfig containing configuration settings for the model.
                This parameter is required for initializing the BioGptForSequenceClassification instance.
                It specifies the configuration details such as the number of labels and hidden size.

        Returns:
            None.

        Raises:
            TypeError: If the config parameter is not of type BioGptConfig.
            ValueError: If the num_labels attribute is not present in the config parameter.
            ValueError: If an error occurs during the initialization of the BioGptModel or Dense layers.
        """
        super().__init__(config)
        self.num_labels = config.num_labels
        self.biogpt = BioGptModel(config)
        self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)

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

    def forward(
        self,
        input_ids: Optional[mindspore.Tensor] = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        head_mask: Optional[mindspore.Tensor] = None,
        past_key_values: Optional[Tuple[Tuple[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, SequenceClassifierOutputWithPast]:
        r"""
        Args:
            labels (`mindspore.Tensor` of shape `(batch_size,)`, *optional*):
                Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
                config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
                `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        """
        return_dict = return_dict if return_dict is not None else self.config.use_return_dict

        transformer_outputs = self.biogpt(
            input_ids,
            past_key_values=past_key_values,
            attention_mask=attention_mask,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
            use_cache=use_cache,
            output_attentions=output_attentions,
            output_hidden_states=output_hidden_states,
            return_dict=return_dict,
        )
        hidden_states = transformer_outputs[0]
        logits = self.score(hidden_states)

        if input_ids is not None:
            batch_size, sequence_length = input_ids.shape[:2]
        else:
            batch_size, sequence_length = inputs_embeds.shape[:2]

        if self.config.pad_token_id is None:
            sequence_length = -1
        else:
            if input_ids is not None:
                sequence_length = ops.ne(input_ids, self.config.pad_token_id).sum(-1) - 1
            else:
                sequence_length = -1
                logger.warning(
                    f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
                    "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
                )

        pooled_logits = logits[ops.arange(batch_size), sequence_length]

        loss = None
        if labels is not None:
            if self.config.problem_type is None:
                if self.num_labels == 1:
                    self.config.problem_type = "regression"
                elif self.num_labels > 1 and labels.dtype in (mindspore.int64, mindspore.int32):
                    self.config.problem_type = "single_label_classification"
                else:
                    self.config.problem_type = "multi_label_classification"

            if self.config.problem_type == "regression":
                if self.num_labels == 1:
                    loss = F.mse_loss(pooled_logits.squeeze(), labels.squeeze())
                else:
                    loss = F.mse_loss(pooled_logits, labels)
            elif self.config.problem_type == "single_label_classification":
                loss = F.cross_entropy(pooled_logits.view(-1, self.num_labels), labels.view(-1))
            elif self.config.problem_type == "multi_label_classification":
                loss = F.binary_cross_entropy_with_logits(pooled_logits, labels)
        if not return_dict:
            output = (pooled_logits,) + transformer_outputs[1:]
            return ((loss,) + output) if loss is not None else output

        return SequenceClassifierOutputWithPast(
            loss=loss,
            logits=pooled_logits,
            past_key_values=transformer_outputs.past_key_values,
            hidden_states=transformer_outputs.hidden_states,
            attentions=transformer_outputs.attentions,
        )

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

        Args:
            self (BioGptForSequenceClassification): The instance of the BioGptForSequenceClassification class.
                Represents the object itself.

        Returns:
            None: This method returns the embeddings obtained from the BioGpt model.

        Raises:
            None.
        """
        return self.biogpt.embed_tokens

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

        Args:
            self (BioGptForSequenceClassification): The instance of the BioGptForSequenceClassification class.
            value (Tensor): The input embeddings to be set for the model. It should be a 2D tensor.

        Returns:
            None.

        Raises:
            None
        """
        self.biogpt.embed_tokens = value

mindnlp.transformers.models.biogpt.modeling_biogpt.BioGptForSequenceClassification.__init__(config)

Initializes a BioGptForSequenceClassification instance.

PARAMETER DESCRIPTION
self

The instance of the BioGptForSequenceClassification class.

config

An instance of BioGptConfig containing configuration settings for the model. This parameter is required for initializing the BioGptForSequenceClassification instance. It specifies the configuration details such as the number of labels and hidden size.

TYPE: BioGptConfig

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
TypeError

If the config parameter is not of type BioGptConfig.

ValueError

If the num_labels attribute is not present in the config parameter.

ValueError

If an error occurs during the initialization of the BioGptModel or Dense layers.

Source code in mindnlp/transformers/models/biogpt/modeling_biogpt.py
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
def __init__(self, config: BioGptConfig):
    """
    Initializes a BioGptForSequenceClassification instance.

    Args:
        self: The instance of the BioGptForSequenceClassification class.
        config (BioGptConfig): An instance of BioGptConfig containing configuration settings for the model.
            This parameter is required for initializing the BioGptForSequenceClassification instance.
            It specifies the configuration details such as the number of labels and hidden size.

    Returns:
        None.

    Raises:
        TypeError: If the config parameter is not of type BioGptConfig.
        ValueError: If the num_labels attribute is not present in the config parameter.
        ValueError: If an error occurs during the initialization of the BioGptModel or Dense layers.
    """
    super().__init__(config)
    self.num_labels = config.num_labels
    self.biogpt = BioGptModel(config)
    self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)

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

mindnlp.transformers.models.biogpt.modeling_biogpt.BioGptForSequenceClassification.forward(input_ids=None, attention_mask=None, 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
labels

Labels for computing the sequence classification/regression loss. Indices should be in [0, ..., config.num_labels - 1]. If config.num_labels == 1 a regression loss is computed (Mean-Square loss), If config.num_labels > 1 a classification loss is computed (Cross-Entropy).

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

Source code in mindnlp/transformers/models/biogpt/modeling_biogpt.py
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
def forward(
    self,
    input_ids: Optional[mindspore.Tensor] = None,
    attention_mask: Optional[mindspore.Tensor] = None,
    head_mask: Optional[mindspore.Tensor] = None,
    past_key_values: Optional[Tuple[Tuple[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, SequenceClassifierOutputWithPast]:
    r"""
    Args:
        labels (`mindspore.Tensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
    """
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict

    transformer_outputs = self.biogpt(
        input_ids,
        past_key_values=past_key_values,
        attention_mask=attention_mask,
        head_mask=head_mask,
        inputs_embeds=inputs_embeds,
        use_cache=use_cache,
        output_attentions=output_attentions,
        output_hidden_states=output_hidden_states,
        return_dict=return_dict,
    )
    hidden_states = transformer_outputs[0]
    logits = self.score(hidden_states)

    if input_ids is not None:
        batch_size, sequence_length = input_ids.shape[:2]
    else:
        batch_size, sequence_length = inputs_embeds.shape[:2]

    if self.config.pad_token_id is None:
        sequence_length = -1
    else:
        if input_ids is not None:
            sequence_length = ops.ne(input_ids, self.config.pad_token_id).sum(-1) - 1
        else:
            sequence_length = -1
            logger.warning(
                f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
                "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
            )

    pooled_logits = logits[ops.arange(batch_size), sequence_length]

    loss = None
    if labels is not None:
        if self.config.problem_type is None:
            if self.num_labels == 1:
                self.config.problem_type = "regression"
            elif self.num_labels > 1 and labels.dtype in (mindspore.int64, mindspore.int32):
                self.config.problem_type = "single_label_classification"
            else:
                self.config.problem_type = "multi_label_classification"

        if self.config.problem_type == "regression":
            if self.num_labels == 1:
                loss = F.mse_loss(pooled_logits.squeeze(), labels.squeeze())
            else:
                loss = F.mse_loss(pooled_logits, labels)
        elif self.config.problem_type == "single_label_classification":
            loss = F.cross_entropy(pooled_logits.view(-1, self.num_labels), labels.view(-1))
        elif self.config.problem_type == "multi_label_classification":
            loss = F.binary_cross_entropy_with_logits(pooled_logits, labels)
    if not return_dict:
        output = (pooled_logits,) + transformer_outputs[1:]
        return ((loss,) + output) if loss is not None else output

    return SequenceClassifierOutputWithPast(
        loss=loss,
        logits=pooled_logits,
        past_key_values=transformer_outputs.past_key_values,
        hidden_states=transformer_outputs.hidden_states,
        attentions=transformer_outputs.attentions,
    )

mindnlp.transformers.models.biogpt.modeling_biogpt.BioGptForSequenceClassification.get_input_embeddings()

Method to retrieve the input embeddings from BioGptForSequenceClassification.

PARAMETER DESCRIPTION
self

The instance of the BioGptForSequenceClassification class. Represents the object itself.

TYPE: BioGptForSequenceClassification

RETURNS DESCRIPTION
None

This method returns the embeddings obtained from the BioGpt model.

Source code in mindnlp/transformers/models/biogpt/modeling_biogpt.py
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
def get_input_embeddings(self):
    """
    Method to retrieve the input embeddings from BioGptForSequenceClassification.

    Args:
        self (BioGptForSequenceClassification): The instance of the BioGptForSequenceClassification class.
            Represents the object itself.

    Returns:
        None: This method returns the embeddings obtained from the BioGpt model.

    Raises:
        None.
    """
    return self.biogpt.embed_tokens

mindnlp.transformers.models.biogpt.modeling_biogpt.BioGptForSequenceClassification.set_input_embeddings(value)

Set the input embeddings for the BioGptForSequenceClassification model.

PARAMETER DESCRIPTION
self

The instance of the BioGptForSequenceClassification class.

TYPE: BioGptForSequenceClassification

value

The input embeddings to be set for the model. It should be a 2D tensor.

TYPE: Tensor

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/biogpt/modeling_biogpt.py
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
def set_input_embeddings(self, value):
    """
    Set the input embeddings for the BioGptForSequenceClassification model.

    Args:
        self (BioGptForSequenceClassification): The instance of the BioGptForSequenceClassification class.
        value (Tensor): The input embeddings to be set for the model. It should be a 2D tensor.

    Returns:
        None.

    Raises:
        None
    """
    self.biogpt.embed_tokens = value

mindnlp.transformers.models.biogpt.modeling_biogpt.BioGptModel

Bases: BioGptPreTrainedModel

BioGptModel represents a GPT (Generative Pre-trained Transformer) model customized for bioinformatics tasks. This class inherits from BioGptPreTrainedModel and implements methods for initializing the model, setting input embeddings, and forwarding the model for inference or training. The model includes parameters for layer dropout, hidden dropout probability, embedding dimensions, padding index, and layer normalization. The forward method processes input data, applies attention masks, computes positional embeddings, and iterates through decoder layers to generate model output. Additionally, the class supports gradient checkpointing and caching for efficient training.

Source code in mindnlp/transformers/models/biogpt/modeling_biogpt.py
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
class BioGptModel(BioGptPreTrainedModel):

    """
    BioGptModel represents a GPT (Generative Pre-trained Transformer) model customized for bioinformatics tasks.
    This class inherits from BioGptPreTrainedModel and implements methods for initializing the model,
    setting input embeddings, and forwarding the model for inference or training.
    The model includes parameters for layer dropout, hidden dropout probability, embedding dimensions,
    padding index, and layer normalization.
    The forward method processes input data, applies attention masks, computes positional embeddings,
    and iterates through decoder layers to generate model output.
    Additionally, the class supports gradient checkpointing and caching for efficient training.
    """
    def __init__(self, config: BioGptConfig):
        """
        Initializes a BioGptModel instance with the provided configuration.

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

                - BioGptConfig is a data class that holds various settings for the BioGptModel.
                - It must be provided to properly configure the model.
                - The config parameter is required and should not be None.

        Returns:
            None.

        Raises:
            None
        """
        super().__init__(config)
        self.config = config
        self.layerdrop = config.layerdrop
        self.dropout = config.hidden_dropout_prob
        self.embed_dim = config.hidden_size
        self.padding_idx = config.pad_token_id
        self.embed_scale = math.sqrt(config.hidden_size) if config.scale_embedding else 1.0

        self.embed_tokens = nn.Embedding(config.vocab_size, self.embed_dim, self.padding_idx)
        self.embed_positions = BioGptLearnedPositionalEmbedding(config.max_position_embeddings, self.embed_dim)

        self.layers = nn.ModuleList([BioGptDecoderLayer(config) for _ in range(config.num_hidden_layers)])
        self.layer_norm = nn.LayerNorm(self.embed_dim)

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

    def get_input_embeddings(self):
        """
        Method: get_input_embeddings

        Description:
        This method retrieves the input embeddings from the BioGptModel instance.

        Args:
            self (BioGptModel): The current instance of the BioGptModel class.

        Returns:
            embed_tokens: This method returns the input embeddings associated with the BioGptModel instance.

        Raises:
            None.
        """
        return self.embed_tokens

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

        Args:
            self (BioGptModel): The instance of the BioGptModel class.
            value (Any): The input embeddings to be set for the model.

        Returns:
            None:
                This method updates the 'embed_tokens' attribute of the BioGptModel instance with the provided
                input embeddings.

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

    def forward(
        self,
        input_ids: Optional[mindspore.Tensor] = None,
        attention_mask: Optional[mindspore.Tensor] = None,
        head_mask: Optional[mindspore.Tensor] = None,
        inputs_embeds: Optional[mindspore.Tensor] = None,
        past_key_values: Optional[Tuple[Tuple[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, BaseModelOutputWithPastAndCrossAttentions]:
        """
        Constructs the BioGptModel.

        Args:
            self (BioGptModel): The instance of the BioGptModel class.
            input_ids (Optional[mindspore.Tensor]): The input token IDs. Defaults to None.
            attention_mask (Optional[mindspore.Tensor]): The attention mask. Defaults to None.
            head_mask (Optional[mindspore.Tensor]): The head mask. Defaults to None.
            inputs_embeds (Optional[mindspore.Tensor]): The embedded inputs. Defaults to None.
            past_key_values (Optional[Tuple[Tuple[mindspore.Tensor]]]): The past key values. Defaults to None.
            use_cache (Optional[bool]): Whether to use cache. Defaults to None.
            output_attentions (Optional[bool]): Whether to output attentions. Defaults to None.
            output_hidden_states (Optional[bool]): Whether to output hidden states. Defaults to None.
            return_dict (Optional[bool]): Whether to return a dictionary. Defaults to None.

        Returns:
            Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]: The output of the BioGptModel.
                It can either be a tuple or an instance of BaseModelOutputWithPastAndCrossAttentions.

        Raises:
            ValueError: If both input_ids and inputs_embeds are specified.
            ValueError: If neither input_ids nor inputs_embeds are specified.
            ValueError: If the length of the provided attention mask is incorrect.
            Warning: If use_cache is set to True and gradient checkpointing is enabled.

        """
        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

        # retrieve input_ids and inputs_embeds
        if input_ids is not None and inputs_embeds is not None:
            raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
        if input_ids is not None:
            input = input_ids
            input_shape = input.shape
        elif inputs_embeds is not None:
            input_shape = inputs_embeds.shape[:-1]
            input = inputs_embeds[:, :, -1]
        else:
            raise ValueError("You have to specify either input_ids or inputs_embeds")

        # past_key_values_length
        past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0

        if inputs_embeds is None:
            inputs_embeds = self.embed_tokens(input) * self.embed_scale

        if attention_mask is None:
            attention_mask = ops.ones(
                inputs_embeds.shape[0], inputs_embeds.shape[1] + past_key_values_length,
                dtype=mindspore.bool_,
            )
        elif attention_mask.shape[1] != past_key_values_length + input_shape[1]:
            raise ValueError(
                f"The provided attention mask has length {attention_mask.shape[1]}, but its length should be "
                f"{past_key_values_length + input_shape[1]} (sum of the lengths of current and past inputs)"
            )

        # embed positions
        positions = self.embed_positions(attention_mask, past_key_values_length)

        attention_mask = _prepare_4d_causal_attention_mask(
            attention_mask, input_shape, inputs_embeds, past_key_values_length
        )

        hidden_states = inputs_embeds + positions

        hidden_states = F.dropout(hidden_states, p=self.dropout, training=self.training)

        if self.gradient_checkpointing and self.training:
            if use_cache:
                logger.warning_once(
                    "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
                )
                use_cache = False

        all_hidden_states = () if output_hidden_states else None
        all_self_attns = () if output_attentions else None
        all_cross_attentions = None
        next_decoder_cache = () if use_cache else None

        for idx, decoder_layer in enumerate(self.layers):
            # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
            if output_hidden_states:
                all_hidden_states += (hidden_states,)
            if self.training:
                dropout_probability = ops.rand([])
                if dropout_probability < self.layerdrop:
                    continue

            past_key_value = past_key_values[idx] if past_key_values is not None else None

            if self.gradient_checkpointing and self.training:
                layer_outputs = self._gradient_checkpointing_func(
                    decoder_layer.__call__,
                    hidden_states,
                    attention_mask,
                    head_mask[idx] if head_mask is not None else None,
                    None,
                    output_attentions,
                    use_cache,
                )
            else:
                layer_outputs = decoder_layer(
                    hidden_states,
                    attention_mask=attention_mask,
                    layer_head_mask=(head_mask[idx] if head_mask is not None else None),
                    past_key_value=past_key_value,
                    output_attentions=output_attentions,
                    use_cache=use_cache,
                )

            hidden_states = layer_outputs[0]

            if use_cache:
                next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)

            if output_attentions:
                all_self_attns += (layer_outputs[1],)

        # add hidden states from the last decoder layer
        if output_hidden_states:
            all_hidden_states += (hidden_states,)

        hidden_states = self.layer_norm(hidden_states)

        next_cache = next_decoder_cache if use_cache else None

        if not return_dict:
            return tuple(
                v
                for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions]
                if v is not None
            )
        return BaseModelOutputWithPastAndCrossAttentions(
            last_hidden_state=hidden_states,
            past_key_values=next_cache,
            hidden_states=all_hidden_states,
            attentions=all_self_attns,
            cross_attentions=all_cross_attentions,
        )

mindnlp.transformers.models.biogpt.modeling_biogpt.BioGptModel.__init__(config)

Initializes a BioGptModel instance with the provided configuration.

PARAMETER DESCRIPTION
self

The instance of the BioGptModel class.

config

An instance of BioGptConfig containing the configuration parameters for the model.

  • BioGptConfig is a data class that holds various settings for the BioGptModel.
  • It must be provided to properly configure the model.
  • The config parameter is required and should not be None.

TYPE: BioGptConfig

RETURNS DESCRIPTION

None.

Source code in mindnlp/transformers/models/biogpt/modeling_biogpt.py
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
def __init__(self, config: BioGptConfig):
    """
    Initializes a BioGptModel instance with the provided configuration.

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

            - BioGptConfig is a data class that holds various settings for the BioGptModel.
            - It must be provided to properly configure the model.
            - The config parameter is required and should not be None.

    Returns:
        None.

    Raises:
        None
    """
    super().__init__(config)
    self.config = config
    self.layerdrop = config.layerdrop
    self.dropout = config.hidden_dropout_prob
    self.embed_dim = config.hidden_size
    self.padding_idx = config.pad_token_id
    self.embed_scale = math.sqrt(config.hidden_size) if config.scale_embedding else 1.0

    self.embed_tokens = nn.Embedding(config.vocab_size, self.embed_dim, self.padding_idx)
    self.embed_positions = BioGptLearnedPositionalEmbedding(config.max_position_embeddings, self.embed_dim)

    self.layers = nn.ModuleList([BioGptDecoderLayer(config) for _ in range(config.num_hidden_layers)])
    self.layer_norm = nn.LayerNorm(self.embed_dim)

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

mindnlp.transformers.models.biogpt.modeling_biogpt.BioGptModel.forward(input_ids=None, attention_mask=None, head_mask=None, inputs_embeds=None, past_key_values=None, use_cache=None, output_attentions=None, output_hidden_states=None, return_dict=None)

Constructs the BioGptModel.

PARAMETER DESCRIPTION
self

The instance of the BioGptModel class.

TYPE: BioGptModel

input_ids

The input token IDs. Defaults to None.

TYPE: Optional[Tensor] DEFAULT: None

attention_mask

The attention mask. Defaults to None.

TYPE: Optional[Tensor] DEFAULT: None

head_mask

The head mask. Defaults to None.

TYPE: Optional[Tensor] DEFAULT: None

inputs_embeds

The embedded inputs. Defaults to None.

TYPE: Optional[Tensor] DEFAULT: None

past_key_values

The past key values. Defaults to None.

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

use_cache

Whether to use cache. Defaults to None.

TYPE: Optional[bool] DEFAULT: None

output_attentions

Whether to output attentions. Defaults to None.

TYPE: Optional[bool] DEFAULT: None

output_hidden_states

Whether to output hidden states. Defaults to None.

TYPE: Optional[bool] DEFAULT: None

return_dict

Whether to return a dictionary. Defaults to None.

TYPE: Optional[bool] DEFAULT: None

RETURNS DESCRIPTION
Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]

Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]: The output of the BioGptModel. It can either be a tuple or an instance of BaseModelOutputWithPastAndCrossAttentions.

RAISES DESCRIPTION
ValueError

If both input_ids and inputs_embeds are specified.

ValueError

If neither input_ids nor inputs_embeds are specified.

ValueError

If the length of the provided attention mask is incorrect.

Warning

If use_cache is set to True and gradient checkpointing is enabled.

Source code in mindnlp/transformers/models/biogpt/modeling_biogpt.py
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
def forward(
    self,
    input_ids: Optional[mindspore.Tensor] = None,
    attention_mask: Optional[mindspore.Tensor] = None,
    head_mask: Optional[mindspore.Tensor] = None,
    inputs_embeds: Optional[mindspore.Tensor] = None,
    past_key_values: Optional[Tuple[Tuple[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, BaseModelOutputWithPastAndCrossAttentions]:
    """
    Constructs the BioGptModel.

    Args:
        self (BioGptModel): The instance of the BioGptModel class.
        input_ids (Optional[mindspore.Tensor]): The input token IDs. Defaults to None.
        attention_mask (Optional[mindspore.Tensor]): The attention mask. Defaults to None.
        head_mask (Optional[mindspore.Tensor]): The head mask. Defaults to None.
        inputs_embeds (Optional[mindspore.Tensor]): The embedded inputs. Defaults to None.
        past_key_values (Optional[Tuple[Tuple[mindspore.Tensor]]]): The past key values. Defaults to None.
        use_cache (Optional[bool]): Whether to use cache. Defaults to None.
        output_attentions (Optional[bool]): Whether to output attentions. Defaults to None.
        output_hidden_states (Optional[bool]): Whether to output hidden states. Defaults to None.
        return_dict (Optional[bool]): Whether to return a dictionary. Defaults to None.

    Returns:
        Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]: The output of the BioGptModel.
            It can either be a tuple or an instance of BaseModelOutputWithPastAndCrossAttentions.

    Raises:
        ValueError: If both input_ids and inputs_embeds are specified.
        ValueError: If neither input_ids nor inputs_embeds are specified.
        ValueError: If the length of the provided attention mask is incorrect.
        Warning: If use_cache is set to True and gradient checkpointing is enabled.

    """
    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

    # retrieve input_ids and inputs_embeds
    if input_ids is not None and inputs_embeds is not None:
        raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
    if input_ids is not None:
        input = input_ids
        input_shape = input.shape
    elif inputs_embeds is not None:
        input_shape = inputs_embeds.shape[:-1]
        input = inputs_embeds[:, :, -1]
    else:
        raise ValueError("You have to specify either input_ids or inputs_embeds")

    # past_key_values_length
    past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0

    if inputs_embeds is None:
        inputs_embeds = self.embed_tokens(input) * self.embed_scale

    if attention_mask is None:
        attention_mask = ops.ones(
            inputs_embeds.shape[0], inputs_embeds.shape[1] + past_key_values_length,
            dtype=mindspore.bool_,
        )
    elif attention_mask.shape[1] != past_key_values_length + input_shape[1]:
        raise ValueError(
            f"The provided attention mask has length {attention_mask.shape[1]}, but its length should be "
            f"{past_key_values_length + input_shape[1]} (sum of the lengths of current and past inputs)"
        )

    # embed positions
    positions = self.embed_positions(attention_mask, past_key_values_length)

    attention_mask = _prepare_4d_causal_attention_mask(
        attention_mask, input_shape, inputs_embeds, past_key_values_length
    )

    hidden_states = inputs_embeds + positions

    hidden_states = F.dropout(hidden_states, p=self.dropout, training=self.training)

    if self.gradient_checkpointing and self.training:
        if use_cache:
            logger.warning_once(
                "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
            )
            use_cache = False

    all_hidden_states = () if output_hidden_states else None
    all_self_attns = () if output_attentions else None
    all_cross_attentions = None
    next_decoder_cache = () if use_cache else None

    for idx, decoder_layer in enumerate(self.layers):
        # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
        if output_hidden_states:
            all_hidden_states += (hidden_states,)
        if self.training:
            dropout_probability = ops.rand([])
            if dropout_probability < self.layerdrop:
                continue

        past_key_value = past_key_values[idx] if past_key_values is not None else None

        if self.gradient_checkpointing and self.training:
            layer_outputs = self._gradient_checkpointing_func(
                decoder_layer.__call__,
                hidden_states,
                attention_mask,
                head_mask[idx] if head_mask is not None else None,
                None,
                output_attentions,
                use_cache,
            )
        else:
            layer_outputs = decoder_layer(
                hidden_states,
                attention_mask=attention_mask,
                layer_head_mask=(head_mask[idx] if head_mask is not None else None),
                past_key_value=past_key_value,
                output_attentions=output_attentions,
                use_cache=use_cache,
            )

        hidden_states = layer_outputs[0]

        if use_cache:
            next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)

        if output_attentions:
            all_self_attns += (layer_outputs[1],)

    # add hidden states from the last decoder layer
    if output_hidden_states:
        all_hidden_states += (hidden_states,)

    hidden_states = self.layer_norm(hidden_states)

    next_cache = next_decoder_cache if use_cache else None

    if not return_dict:
        return tuple(
            v
            for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions]
            if v is not None
        )
    return BaseModelOutputWithPastAndCrossAttentions(
        last_hidden_state=hidden_states,
        past_key_values=next_cache,
        hidden_states=all_hidden_states,
        attentions=all_self_attns,
        cross_attentions=all_cross_attentions,
    )

mindnlp.transformers.models.biogpt.modeling_biogpt.BioGptModel.get_input_embeddings()

Description: This method retrieves the input embeddings from the BioGptModel instance.

PARAMETER DESCRIPTION
self

The current instance of the BioGptModel class.

TYPE: BioGptModel

RETURNS DESCRIPTION
embed_tokens

This method returns the input embeddings associated with the BioGptModel instance.

Source code in mindnlp/transformers/models/biogpt/modeling_biogpt.py
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
def get_input_embeddings(self):
    """
    Method: get_input_embeddings

    Description:
    This method retrieves the input embeddings from the BioGptModel instance.

    Args:
        self (BioGptModel): The current instance of the BioGptModel class.

    Returns:
        embed_tokens: This method returns the input embeddings associated with the BioGptModel instance.

    Raises:
        None.
    """
    return self.embed_tokens

mindnlp.transformers.models.biogpt.modeling_biogpt.BioGptModel.set_input_embeddings(value)

Set the input embeddings for the BioGptModel.

PARAMETER DESCRIPTION
self

The instance of the BioGptModel class.

TYPE: BioGptModel

value

The input embeddings to be set for the model.

TYPE: Any

RETURNS DESCRIPTION
None

This method updates the 'embed_tokens' attribute of the BioGptModel instance with the provided input embeddings.

Source code in mindnlp/transformers/models/biogpt/modeling_biogpt.py
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
def set_input_embeddings(self, value):
    """
    Set the input embeddings for the BioGptModel.

    Args:
        self (BioGptModel): The instance of the BioGptModel class.
        value (Any): The input embeddings to be set for the model.

    Returns:
        None:
            This method updates the 'embed_tokens' attribute of the BioGptModel instance with the provided
            input embeddings.

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

mindnlp.transformers.models.biogpt.modeling_biogpt.BioGptPreTrainedModel

Bases: PreTrainedModel

An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.

Source code in mindnlp/transformers/models/biogpt/modeling_biogpt.py
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
class BioGptPreTrainedModel(PreTrainedModel):
    """
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    """
    config_class = BioGptConfig
    base_model_prefix = "biogpt"
    supports_gradient_checkpointing = True

    def _init_weights(self, cell):
        """Initialize the weights"""
        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(self.config.initializer_range),
                                                    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, self.config.initializer_range, cell.weight.shape)
            if cell.padding_idx:
                weight[cell.padding_idx] = 0

            cell.weight.set_data(Tensor(weight, cell.weight.dtype))
        elif isinstance(cell, nn.LayerNorm):
            cell.weight.set_data(initializer('ones', cell.weight.shape, cell.weight.dtype))
            cell.bias.set_data(initializer('zeros', cell.bias.shape, cell.bias.dtype))

mindnlp.transformers.models.biogpt.tokenization_biogpt.BioGptTokenizer

Bases: PreTrainedTokenizer

Construct an FAIRSEQ Transformer tokenizer. Moses tokenization followed by Byte-Pair Encoding.

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

PARAMETER DESCRIPTION
vocab_file

Path to the vocabulary file.

TYPE: `str`

merges_file

Merges file.

TYPE: `str`

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>'

bos_token

The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.

When building a sequence using special tokens, this is not the token that is used for the beginning of sequence. The token used is the cls_token.

TYPE: `str`, *optional*, defaults to `"<s>"` DEFAULT: '<s>'

eos_token

The end of sequence token.

When building a sequence using special tokens, this is not the token that is used for the end of sequence. The token used is the sep_token.

TYPE: `str`, *optional*, defaults to `"</s>"` DEFAULT: '</s>'

sep_token

The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for sequence classification or for a text and a question for question answering. It is also used as the last token of a sequence built with special tokens.

TYPE: `str`, *optional*, defaults to `"</s>"` DEFAULT: '</s>'

pad_token

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

TYPE: `str`, *optional*, defaults to `"<pad>"` DEFAULT: '<pad>'

Source code in mindnlp/transformers/models/biogpt/tokenization_biogpt.py
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
class BioGptTokenizer(PreTrainedTokenizer):
    """
    Construct an FAIRSEQ Transformer tokenizer. Moses tokenization followed by Byte-Pair Encoding.

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

    Args:
        vocab_file (`str`):
            Path to the vocabulary file.
        merges_file (`str`):
            Merges file.
        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.
        bos_token (`str`, *optional*, defaults to `"<s>"`):
            The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.

            <Tip>

            When building a sequence using special tokens, this is not the token that is used for the beginning of
            sequence. The token used is the `cls_token`.

            </Tip>

        eos_token (`str`, *optional*, defaults to `"</s>"`):
            The end of sequence token.

            <Tip>

            When building a sequence using special tokens, this is not the token that is used for the end of sequence.
            The token used is the `sep_token`.

            </Tip>

        sep_token (`str`, *optional*, defaults to `"</s>"`):
            The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
            sequence classification or for a text and a question for question answering. It is also used as the last
            token of a sequence built with special tokens.
        pad_token (`str`, *optional*, defaults to `"<pad>"`):
            The token used for padding, for example when batching sequences of different lengths.
    """
    vocab_files_names = VOCAB_FILES_NAMES
    pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
    max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    model_input_names = ["input_ids", "attention_mask"]

    def __init__(
        self,
        vocab_file,
        merges_file,
        unk_token="<unk>",
        bos_token="<s>",
        eos_token="</s>",
        sep_token="</s>",
        pad_token="<pad>",
        **kwargs,
    ):
        """
        Initializes a new instance of the BioGptTokenizer class.

        Args:
            self: The instance of the class.
            vocab_file (str): The path to the vocabulary file.
            merges_file (str): The path to the merges file.
            unk_token (str, optional): The token to represent unknown words. Defaults to '<unk>'.
            bos_token (str, optional): The token to represent the beginning of a sentence. Defaults to '<s>'.
            eos_token (str, optional): The token to represent the end of a sentence. Defaults to '</s>'.
            sep_token (str, optional): The token to represent sentence separation. Defaults to '</s>'.
            pad_token (str, optional): The token to represent padding. Defaults to '<pad>'.
            **kwargs: Additional keyword arguments.

        Returns:
            None

        Raises:
            ImportError: If sacremoses library is not installed.
            IOError: If the vocabulary or merges file cannot be read.
        """
        try:
            import sacremoses
        except ImportError as e:
            raise ImportError(
                "You need to install sacremoses to use BioGptTokenizer. "
                "See https://pypi.org/project/sacremoses/ for installation."
            ) from e

        self.lang = "en"
        self.sm = sacremoses
        # cache of sm.MosesTokenizer instance
        self.cache_moses_tokenizer = {}
        self.cache_moses_detokenizer = {}

        """ Initialisation"""
        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]
        merges = [tuple(merge.split()[:2]) for merge in merges]
        self.bpe_ranks = dict(zip(merges, range(len(merges))))
        self.cache = {}

        super().__init__(
            bos_token=bos_token,
            eos_token=eos_token,
            sep_token=sep_token,
            unk_token=unk_token,
            pad_token=pad_token,
            **kwargs,
        )

    @property
    def vocab_size(self):
        """Returns vocab size"""
        return len(self.encoder)

    def get_vocab(self):
        """
        Method to retrieve the vocabulary dictionary consisting of tokens and their corresponding encodings.

        Args:
            self (BioGptTokenizer): The instance of the BioGptTokenizer class.
                It represents the tokenizer object.

        Returns:
            None: The method returns a vocabulary dictionary that contains tokens and their respective encodings.

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

    def moses_tokenize(self, text, lang):
        """
        Perform Moses tokenization on the given text.

        Args:
            self (BioGptTokenizer): An instance of the BioGptTokenizer class.
            text (str): The text to be tokenized.
            lang (str): The language code for tokenization.

        Returns:
            None

        Raises:
            KeyError: If the language code is not found in the cache_moses_tokenizer dictionary.
            ValueError: If the language code is invalid or unsupported.
            Exception: If any other error occurs during tokenization.

        This method utilizes the MosesTokenizer from the nltk.translate.moses package to tokenize the input text.
        It first checks if the MosesTokenizer for the specified language is already cached.
        If not, it creates a new MosesTokenizer instance for the language and adds it to the cache.
        The tokenization is then performed using the cached MosesTokenizer object.

        The 'aggressive_dash_splits', 'return_str', and 'escape' parameters are passed to the tokenize method of
        the MosesTokenizer.
        'aggressive_dash_splits' determines whether to perform aggressive dash splitting,
        'return_str' specifies whether to return a string or a list of tokens,
        and 'escape' determines whether to escape XML/HTML characters in the text before tokenization.

        Note:
            This method assumes that the BioGptTokenizer instance has been properly initialized with the necessary
            resources for tokenization.
        """
        if lang not in self.cache_moses_tokenizer:
            moses_tokenizer = self.sm.MosesTokenizer(lang=lang)
            self.cache_moses_tokenizer[lang] = moses_tokenizer
        return self.cache_moses_tokenizer[lang].tokenize(
            text, aggressive_dash_splits=True, return_str=False, escape=True
        )

    def moses_detokenize(self, tokens, lang):
        """
        Performs Moses detokenization on a list of tokens for a specified language.

        Args:
            self (BioGptTokenizer): An instance of the BioGptTokenizer class.
            tokens (list): A list of tokens to be detokenized.
            lang (str): The language of the tokens. Must be a supported language.

        Returns:
            None: The method modifies the cache_moses_detokenizer attribute of the BioGptTokenizer instance.

        Raises:
            KeyError: If the specified language is not supported.
            TypeError: If the tokens parameter is not a list.

        Note:
            This method utilizes a cache to store MosesDetokenizer objects for each language,
            ensuring efficient detokenization by reusing previously created instances.
        """
        if lang not in self.cache_moses_detokenizer:
            moses_detokenizer = self.sm.MosesDetokenizer(lang=lang)
            self.cache_moses_detokenizer[lang] = moses_detokenizer
        return self.cache_moses_detokenizer[lang].detokenize(tokens)

    def bpe(self, token):
        """
        Performs Byte Pair Encoding (BPE) on a given token.

        Args:
            self: An instance of the BioGptTokenizer class.
            token (str): The token to be encoded using BPE.

        Returns:
            str: The BPE-encoded representation of the token.

        Raises:
            None.

        Description:
            This method takes a token and applies Byte Pair Encoding (BPE) to it. BPE is a subword tokenization
            technique that breaks down a token into a sequence of subword units.
            The BPE algorithm iteratively  merges the most frequent pairs of subword units to create a vocabulary
            of subword units.

            The token parameter is the input token to be encoded using BPE. The token is expected to be a string.

            The method returns the BPE-encoded representation of the token as a string.
            The encoded representation is obtained by iteratively merging the most frequent pairs of subword units
            until no more merges can be made.
            The resulting subword units are then joined together to form the encoded token.

            Note that the method may use a cache to store previously encoded tokens for efficiency.

        Example:
            ```python
            >>> tokenizer = BioGptTokenizer()
            >>> encoded_token = tokenizer.bpe('sequence')
            >>> print(encoded_token)
            >>> # Output: 'seq uence'</w>'
            ```
        """
        word = tuple(token[:-1]) + (token[-1] + "</w>",)
        if token in self.cache:
            return self.cache[token]
        pairs = get_pairs(word)

        if not pairs:
            return token + "</w>"

        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)
                except ValueError:
                    new_word.extend(word[i:])
                    break
                else:
                    new_word.extend(word[i:j])
                    i = j

                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
            pairs = get_pairs(word)
        word = " ".join(word)
        if word == "\n  </w>":
            word = "\n</w>"
        self.cache[token] = word
        return word

    def _tokenize(self, text, bypass_tokenizer=False):
        """Returns a tokenized string."""
        if bypass_tokenizer:
            text = text.split()
        else:
            text = self.moses_tokenize(text, self.lang)

        split_tokens = []
        for token in text:
            if token:
                split_tokens.extend(list(self.bpe(token).split(" ")))

        return split_tokens

    def _convert_token_to_id(self, token):
        """Converts a token (str) in an id using the vocab."""
        return self.encoder.get(token, self.encoder.get(self.unk_token))

    def _convert_id_to_token(self, index):
        """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):
        """Converts a sequence of tokens (string) in a single string."""
        # remove BPE
        tokens = [t.replace(" ", "").replace("</w>", " ") for t in tokens]
        tokens = "".join(tokens).split()
        # detokenize
        text = self.moses_detokenize(tokens, self.lang)
        return text

    def build_inputs_with_special_tokens(
        self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
    ) -> List[int]:
        """
        Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
        adding special tokens. A BioGPT sequence has the following format:

        - single sequence: `</s> X `
        - pair of sequences: `</s> A </s> B `

        Args:
            token_ids_0 (`List[int]`):
                List of IDs to which the special tokens will be added.
            token_ids_1 (`List[int]`, *optional*):
                Optional second list of IDs for sequence pairs.

        Returns:
            `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
        """
        if token_ids_1 is None:
            return [self.sep_token_id] + token_ids_0
        sep = [self.sep_token_id]
        return sep + token_ids_0 + sep + token_ids_1

    def get_special_tokens_mask(
        self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
    ) -> List[int]:
        """
        Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
        special tokens using the tokenizer `prepare_for_model` method.

        Args:
            token_ids_0 (`List[int]`):
                List of IDs.
            token_ids_1 (`List[int]`, *optional*):
                Optional second list of IDs for sequence pairs.
            already_has_special_tokens (`bool`, *optional*, defaults to `False`):
                Whether or not the token list is already formatted with special tokens for the model.

        Returns:
            `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
        """
        if already_has_special_tokens:
            return super().get_special_tokens_mask(
                token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
            )
        # no bos used in fairseq
        if token_ids_1 is not None:
            return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1))
        return [1] + ([0] * len(token_ids_0))

    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. A FAIRSEQ
        Transformer sequence pair mask has the following format:

        ```
        0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
        | first sequence    | second sequence |
        ```

        If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).

        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 [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
        """
        sep = [self.sep_token_id]

        # no bos used in fairseq
        if token_ids_1 is None:
            return len(token_ids_0 + sep) * [0]
        return len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]

    def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
        """
        Save the vocabulary to the specified directory with the given filename prefix.

        Args:
            self: Instance of the BioGptTokenizer class.
            save_directory (str): The directory path where the vocabulary files will be saved.
                It should already exist, and the method will raise an error if the directory does not exist.
            filename_prefix (Optional[str]): An optional prefix to be added to the filenames of the vocabulary files.
                If provided, the filenames will be prefixed with this value. Default is None.

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

        Raises:
            OSError: If the specified save_directory is not a valid directory.
            IOError: If there is an issue writing the vocabulary files to the disk.
        """
        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:
            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

    def __getstate__(self):
        """
        The '__getstate__' method in the 'BioGptTokenizer' class is used to retrieve the state of the object for pickling.

        Args:
            self: An instance of the 'BioGptTokenizer' class.

        Returns:
            None: This method does not explicitly return a value, but modifies the state of the object.

        Raises:
            None.
        """
        state = self.__dict__.copy()
        state["sm"] = None
        return state

    def __setstate__(self, d):
        """
        Sets the state of the BioGptTokenizer object.

        Args:
            self (BioGptTokenizer): The instance of the BioGptTokenizer class.
            d (dict): The dictionary containing the state information to be set. 

        Returns:
            None.

        Raises:
            ImportError: If the sacremoses module is not installed, an ImportError is raised. 
                The error message specifies that sacremoses needs to be installed and provides a link to the installation page.
        """
        self.__dict__ = d

        try:
            import sacremoses
        except ImportError as e:
            raise ImportError(
                "You need to install sacremoses to use XLMTokenizer. "
                "See https://pypi.org/project/sacremoses/ for installation."
            ) from e

        self.sm = sacremoses

mindnlp.transformers.models.biogpt.tokenization_biogpt.BioGptTokenizer.cache_moses_detokenizer = {} instance-attribute

Initialisation

mindnlp.transformers.models.biogpt.tokenization_biogpt.BioGptTokenizer.vocab_size property

Returns vocab size

mindnlp.transformers.models.biogpt.tokenization_biogpt.BioGptTokenizer.__getstate__()

The 'getstate' method in the 'BioGptTokenizer' class is used to retrieve the state of the object for pickling.

PARAMETER DESCRIPTION
self

An instance of the 'BioGptTokenizer' class.

RETURNS DESCRIPTION
None

This method does not explicitly return a value, but modifies the state of the object.

Source code in mindnlp/transformers/models/biogpt/tokenization_biogpt.py
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
def __getstate__(self):
    """
    The '__getstate__' method in the 'BioGptTokenizer' class is used to retrieve the state of the object for pickling.

    Args:
        self: An instance of the 'BioGptTokenizer' class.

    Returns:
        None: This method does not explicitly return a value, but modifies the state of the object.

    Raises:
        None.
    """
    state = self.__dict__.copy()
    state["sm"] = None
    return state

mindnlp.transformers.models.biogpt.tokenization_biogpt.BioGptTokenizer.__init__(vocab_file, merges_file, unk_token='<unk>', bos_token='<s>', eos_token='</s>', sep_token='</s>', pad_token='<pad>', **kwargs)

Initializes a new instance of the BioGptTokenizer class.

PARAMETER DESCRIPTION
self

The instance of the class.

vocab_file

The path to the vocabulary file.

TYPE: str

merges_file

The path to the merges file.

TYPE: str

unk_token

The token to represent unknown words. Defaults to ''.

TYPE: str DEFAULT: '<unk>'

bos_token

The token to represent the beginning of a sentence. Defaults to ''.

TYPE: str DEFAULT: '<s>'

eos_token

The token to represent the end of a sentence. Defaults to ''.

TYPE: str DEFAULT: '</s>'

sep_token

The token to represent sentence separation. Defaults to ''.

TYPE: str DEFAULT: '</s>'

pad_token

The token to represent padding. Defaults to ''.

TYPE: str DEFAULT: '<pad>'

**kwargs

Additional keyword arguments.

DEFAULT: {}

RETURNS DESCRIPTION

None

RAISES DESCRIPTION
ImportError

If sacremoses library is not installed.

IOError

If the vocabulary or merges file cannot be read.

Source code in mindnlp/transformers/models/biogpt/tokenization_biogpt.py
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
def __init__(
    self,
    vocab_file,
    merges_file,
    unk_token="<unk>",
    bos_token="<s>",
    eos_token="</s>",
    sep_token="</s>",
    pad_token="<pad>",
    **kwargs,
):
    """
    Initializes a new instance of the BioGptTokenizer class.

    Args:
        self: The instance of the class.
        vocab_file (str): The path to the vocabulary file.
        merges_file (str): The path to the merges file.
        unk_token (str, optional): The token to represent unknown words. Defaults to '<unk>'.
        bos_token (str, optional): The token to represent the beginning of a sentence. Defaults to '<s>'.
        eos_token (str, optional): The token to represent the end of a sentence. Defaults to '</s>'.
        sep_token (str, optional): The token to represent sentence separation. Defaults to '</s>'.
        pad_token (str, optional): The token to represent padding. Defaults to '<pad>'.
        **kwargs: Additional keyword arguments.

    Returns:
        None

    Raises:
        ImportError: If sacremoses library is not installed.
        IOError: If the vocabulary or merges file cannot be read.
    """
    try:
        import sacremoses
    except ImportError as e:
        raise ImportError(
            "You need to install sacremoses to use BioGptTokenizer. "
            "See https://pypi.org/project/sacremoses/ for installation."
        ) from e

    self.lang = "en"
    self.sm = sacremoses
    # cache of sm.MosesTokenizer instance
    self.cache_moses_tokenizer = {}
    self.cache_moses_detokenizer = {}

    """ Initialisation"""
    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]
    merges = [tuple(merge.split()[:2]) for merge in merges]
    self.bpe_ranks = dict(zip(merges, range(len(merges))))
    self.cache = {}

    super().__init__(
        bos_token=bos_token,
        eos_token=eos_token,
        sep_token=sep_token,
        unk_token=unk_token,
        pad_token=pad_token,
        **kwargs,
    )

mindnlp.transformers.models.biogpt.tokenization_biogpt.BioGptTokenizer.__setstate__(d)

Sets the state of the BioGptTokenizer object.

PARAMETER DESCRIPTION
self

The instance of the BioGptTokenizer class.

TYPE: BioGptTokenizer

d

The dictionary containing the state information to be set.

TYPE: dict

RETURNS DESCRIPTION

None.

RAISES DESCRIPTION
ImportError

If the sacremoses module is not installed, an ImportError is raised. The error message specifies that sacremoses needs to be installed and provides a link to the installation page.

Source code in mindnlp/transformers/models/biogpt/tokenization_biogpt.py
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
def __setstate__(self, d):
    """
    Sets the state of the BioGptTokenizer object.

    Args:
        self (BioGptTokenizer): The instance of the BioGptTokenizer class.
        d (dict): The dictionary containing the state information to be set. 

    Returns:
        None.

    Raises:
        ImportError: If the sacremoses module is not installed, an ImportError is raised. 
            The error message specifies that sacremoses needs to be installed and provides a link to the installation page.
    """
    self.__dict__ = d

    try:
        import sacremoses
    except ImportError as e:
        raise ImportError(
            "You need to install sacremoses to use XLMTokenizer. "
            "See https://pypi.org/project/sacremoses/ for installation."
        ) from e

    self.sm = sacremoses

mindnlp.transformers.models.biogpt.tokenization_biogpt.BioGptTokenizer.bpe(token)

Performs Byte Pair Encoding (BPE) on a given token.

PARAMETER DESCRIPTION
self

An instance of the BioGptTokenizer class.

token

The token to be encoded using BPE.

TYPE: str

RETURNS DESCRIPTION
str

The BPE-encoded representation of the token.

Description

This method takes a token and applies Byte Pair Encoding (BPE) to it. BPE is a subword tokenization technique that breaks down a token into a sequence of subword units. The BPE algorithm iteratively merges the most frequent pairs of subword units to create a vocabulary of subword units.

The token parameter is the input token to be encoded using BPE. The token is expected to be a string.

The method returns the BPE-encoded representation of the token as a string. The encoded representation is obtained by iteratively merging the most frequent pairs of subword units until no more merges can be made. The resulting subword units are then joined together to form the encoded token.

Note that the method may use a cache to store previously encoded tokens for efficiency.

Example
>>> tokenizer = BioGptTokenizer()
>>> encoded_token = tokenizer.bpe('sequence')
>>> print(encoded_token)
>>> # Output: 'seq uence'</w>'
Source code in mindnlp/transformers/models/biogpt/tokenization_biogpt.py
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
def bpe(self, token):
    """
    Performs Byte Pair Encoding (BPE) on a given token.

    Args:
        self: An instance of the BioGptTokenizer class.
        token (str): The token to be encoded using BPE.

    Returns:
        str: The BPE-encoded representation of the token.

    Raises:
        None.

    Description:
        This method takes a token and applies Byte Pair Encoding (BPE) to it. BPE is a subword tokenization
        technique that breaks down a token into a sequence of subword units.
        The BPE algorithm iteratively  merges the most frequent pairs of subword units to create a vocabulary
        of subword units.

        The token parameter is the input token to be encoded using BPE. The token is expected to be a string.

        The method returns the BPE-encoded representation of the token as a string.
        The encoded representation is obtained by iteratively merging the most frequent pairs of subword units
        until no more merges can be made.
        The resulting subword units are then joined together to form the encoded token.

        Note that the method may use a cache to store previously encoded tokens for efficiency.

    Example:
        ```python
        >>> tokenizer = BioGptTokenizer()
        >>> encoded_token = tokenizer.bpe('sequence')
        >>> print(encoded_token)
        >>> # Output: 'seq uence'</w>'
        ```
    """
    word = tuple(token[:-1]) + (token[-1] + "</w>",)
    if token in self.cache:
        return self.cache[token]
    pairs = get_pairs(word)

    if not pairs:
        return token + "</w>"

    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)
            except ValueError:
                new_word.extend(word[i:])
                break
            else:
                new_word.extend(word[i:j])
                i = j

            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
        pairs = get_pairs(word)
    word = " ".join(word)
    if word == "\n  </w>":
        word = "\n</w>"
    self.cache[token] = word
    return word

mindnlp.transformers.models.biogpt.tokenization_biogpt.BioGptTokenizer.build_inputs_with_special_tokens(token_ids_0, token_ids_1=None)

Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A BioGPT sequence has the following format:

  • single sequence: </s> X
  • pair of sequences: </s> A </s> B
PARAMETER DESCRIPTION
token_ids_0

List of IDs to which the special tokens will be added.

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 input IDs with the appropriate special tokens.

Source code in mindnlp/transformers/models/biogpt/tokenization_biogpt.py
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
def build_inputs_with_special_tokens(
    self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
) -> List[int]:
    """
    Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
    adding special tokens. A BioGPT sequence has the following format:

    - single sequence: `</s> X `
    - pair of sequences: `</s> A </s> B `

    Args:
        token_ids_0 (`List[int]`):
            List of IDs to which the special tokens will be added.
        token_ids_1 (`List[int]`, *optional*):
            Optional second list of IDs for sequence pairs.

    Returns:
        `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
    """
    if token_ids_1 is None:
        return [self.sep_token_id] + token_ids_0
    sep = [self.sep_token_id]
    return sep + token_ids_0 + sep + token_ids_1

mindnlp.transformers.models.biogpt.tokenization_biogpt.BioGptTokenizer.convert_tokens_to_string(tokens)

Converts a sequence of tokens (string) in a single string.

Source code in mindnlp/transformers/models/biogpt/tokenization_biogpt.py
355
356
357
358
359
360
361
362
def convert_tokens_to_string(self, tokens):
    """Converts a sequence of tokens (string) in a single string."""
    # remove BPE
    tokens = [t.replace(" ", "").replace("</w>", " ") for t in tokens]
    tokens = "".join(tokens).split()
    # detokenize
    text = self.moses_detokenize(tokens, self.lang)
    return text

mindnlp.transformers.models.biogpt.tokenization_biogpt.BioGptTokenizer.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. A FAIRSEQ Transformer sequence pair mask has the following format:

0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
| first sequence    | second sequence |

If token_ids_1 is None, this method only returns the first portion of the mask (0s).

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 token type IDs according to the given sequence(s).

Source code in mindnlp/transformers/models/biogpt/tokenization_biogpt.py
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
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. A FAIRSEQ
    Transformer sequence pair mask has the following format:

    ```
    0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
    | first sequence    | second sequence |
    ```

    If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).

    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 [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
    """
    sep = [self.sep_token_id]

    # no bos used in fairseq
    if token_ids_1 is None:
        return len(token_ids_0 + sep) * [0]
    return len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]

mindnlp.transformers.models.biogpt.tokenization_biogpt.BioGptTokenizer.get_special_tokens_mask(token_ids_0, token_ids_1=None, already_has_special_tokens=False)

Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer prepare_for_model method.

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

already_has_special_tokens

Whether or not the token list is already formatted with special tokens for the model.

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

RETURNS DESCRIPTION
List[int]

List[int]: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.

Source code in mindnlp/transformers/models/biogpt/tokenization_biogpt.py
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
def get_special_tokens_mask(
    self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
) -> List[int]:
    """
    Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
    special tokens using the tokenizer `prepare_for_model` method.

    Args:
        token_ids_0 (`List[int]`):
            List of IDs.
        token_ids_1 (`List[int]`, *optional*):
            Optional second list of IDs for sequence pairs.
        already_has_special_tokens (`bool`, *optional*, defaults to `False`):
            Whether or not the token list is already formatted with special tokens for the model.

    Returns:
        `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
    """
    if already_has_special_tokens:
        return super().get_special_tokens_mask(
            token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
        )
    # no bos used in fairseq
    if token_ids_1 is not None:
        return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1))
    return [1] + ([0] * len(token_ids_0))

mindnlp.transformers.models.biogpt.tokenization_biogpt.BioGptTokenizer.get_vocab()

Method to retrieve the vocabulary dictionary consisting of tokens and their corresponding encodings.

PARAMETER DESCRIPTION
self

The instance of the BioGptTokenizer class. It represents the tokenizer object.

TYPE: BioGptTokenizer

RETURNS DESCRIPTION
None

The method returns a vocabulary dictionary that contains tokens and their respective encodings.

Source code in mindnlp/transformers/models/biogpt/tokenization_biogpt.py
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
def get_vocab(self):
    """
    Method to retrieve the vocabulary dictionary consisting of tokens and their corresponding encodings.

    Args:
        self (BioGptTokenizer): The instance of the BioGptTokenizer class.
            It represents the tokenizer object.

    Returns:
        None: The method returns a vocabulary dictionary that contains tokens and their respective encodings.

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

mindnlp.transformers.models.biogpt.tokenization_biogpt.BioGptTokenizer.moses_detokenize(tokens, lang)

Performs Moses detokenization on a list of tokens for a specified language.

PARAMETER DESCRIPTION
self

An instance of the BioGptTokenizer class.

TYPE: BioGptTokenizer

tokens

A list of tokens to be detokenized.

TYPE: list

lang

The language of the tokens. Must be a supported language.

TYPE: str

RETURNS DESCRIPTION
None

The method modifies the cache_moses_detokenizer attribute of the BioGptTokenizer instance.

RAISES DESCRIPTION
KeyError

If the specified language is not supported.

TypeError

If the tokens parameter is not a list.

Note

This method utilizes a cache to store MosesDetokenizer objects for each language, ensuring efficient detokenization by reusing previously created instances.

Source code in mindnlp/transformers/models/biogpt/tokenization_biogpt.py
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
def moses_detokenize(self, tokens, lang):
    """
    Performs Moses detokenization on a list of tokens for a specified language.

    Args:
        self (BioGptTokenizer): An instance of the BioGptTokenizer class.
        tokens (list): A list of tokens to be detokenized.
        lang (str): The language of the tokens. Must be a supported language.

    Returns:
        None: The method modifies the cache_moses_detokenizer attribute of the BioGptTokenizer instance.

    Raises:
        KeyError: If the specified language is not supported.
        TypeError: If the tokens parameter is not a list.

    Note:
        This method utilizes a cache to store MosesDetokenizer objects for each language,
        ensuring efficient detokenization by reusing previously created instances.
    """
    if lang not in self.cache_moses_detokenizer:
        moses_detokenizer = self.sm.MosesDetokenizer(lang=lang)
        self.cache_moses_detokenizer[lang] = moses_detokenizer
    return self.cache_moses_detokenizer[lang].detokenize(tokens)

mindnlp.transformers.models.biogpt.tokenization_biogpt.BioGptTokenizer.moses_tokenize(text, lang)

Perform Moses tokenization on the given text.

PARAMETER DESCRIPTION
self

An instance of the BioGptTokenizer class.

TYPE: BioGptTokenizer

text

The text to be tokenized.

TYPE: str

lang

The language code for tokenization.

TYPE: str

RETURNS DESCRIPTION

None

RAISES DESCRIPTION
KeyError

If the language code is not found in the cache_moses_tokenizer dictionary.

ValueError

If the language code is invalid or unsupported.

Exception

If any other error occurs during tokenization.

This method utilizes the MosesTokenizer from the nltk.translate.moses package to tokenize the input text. It first checks if the MosesTokenizer for the specified language is already cached. If not, it creates a new MosesTokenizer instance for the language and adds it to the cache. The tokenization is then performed using the cached MosesTokenizer object.

The 'aggressive_dash_splits', 'return_str', and 'escape' parameters are passed to the tokenize method of the MosesTokenizer. 'aggressive_dash_splits' determines whether to perform aggressive dash splitting, 'return_str' specifies whether to return a string or a list of tokens, and 'escape' determines whether to escape XML/HTML characters in the text before tokenization.

Note

This method assumes that the BioGptTokenizer instance has been properly initialized with the necessary resources for tokenization.

Source code in mindnlp/transformers/models/biogpt/tokenization_biogpt.py
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
def moses_tokenize(self, text, lang):
    """
    Perform Moses tokenization on the given text.

    Args:
        self (BioGptTokenizer): An instance of the BioGptTokenizer class.
        text (str): The text to be tokenized.
        lang (str): The language code for tokenization.

    Returns:
        None

    Raises:
        KeyError: If the language code is not found in the cache_moses_tokenizer dictionary.
        ValueError: If the language code is invalid or unsupported.
        Exception: If any other error occurs during tokenization.

    This method utilizes the MosesTokenizer from the nltk.translate.moses package to tokenize the input text.
    It first checks if the MosesTokenizer for the specified language is already cached.
    If not, it creates a new MosesTokenizer instance for the language and adds it to the cache.
    The tokenization is then performed using the cached MosesTokenizer object.

    The 'aggressive_dash_splits', 'return_str', and 'escape' parameters are passed to the tokenize method of
    the MosesTokenizer.
    'aggressive_dash_splits' determines whether to perform aggressive dash splitting,
    'return_str' specifies whether to return a string or a list of tokens,
    and 'escape' determines whether to escape XML/HTML characters in the text before tokenization.

    Note:
        This method assumes that the BioGptTokenizer instance has been properly initialized with the necessary
        resources for tokenization.
    """
    if lang not in self.cache_moses_tokenizer:
        moses_tokenizer = self.sm.MosesTokenizer(lang=lang)
        self.cache_moses_tokenizer[lang] = moses_tokenizer
    return self.cache_moses_tokenizer[lang].tokenize(
        text, aggressive_dash_splits=True, return_str=False, escape=True
    )

mindnlp.transformers.models.biogpt.tokenization_biogpt.BioGptTokenizer.save_vocabulary(save_directory, filename_prefix=None)

Save the vocabulary to the specified directory with the given filename prefix.

PARAMETER DESCRIPTION
self

Instance of the BioGptTokenizer class.

save_directory

The directory path where the vocabulary files will be saved. It should already exist, and the method will raise an error if the directory does not exist.

TYPE: str

filename_prefix

An optional prefix to be added to the filenames of the vocabulary files. If provided, the filenames will be prefixed with this value. Default is None.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION
Tuple[str]

Tuple[str]: A tuple containing the paths to the saved vocabulary file and merge file.

RAISES DESCRIPTION
OSError

If the specified save_directory is not a valid directory.

IOError

If there is an issue writing the vocabulary files to the disk.

Source code in mindnlp/transformers/models/biogpt/tokenization_biogpt.py
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
    """
    Save the vocabulary to the specified directory with the given filename prefix.

    Args:
        self: Instance of the BioGptTokenizer class.
        save_directory (str): The directory path where the vocabulary files will be saved.
            It should already exist, and the method will raise an error if the directory does not exist.
        filename_prefix (Optional[str]): An optional prefix to be added to the filenames of the vocabulary files.
            If provided, the filenames will be prefixed with this value. Default is None.

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

    Raises:
        OSError: If the specified save_directory is not a valid directory.
        IOError: If there is an issue writing the vocabulary files to the disk.
    """
    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:
        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