自定义层和工具
本页面列出了库中使用的所有自定义层,以及它为建模提供的实用函数。
大多数这些内容只有在您研究库中模型的代码时才有用。
Pytorch 自定义模块
由Radford等人为OpenAI GPT定义的一维卷积层(也在GPT-2中使用)。
基本上像一个线性层一样工作,但权重是转置的。
类 transformers.modeling_utils.PoolerStartLogits
< source >( config: PretrainedConfig )
参数
- config (PretrainedConfig) —
模型使用的配置,将用于获取模型的
hidden_size
。
从序列隐藏状态计算SQuAD起始logits。
前进
< source >( hidden_states: FloatTensor p_mask: typing.Optional[torch.FloatTensor] = None ) → torch.FloatTensor
class transformers.modeling_utils.PoolerEndLogits
< source >( config: PretrainedConfig )
参数
- config (PretrainedConfig) —
模型使用的配置,将用于获取模型的
hidden_size
和要使用的layer_norm_eps
。
从序列隐藏状态计算SQuAD结束logits。
前进
< source >( hidden_states: FloatTensor start_states: typing.Optional[torch.FloatTensor] = None start_positions: typing.Optional[torch.LongTensor] = None p_mask: typing.Optional[torch.FloatTensor] = None ) → torch.FloatTensor
参数
- hidden_states (
torch.FloatTensor
of shape(batch_size, seq_len, hidden_size)
) — 模型的最终隐藏状态。 - start_states (
torch.FloatTensor
of shape(batch_size, seq_len, hidden_size)
, optional) — 标记跨度的第一个标记的隐藏状态。 - start_positions (
torch.LongTensor
of shape(batch_size,)
, optional) — 标记跨度的第一个标记的位置。 - p_mask (
torch.FloatTensor
of shape(batch_size, seq_len)
, optional) — 用于无效位置(如查询和特殊符号(PAD, SEP, CLS))的标记的掩码。1.0 表示标记应被掩码。
返回
torch.FloatTensor
SQuAD的最终logits。
start_states
或 start_positions
中的一个不应为 None
。如果两者都设置了,start_positions
会覆盖 start_states
。
类 transformers.modeling_utils.PoolerAnswerClass
< source >( config )
参数
- config (PretrainedConfig) —
模型使用的配置,将用于获取模型的
hidden_size
。
从分类和起始标记的隐藏状态计算SQuAD 2.0答案类别。
前进
< source >( hidden_states: FloatTensor start_states: typing.Optional[torch.FloatTensor] = None start_positions: typing.Optional[torch.LongTensor] = None cls_index: typing.Optional[torch.LongTensor] = None ) → torch.FloatTensor
参数
- hidden_states (
torch.FloatTensor
of shape(batch_size, seq_len, hidden_size)
) — 模型的最终隐藏状态。 - start_states (
torch.FloatTensor
of shape(batch_size, seq_len, hidden_size)
, optional) — 标记跨度的第一个标记的隐藏状态。 - start_positions (
torch.LongTensor
of shape(batch_size,)
, optional) — 标记跨度的第一个标记的位置。 - cls_index (
torch.LongTensor
of shape(batch_size,)
, optional) — 批次中每个句子的CLS标记的位置。如果为None
,则取最后一个标记。
返回
torch.FloatTensor
SQuAD 2.0 答案类。
start_states
或 start_positions
中的一个不应为 None
。如果两者都设置了,start_positions
会覆盖 start_states
。
类 transformers.modeling_utils.SquadHeadOutput
< source >( loss: typing.Optional[torch.FloatTensor] = None start_top_log_probs: typing.Optional[torch.FloatTensor] = None start_top_index: typing.Optional[torch.LongTensor] = None end_top_log_probs: typing.Optional[torch.FloatTensor] = None end_top_index: typing.Optional[torch.LongTensor] = None cls_logits: typing.Optional[torch.FloatTensor] = None )
参数
- loss (
torch.FloatTensor
形状为(1,)
, 可选, 如果同时提供了start_positions
和end_positions
则返回) — 分类损失,作为起始标记、结束标记(以及如果提供了 is_impossible)分类损失的总和。 - start_top_log_probs (
torch.FloatTensor
of shape(batch_size, config.start_n_top)
, optional, returned ifstart_positions
orend_positions
is not provided) — 用于前config.start_n_top个起始标记可能性的对数概率(beam-search)。 - start_top_index (
torch.LongTensor
of shape(batch_size, config.start_n_top)
, optional, returned ifstart_positions
orend_positions
is not provided) — 用于前 config.start_n_top 个开始标记可能性的索引(beam-search)。 - end_top_log_probs (
torch.FloatTensor
形状为(batch_size, config.start_n_top * config.end_n_top)
, 可选, 如果未提供start_positions
或end_positions
时返回) — 前config.start_n_top * config.end_n_top
个结束标记可能性的对数概率 (beam-search). - end_top_index (
torch.LongTensor
of shape(batch_size, config.start_n_top * config.end_n_top)
, optional, 如果未提供start_positions
或end_positions
则返回) — 表示前config.start_n_top * config.end_n_top
个结束标记可能性的索引(beam-search)。 - cls_logits (
torch.FloatTensor
of shape(batch_size,)
, 可选, 如果未提供start_positions
或end_positions
时返回) — 答案的is_impossible
标签的对数概率.
使用SQuADHead的问答模型输出的基类。
类 transformers.modeling_utils.SQuADHead
< source >( config )
参数
- config (PretrainedConfig) —
模型使用的配置,将用于获取模型的
hidden_size
和要使用的layer_norm_eps
。
一个受XLNet启发的SQuAD头。
前进
< source >( hidden_states: FloatTensor start_positions: typing.Optional[torch.LongTensor] = None end_positions: typing.Optional[torch.LongTensor] = None cls_index: typing.Optional[torch.LongTensor] = None is_impossible: typing.Optional[torch.LongTensor] = None p_mask: typing.Optional[torch.FloatTensor] = None return_dict: bool = False ) → transformers.modeling_utils.SquadHeadOutput 或 tuple(torch.FloatTensor)
参数
- hidden_states (
torch.FloatTensor
of shape(batch_size, seq_len, hidden_size)
) — 模型在序列标记上的最终隐藏状态。 - start_positions (
torch.LongTensor
of shape(batch_size,)
, optional) — 标记跨度的第一个标记的位置。 - end_positions (
torch.LongTensor
of shape(batch_size,)
, optional) — 标记跨度的最后一个标记的位置。 - cls_index (
torch.LongTensor
of shape(batch_size,)
, optional) — 批次中每个句子的CLS标记的位置。如果为None
,则取最后一个标记。 - is_impossible (
torch.LongTensor
of shape(batch_size,)
, optional) — 问题在段落中是否有可能的答案。 - p_mask (
torch.FloatTensor
of shape(batch_size, seq_len)
, optional) — 用于无效位置(如查询和特殊符号(PAD, SEP, CLS))的标记的掩码。1.0 表示标记应被掩码。 - return_dict (
bool
, 可选, 默认为False
) — 是否返回一个 ModelOutput 而不是一个普通的元组。
返回
transformers.modeling_utils.SquadHeadOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_utils.SquadHeadOutput 或一个由
torch.FloatTensor
组成的元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),包含各种
元素,具体取决于配置(
)和输入。
- loss (
torch.FloatTensor
形状为(1,)
,可选,如果提供了start_positions
和end_positions
则返回) — 分类损失,作为起始标记、结束标记(以及如果提供了is_impossible
)分类损失的总和。 - start_top_log_probs (
torch.FloatTensor
形状为(batch_size, config.start_n_top)
,可选,如果未提供start_positions
或end_positions
则返回) — 前config.start_n_top
个起始标记可能性的对数概率(beam-search)。 - start_top_index (
torch.LongTensor
形状为(batch_size, config.start_n_top)
,可选,如果未提供start_positions
或end_positions
则返回) — 前config.start_n_top
个起始标记可能性的索引(beam-search)。 - end_top_log_probs (
torch.FloatTensor
形状为(batch_size, config.start_n_top * config.end_n_top)
,可选,如果未提供start_positions
或end_positions
则返回) — 前config.start_n_top * config.end_n_top
个结束标记可能性的对数概率(beam-search)。 - end_top_index (
torch.LongTensor
形状为(batch_size, config.start_n_top * config.end_n_top)
,可选,如果未提供start_positions
或end_positions
则返回) — 前config.start_n_top * config.end_n_top
个结束标记可能性的索引(beam-search)。 - cls_logits (
torch.FloatTensor
形状为(batch_size,)
,可选,如果未提供start_positions
或end_positions
则返回) — 答案的is_impossible
标签的对数概率。
类 transformers.modeling_utils.SequenceSummary
< source >( config: PretrainedConfig )
参数
- config (PretrainedConfig) —
The config used by the model. Relevant arguments in the config class of the model are (refer to the actual
config class of your model for the default values it uses):
-
summary_type (
str
) — 用于生成此摘要的方法。接受的值为:"last"
— Take the last token hidden state (like XLNet)"first"
— Take the first token hidden state (like Bert)"mean"
— Take the mean of all tokens hidden states"cls_index"
— Supply a Tensor of classification token position (GPT/GPT-2)"attn"
— Not implemented now, use multi-head attention
-
summary_use_proj (
bool
) — 在向量提取后添加投影。 -
summary_proj_to_labels (
bool
) — 如果为True
,则投影输出到config.num_labels
类别 (否则输出到config.hidden_size
)。 -
summary_activation (
Optional[str]
) — 设置为"tanh"
以在输出中添加 tanh 激活函数, 其他字符串或None
将不添加激活函数。 -
summary_first_dropout (
float
) — 在投影和激活之前的可选丢弃概率。 -
summary_last_dropout (
float
)— 投影和激活后的可选丢弃概率。
-
计算序列隐藏状态的单一向量摘要。
前进
< source >( hidden_states: FloatTensor cls_index: typing.Optional[torch.LongTensor] = None ) → torch.FloatTensor
计算序列隐藏状态的单个向量摘要。
PyTorch 辅助函数
transformers.apply_chunking_to_forward
< source >( forward_fn: Callable[..., torch.Tensor] chunk_size: int chunk_dim: int *input_tensors ) → torch.Tensor
此函数将input_tensors
在维度chunk_dim
上分割成大小为chunk_size
的较小输入张量部分。然后,它独立地对每个部分应用层forward_fn
以节省内存。
如果 forward_fn
在 chunk_dim
上是独立的,这个函数将产生与直接将 forward_fn
应用于 input_tensors
相同的结果。
示例:
# rename the usual forward() fn to forward_chunk()
def forward_chunk(self, hidden_states):
hidden_states = self.decoder(hidden_states)
return hidden_states
# implement a chunked forward function
def forward(self, hidden_states):
return apply_chunking_to_forward(self.forward_chunk, self.chunk_size_lm_head, self.seq_len_dim, hidden_states)
transformers.pytorch_utils.find_pruneable_heads_and_indices
< source >( heads: List[int] n_heads: int head_size: int already_pruned_heads: Set[int] ) → Tuple[Set[int], torch.LongTensor]
找到头部及其索引,考虑already_pruned_heads
。
transformers.prune_layer
< source >( 层: Union[nn.Linear, Conv1D] 索引: torch.LongTensor 维度: Optional[int] = None ) → torch.nn.Linear
或 Conv1D
参数
- layer (
Union[torch.nn.Linear, Conv1D]
) — 要修剪的层. - index (
torch.LongTensor
) — 要在层中保留的索引。 - dim (
int
, 可选) — 保留索引的维度。
返回
torch.nn.Linear
或 Conv1D
修剪后的层作为一个新层,具有requires_grad=True
。
修剪Conv1D或线性层,只保留索引中的条目。
用于移除头部。
transformers.pytorch_utils.prune_conv1d_layer
< source >( 层: Conv1D 索引: torch.LongTensor 维度: int = 1 ) → Conv1D
修剪一个Conv1D层,只保留索引中的条目。Conv1D像一个线性层一样工作(例如BERT),但权重是转置的。
用于移除头部。
transformers.pytorch_utils.prune_linear_layer
< source >( 层: nn.Linear 索引: torch.LongTensor 维度: int = 0 ) → torch.nn.Linear
修剪线性层以仅保留索引中的条目。
用于移除头部。
TensorFlow 自定义层
类 transformers.modeling_tf_utils.TFConv1D
< source >( nf nx initializer_range = 0.02 **kwargs )
由Radford等人为OpenAI GPT定义的一维卷积层(也在GPT-2中使用)。
基本上像一个线性层一样工作,但权重是转置的。
类 transformers.TFSequenceSummary
< source >( config: PretrainedConfig initializer_range: float = 0.02 **kwargs )
参数
- config (PretrainedConfig) —
The config used by the model. Relevant arguments in the config class of the model are (refer to the actual
config class of your model for the default values it uses):
-
summary_type (
str
) — 用于生成此摘要的方法。接受的值为:"last"
— Take the last token hidden state (like XLNet)"first"
— Take the first token hidden state (like Bert)"mean"
— Take the mean of all tokens hidden states"cls_index"
— Supply a Tensor of classification token position (GPT/GPT-2)"attn"
— Not implemented now, use multi-head attention
-
summary_use_proj (
bool
) — 在向量提取后添加投影。 -
summary_proj_to_labels (
bool
) — 如果为True
,则投影输出到config.num_labels
类别 (否则输出到config.hidden_size
)。 -
summary_activation (
Optional[str]
) — 设置为"tanh"
以在输出中添加 tanh 激活函数, 其他字符串或None
将不添加激活函数。 -
summary_first_dropout (
float
) — 在投影和激活之前的可选丢弃概率。 -
summary_last_dropout (
float
)— 投影和激活后的可选丢弃概率。
-
- initializer_range (
float
, optional, 默认为 0.02) — 用于初始化权重的标准差. - kwargs (
Dict[str, Any]
, 可选) — 传递给keras.layers.Layer
的__init__
的额外关键字参数。
计算序列隐藏状态的单个向量摘要。
TensorFlow 损失函数
适用于因果语言建模(CLM)的损失函数,即猜测下一个标记的任务。
任何标签为-100的将在损失计算中被忽略(连同相应的logits)。
适用于掩码语言建模(MLM)的损失函数,即猜测被掩码标记的任务。
任何标签为-100的将在损失计算中被忽略(连同相应的logits)。
适用于多项选择任务的损失函数。
适用于问答的损失函数。
适用于序列分类的损失函数。
适用于标记分类的损失函数。
任何标签为-100的将在损失计算中被忽略(连同相应的logits)。
TensorFlow 辅助函数
transformers.modeling_tf_utils.get_initializer
< source >( initializer_range: float = 0.02 ) → keras.initializers.TruncatedNormal
创建一个具有给定范围的keras.initializers.TruncatedNormal
。
transformers.modeling_tf_utils.keras_serializable
< source >( )
装饰一个Keras Layer类以支持Keras序列化。
这是通过以下方式完成的:
- 在
get_config
中的Keras配置字典中添加一个transformers_config
字典(在序列化时由Keras调用)。 - 包装
__init__
以接受transformers_config
字典(在反序列化时由 Keras 传递)并将其转换为实际层初始化器的配置对象。 - 在Keras中将类注册为自定义对象(如果Tensorflow版本支持此功能),这样就不需要在调用
keras.models.load_model
时在custom_objects
中提供它。
transformers.shape_list
< source >( tensor: typing.Union[tensorflow.python.framework.tensor.Tensor, numpy.ndarray] ) → List[int]
在tensorflow中干净地处理动态形状。