modeling#

class CTRLPreTrainedModel(*args, **kwargs)[源代码]#

基类:PretrainedModel

An abstract class for pretrained CTRL models. It provides CTRL related model_config_file, resource_files_names, pretrained_resource_files_map, pretrained_init_configuration, base_model_prefix for downloading and loading pretrained models. See PretrainedModel for more details.

config_class#

CTRLConfig 的别名

base_model_class#

CTRLModel 的别名

class CTRLModel(config: CTRLConfig)[源代码]#

基类: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.

参数:

config (CTRLConfig) --

An instance of CTRLConfig.

备注

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

get_input_embeddings()[源代码]#

get input embedding of model

返回:

embedding of model

返回类型:

nn.Embedding

set_input_embeddings(new_embeddings)[源代码]#

set new input embedding for model

参数:

value (Embedding) -- the new embedding of model

抛出:

NotImplementedError -- Model has not implement set_input_embeddings method

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(config: CTRLConfig)[源代码]#

基类:CTRLPreTrainedModel

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

参数:

config (CTRLConfig) -- An instance of CTRLConfig.

get_output_embeddings()[源代码]#

To be overwrited for models with output embeddings

返回:

the otuput embedding of model

返回类型:

Optional[Embedding]

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(config: CTRLConfig)[源代码]#

基类: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.

参数:

config (CTRLConfig) -- An instance of CTRLConfig.

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)[源代码]#

基类: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#

CTRLLMHeadModel 的别名