modeling

class CTRLModel(vocab_size=246534, max_position_embeddings=50000, hidden_size=1280, intermediate_size=8192, num_hidden_layers=48, num_attention_heads=16, resid_pdrop=0.1, embd_pdrop=0.1, layer_norm_epsilon=1e-06, tie_word_embeddings=True, pad_token_id=None, initializer_range=0.02)[源代码]

基类:paddlenlp.transformers.ctrl.modeling.CTRLPreTrainedModel

The bare CTRL Model transformer outputting raw hidden-states without any specific head on top.

This model inherits from PretrainedModel. Refer to the superclass documentation for the generic methods.

This model is also a Paddle paddle.nn.Layer subclass. Use it as a regular Paddle Layer and refer to the Paddle documentation for all matter related to general usage and behavior.

参数
  • vocab_size (int, optional) -- Vocabulary size of inputs_ids in CTRLModel. Also is the vocab size of token embedding matrix. Defines the number of different tokens that can be represented by the inputs_ids passed when calling CTRLModel. Defaults to 246534.

  • max_position_embeddings (int, optional) -- 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 or 50000). Defaults to 50000.

  • hidden_size (int, optional) -- Dimensionality of the embeddings and hidden states. Defaults to 1280.

  • intermediate_size (int, optional) -- Dimensionality of the inner dimension of the feed forward networks (FFN). Defaults to 8192.

  • num_hidden_layers (int, optional) -- Number of hidden layers in the Transformer encoder. Defaults to 48.

  • num_attention_heads (int, optional) -- Number of attention heads for each attention layer in the Transformer encoder. Defaults to 16.

  • resid_pdrop (float, optional) -- The dropout ratio for all fully connected layers in the encoder. Defaults to 0.1.

  • embd_pdrop (float, optional) -- The dropout ratio for the embeddings. Defaults to 0.1.

  • layer_norm_epsilon (float, optional) -- The epsilon to use in the layer normalization layers. Defaults to 1e-6.

  • tie_word_embeddings (bool, optional) -- Whether the model's input and output word embeddings should be tied. Note that this is only relevant if the model has a output word embedding layer. Defaults to True.

  • pad_token_id (bool, optional) -- The id of the padding token. Defaults to None.

  • initializer_range (float, optional) --

    The standard deviation of the normal initializer. Defaults to 0.02.

    注解

    A normal_initializer initializes weight matrices as normal distributions. See CTRLPreTrainedModel._init_weights() for how weights are initialized in CTRLModel.

forward(input_ids=None, cache=None, attention_mask=None, token_type_ids=None, position_ids=None, use_cache=False, output_attentions=False, output_hidden_states=False)[源代码]

The CTRLModel forward method, overrides the __call__() special method.

参数
  • input_ids (Tensor) -- Indices of input sequence tokens in the vocabulary. They are numerical representations of tokens that build the input sequence. Its data type should be int64 and it has a shape of [batch_size, sequence_length].

  • cache (Tuple[Tuple[Tensor]], optional) -- Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model. Can be used to speed up sequential decoding. The input_ids which have their past given to this model should not be passed as input ids as they have already been computed. Defaults to None.

  • attention_mask (Tensor, optional) -- Mask used in multi-head attention to avoid performing attention on to some unwanted positions, usually the paddings or the subsequent positions. Its data type can be int, float and bool. When the data type is bool, the masked tokens have False values and the others have True values. When the data type is int, the masked tokens have 0 values and the others have 1 values. When the data type is float, the masked tokens have 0.0 values and the others have 1.0 values. It is a tensor with shape broadcasted to [batch_size, num_attention_heads, sequence_length, sequence_length]. Defaults to None, which means nothing needed to be prevented attention to.

  • token_type_ids (Tensor, optional) --

    Segment token indices to indicate different portions of the inputs. Selected in the range [0, type_vocab_size - 1]. If type_vocab_size is 2, which means the inputs have two portions. Indices can either be 0 or 1:

    • 0 corresponds to a sentence A token,

    • 1 corresponds to a sentence B token.

    Its data type should be int64 and it has a shape of [batch_size, sequence_length]. Defaults to None, which means we don't add segment embeddings.

  • position_ids (Tensor, optional) -- Indices of positions of each input sequence tokens in the position embeddings. Selected in the range [0, max_position_embeddings - 1]. Shape as [batch_size, num_tokens] and dtype as int64. Defaults to None.

  • use_cache (bool, optional) -- Whether or not to use cache. Defaults to False. If set to True, key value states will be returned and can be used to speed up decoding.

  • output_attentions (bool, optional) -- Whether or not to return the attentions tensors of all attention layers. Defaults to False.

  • output_hidden_states (bool, optional) -- Whether or not to return the output of all hidden layers. Defaults to False.

