CSS-LM
237 строк · 11.3 Кб
1# coding=utf-8
2# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
3# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16""" XLNet configuration """
17
18import logging
19import warnings
20
21from .configuration_utils import PretrainedConfig
22
23
24logger = logging.getLogger(__name__)
25
26XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP = {
27"xlnet-base-cased": "https://s3.amazonaws.com/models.huggingface.co/bert/xlnet-base-cased-config.json",
28"xlnet-large-cased": "https://s3.amazonaws.com/models.huggingface.co/bert/xlnet-large-cased-config.json",
29}
30
31
32class XLNetConfig(PretrainedConfig):
33"""
34This is the configuration class to store the configuration of a :class:`~transformers.XLNetModel`.
35It is used to instantiate an XLNet model according to the specified arguments, defining the model
36architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of
37the `xlnet-large-cased <https://huggingface.co/xlnet-large-cased>`__ architecture.
38
39Configuration objects inherit from :class:`~transformers.PretrainedConfig` and can be used
40to control the model outputs. Read the documentation from :class:`~transformers.PretrainedConfig`
41for more information.
42
43Args:
44vocab_size (:obj:`int`, optional, defaults to 32000):
45Vocabulary size of the XLNet model. Defines the different tokens that
46can be represented by the `inputs_ids` passed to the forward method of :class:`~transformers.XLNetModel`.
47d_model (:obj:`int`, optional, defaults to 1024):
48Dimensionality of the encoder layers and the pooler layer.
49n_layer (:obj:`int`, optional, defaults to 24):
50Number of hidden layers in the Transformer encoder.
51n_head (:obj:`int`, optional, defaults to 16):
52Number of attention heads for each attention layer in the Transformer encoder.
53d_inner (:obj:`int`, optional, defaults to 4096):
54Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
55ff_activation (:obj:`string`, optional, defaults to "gelu"):
56The non-linear activation function (function or string) in the
57encoder and pooler. If string, "gelu", "relu" and "swish" are supported.
58untie_r (:obj:`boolean`, optional, defaults to :obj:`True`):
59Untie relative position biases
60attn_type (:obj:`string`, optional, defaults to "bi"):
61The attention type used by the model. Set 'bi' for XLNet, 'uni' for Transformer-XL.
62initializer_range (:obj:`float`, optional, defaults to 0.02):
63The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
64layer_norm_eps (:obj:`float`, optional, defaults to 1e-12):
65The epsilon used by the layer normalization layers.
66dropout (:obj:`float`, optional, defaults to 0.1):
67The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
68mem_len (:obj:`int` or :obj:`None`, optional, defaults to :obj:`None`):
69The number of tokens to cache. The key/value pairs that have already been pre-computed
70in a previous forward pass won't be re-computed. See the
71`quickstart <https://huggingface.co/transformers/quickstart.html#using-the-past>`__
72for more information.
73reuse_len (:obj:`int` or :obj:`None`, optional, defaults to :obj:`None`):
74The number of tokens in the current batch to be cached and reused in the future.
75bi_data (:obj:`boolean`, optional, defaults to :obj:`False`):
76Whether to use bidirectional input pipeline. Usually set to `True` during
77pretraining and `False` during finetuning.
78clamp_len (:obj:`int`, optional, defaults to -1):
79Clamp all relative distances larger than clamp_len.
80Setting this attribute to -1 means no clamping.
81same_length (:obj:`boolean`, optional, defaults to :obj:`False`):
82Whether to use the same attention length for each token.
83summary_type (:obj:`string`, optional, defaults to "last"):
84Argument used when doing sequence summary. Used in for the multiple choice head in
85:class:transformers.XLNetForSequenceClassification` and :class:`~transformers.XLNetForMultipleChoice`.
86Is one of the following options:
87
88- 'last' => take the last token hidden state (like XLNet)
89- 'first' => take the first token hidden state (like Bert)
90- 'mean' => take the mean of all tokens hidden states
91- 'cls_index' => supply a Tensor of classification token position (GPT/GPT-2)
92- 'attn' => Not implemented now, use multi-head attention
93summary_use_proj (:obj:`boolean`, optional, defaults to :obj:`True`):
94Argument used when doing sequence summary. Used in for the multiple choice head in
95:class:`~transformers.XLNetForSequenceClassification` and :class:`~transformers.XLNetForMultipleChoice`.
96Add a projection after the vector extraction
97summary_activation (:obj:`string` or :obj:`None`, optional, defaults to :obj:`None`):
98Argument used when doing sequence summary. Used in for the multiple choice head in
99:class:`~transformers.XLNetForSequenceClassification` and :class:`~transformers.XLNetForMultipleChoice`.
100'tanh' => add a tanh activation to the output, Other => no activation.
101summary_proj_to_labels (:obj:`boolean`, optional, defaults to :obj:`True`):
102Argument used when doing sequence summary. Used in for the multiple choice head in
103:class:`~transformers.XLNetForSequenceClassification` and :class:`~transformers.XLNetForMultipleChoice`.
104If True, the projection outputs to config.num_labels classes (otherwise to hidden_size). Default: False.
105summary_last_dropout (:obj:`float`, optional, defaults to 0.1):
106Argument used when doing sequence summary. Used in for the multiple choice head in
107:class:`~transformers.XLNetForSequenceClassification` and :class:`~transformers.XLNetForMultipleChoice`.
108Add a dropout after the projection and activation
109start_n_top (:obj:`int`, optional, defaults to 5):
110Used in the SQuAD evaluation script for XLM and XLNet.
111end_n_top (:obj:`int`, optional, defaults to 5):
112Used in the SQuAD evaluation script for XLM and XLNet.
113use_cache (:obj:`bool`, `optional`, defaults to :obj:`True`):
114Whether or not the model should return the last pre-computed hidden states.
115
116.. note::
117This flag behaves differently from with other models: it just controls the inference behavior, during
118training the model always uses ``use_cache=True``.
119
120Example::
121
122>>> from transformers import XLNetConfig, XLNetModel
123
124>>> # Initializing a XLNet configuration
125>>> configuration = XLNetConfig()
126
127>>> # Initializing a model from the configuration
128>>> model = XLNetModel(configuration)
129
130>>> # Accessing the model configuration
131>>> configuration = model.config
132"""
133
134model_type = "xlnet"
135
136def __init__(
137self,
138vocab_size=32000,
139d_model=1024,
140n_layer=24,
141n_head=16,
142d_inner=4096,
143ff_activation="gelu",
144untie_r=True,
145attn_type="bi",
146initializer_range=0.02,
147layer_norm_eps=1e-12,
148dropout=0.1,
149mem_len=None,
150reuse_len=None,
151bi_data=False,
152clamp_len=-1,
153same_length=False,
154summary_type="last",
155summary_use_proj=True,
156summary_activation="tanh",
157summary_last_dropout=0.1,
158start_n_top=5,
159end_n_top=5,
160pad_token_id=5,
161bos_token_id=1,
162eos_token_id=2,
163**kwargs
164):
165"""Constructs XLNetConfig.
166"""
167super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
168self.vocab_size = vocab_size
169self.d_model = d_model
170self.n_layer = n_layer
171self.n_head = n_head
172assert d_model % n_head == 0
173if "d_head" in kwargs:
174assert (
175kwargs["d_head"] == d_model // n_head
176), f"`d_head` ({kwargs['d_head']}) should be equal to `d_model // n_head` ({d_model // n_head})"
177self.d_head = d_model // n_head
178self.ff_activation = ff_activation
179self.d_inner = d_inner
180self.untie_r = untie_r
181self.attn_type = attn_type
182
183self.initializer_range = initializer_range
184self.layer_norm_eps = layer_norm_eps
185
186self.dropout = dropout
187self.mem_len = mem_len
188self.reuse_len = reuse_len
189self.bi_data = bi_data
190self.clamp_len = clamp_len
191self.same_length = same_length
192
193self.summary_type = summary_type
194self.summary_use_proj = summary_use_proj
195self.summary_activation = summary_activation
196self.summary_last_dropout = summary_last_dropout
197self.start_n_top = start_n_top
198self.end_n_top = end_n_top
199
200self.bos_token_id = bos_token_id
201self.pad_token_id = pad_token_id
202self.eos_token_id = eos_token_id
203
204if mem_len is None or mem_len == 0:
205warnings.warn(
206"This config doesn't use attention memories, a core feature of XLNet."
207" Consider setting `men_len` to a non-zero value, for example "
208"`xlnet = XLNetLMHeadModel.from_pretrained('xlnet-base-cased'', mem_len=1024)`,"
209" for accurate training performance as well as an order of magnitude faster inference."
210" Starting from version 3.5.0, the default parameter will be 1024, following"
211" the implementation in https://arxiv.org/abs/1906.08237",
212FutureWarning,
213)
214
215@property
216def max_position_embeddings(self):
217return -1
218
219@property
220def n_token(self): # Backward compatibility
221return self.vocab_size
222
223@n_token.setter
224def n_token(self, value): # Backward compatibility
225self.vocab_size = value
226
227@property
228def hidden_size(self):
229return self.d_model
230
231@property
232def num_attention_heads(self):
233return self.n_head
234
235@property
236def num_hidden_layers(self):
237return self.n_layer
238