返回

Returns tuple (last_hidden_state, caches, hidden_states, attentions)

With the fields:

  • last_hidden_state (Tensor):

    Sequence of hidden-states at the last layer of the model. It's data type should be float32 and its shape is [batch_size, sequence_length, hidden_size].

  • caches (tuple(tuple(Tensor), optional):

    returned when use_cache=True is passed. Tuple of tuple(Tensor) of length num_hidden_layers, with each tuple having 2 tensors of shape [batch_size, num_heads, sequence_length, embed_size_per_head] and float32 dtype.

  • hidden_states (tuple(Tensor), optional):

    returned when output_hidden_states=True is passed. Tuple of Tensor (one for the output of the embeddings + one for the output of each layer). Each Tensor has a data type of float32 and its shape is [batch_size, sequence_length, hidden_size].

  • attentions (tuple(Tensor), optional):

    returned when output_attentions=True is passed. Tuple of Tensor (one for each layer) of shape. Each Tensor has a data type of float32 and its shape is [batch_size, num_heads, sequence_length, sequence_length].

返回类型

tuple

示例

import paddle
from paddlenlp.transformers import CTRLModel, CTRLTokenizer

tokenizer = CTRLTokenizer.from_pretrained('ctrl')
model = CTRLModel.from_pretrained('ctrl')

inputs = tokenizer("Welcome to use PaddlePaddle and PaddleNLP!")
inputs = {k:paddle.to_tensor([v]) for (k, v) in inputs.items()}
output = model(**inputs)
class CTRLLMHeadModel(ctrl)[源代码]

基类:paddlenlp.transformers.ctrl.modeling.CTRLPreTrainedModel

The CTRL Model transformer with a language modeling head on top (linear layer with weights tied to the input embeddings).

参数

ctrl (CTRLModel) -- An instance of CTRLModel.

forward(input_ids=None, cache=None, attention_mask=None, token_type_ids=None, position_ids=None, labels=None, use_cache=False, output_attentions=False, output_hidden_states=False)[源代码]
参数
  • input_ids (Tensor) -- See CTRLModel.

  • cache (Tensor, optional) -- See CTRLModel.

  • attention_mask (Tensor, optional) -- See CTRLModel.

  • token_type_ids (Tensor, optional) -- See CTRLModel.

  • position_ids (Tensor, optional) -- See CTRLModel.

  • labels (Tensor, 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, ..., vocab_size] All labels set to -100 are ignored (masked), the loss is only computed for labels in [0, ..., vocab_size]. Shape is [batch_size, sequence_length] and dtype is int64.

  • use_cache (bool, optional) -- See CTRLModel.

  • output_attentions (bool, optional) -- See CTRLModel.

  • output_hidden_states (bool, optional) -- See CTRLModel.

返回

Returns tuple (loss, logits, caches, hidden_states, attentions). With the fields:

  • loss (Tensor):

    returned when labels is provided. Language modeling loss (for next-token prediction). It's data type should be float32 and its shape is [1,].

  • logits (Tensor):

    Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). It's data type should be float32 and its shape is [batch_size, sequence_length, vocab_size].

  • caches (tuple(tuple(Tensor), optional):

    See CTRLModel.

  • hidden_states (tuple(Tensor), optional):

    See CTRLModel.

  • attentions (tuple(Tensor), optional):

    See CTRLModel.

返回类型

tuple

示例

import paddle
from paddlenlp.transformers import CTRLLMHeadModel, CTRLTokenizer

tokenizer = CTRLTokenizer.from_pretrained('ctrl')
model = CTRLLMHeadModel.from_pretrained('ctrl')

inputs = tokenizer("Welcome to use PaddlePaddle and PaddleNLP!")
inputs = {k:paddle.to_tensor([v]) for (k, v) in inputs.items()}
output = model(**inputs, labels=inputs["input_ids"])

loss = output[0]
logits = output[1]
class CTRLForSequenceClassification(ctrl, num_classes=2, dropout=None)[源代码]

基类:paddlenlp.transformers.ctrl.modeling.CTRLPreTrainedModel

The CTRL Model transformer with a sequence classification head on top (linear layer). CTRLForSequenceClassification uses the last token in order to do the classification, as other causal models (e.g. GPT-2) do. Since it does classification on the last token, it requires to know the position of the last token. If a pad_token_id is defined in the configuration, it finds the last token that is not a padding token in each row. If no pad_token_id is defined, it simply takes the last value in each row of the batch.

参数
  • ctrl (CTRLModel) -- An instance of CTRLModel.

  • num_classes (int, optional) -- The number of classes. Defaults to 2.

  • dropout (float, optional) -- The dropout probability for output of CTRL. If None, use the same value as hidden_dropout_prob of CTRLModel instance ctrl. Defaults to None.

forward(input_ids=None, cache=None, attention_mask=None, token_type_ids=None, position_ids=None, labels=None, use_cache=False, output_attentions=False, output_hidden_states=False)[源代码]
参数
  • input_ids (Tensor) -- See CTRLModel.

  • cache (Tensor, optional) -- See CTRLModel.

  • attention_mask (Tensor, optional) -- See CTRLModel.

  • token_type_ids (Tensor, optional) -- See CTRLModel.

  • position_ids (Tensor, optional) -- See CTRLModel.

  • labels (Tensor, optional) -- Labels for computing the sequence classification/regression loss. Indices should be in [0, ...,num_classes - 1]. If num_classes == 1 a regression loss is computed (Mean-Square loss), If num_classes > 1 a classification loss is computed (Cross-Entropy). Shape is [batch_size,] and dtype is int64.

  • use_cache (bool, optional) -- See CTRLModel.

  • output_attentions (bool, optional) -- See CTRLModel.

  • output_hidden_states (bool, optional) -- See CTRLModel.

返回

Returns tuple (loss, logits, caches, hidden_states, attentions). With the fields:

  • loss (Tensor):

    returned when labels is provided. Language modeling loss (for next-token prediction). It's data type should be float32 and its shape is [1,].

  • logits (Tensor):

    Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax). It's data type should be float32 and its shape is [batch_size, num_classes].

  • caches (tuple(tuple(Tensor), optional):

    See CTRLModel.

  • hidden_states (tuple(Tensor), optional):

    See CTRLModel.

  • attentions (tuple(Tensor), optional):

    See CTRLModel.

返回类型

tuple

示例

import paddle
from paddlenlp.transformers import CTRLForSequenceClassification, CTRLTokenizer

tokenizer = CTRLTokenizer.from_pretrained('ctrl')
model = CTRLForSequenceClassification.from_pretrained('ctrl', pad_token_id=0)

inputs = tokenizer("Welcome to use PaddlePaddle and PaddleNLP!")
inputs = {k:paddle.to_tensor([v]) for (k, v) in inputs.items()}
output = model(**inputs, labels=paddle.to_tensor([1]))

loss = output[0]
logits = output[1]
class SinusoidalPositionalEmbedding(num_embeddings, embedding_dim)[源代码]

基类:paddle.nn.layer.common.Embedding

This module produces sinusoidal positional embeddings of any length.

forward(position_ids)[源代码]

Defines the computation performed at every call. Should be overridden by all subclasses.

参数
  • *inputs (tuple) -- unpacked tuple arguments

  • **kwargs (dict) -- unpacked dict arguments

CTRLForCausalLM

alias of paddlenlp.transformers.ctrl.modeling.CTRLLMHeadModel