gpt
mindnlp.transformers.models.gpt.modeling_gpt
¶
MindSpore OpenAI GPT model.
mindnlp.transformers.models.gpt.modeling_gpt.Attention
¶
Bases: Module
This class represents an attention mechanism used in neural networks. It is designed to be used as a part of a larger model and inherits from the nn.Module class.
ATTRIBUTE | DESCRIPTION |
---|---|
bias |
A tensor representing the bias used in the attention computation.
TYPE:
|
n_head |
The number of attention heads.
TYPE:
|
split_size |
The size of each split in the attention mechanism.
TYPE:
|
scale |
A flag indicating whether to scale the attention weights.
TYPE:
|
c_attn |
A 1D convolutional layer used for computing the attention weights.
TYPE:
|
c_proj |
A 1D convolutional layer used for projecting the attention weights.
TYPE:
|
attn_dropout |
A dropout layer applied to the attention weights.
TYPE:
|
resid_dropout |
A dropout layer applied to the projected attention weights.
TYPE:
|
pruned_heads |
A set of pruned attention heads.
TYPE:
|
METHOD | DESCRIPTION |
---|---|
__init__ |
Initializes the Attention object. |
prune_heads |
Prunes the specified attention heads. |
_attn |
Computes the attention weights. |
merge_heads |
Merges the attention heads. |
split_heads |
Splits the input into multiple attention heads. |
forward |
Constructs the attention mechanism. |
Note
- The Attention class assumes that the input tensors follow specific shapes and sizes. It is important to ensure that the input data is compatible with the class implementation.
- The Attention class should be used as part of a larger model and is not intended to be used as a standalone component.
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
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 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 |
|
mindnlp.transformers.models.gpt.modeling_gpt.Attention.__init__(nx, n_positions, config, scale=False)
¶
Initialize the Attention class.
PARAMETER | DESCRIPTION |
---|---|
self |
The instance of the Attention class.
TYPE:
|
nx |
The size of the input state.
TYPE:
|
n_positions |
The number of positions.
TYPE:
|
config |
An object containing configuration settings.
TYPE:
|
scale |
Flag indicating whether to scale the output. Default is False.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
None. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the input state size (n_state) is not divisible by the number of attention heads specified in the configuration. |
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
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 |
|
mindnlp.transformers.models.gpt.modeling_gpt.Attention.forward(x, attention_mask=None, head_mask=None, output_attentions=False)
¶
This method 'forward' in the class 'Attention' processes the input data 'x' through attention mechanisms.
PARAMETER | DESCRIPTION |
---|---|
self |
The instance of the Attention class.
TYPE:
|
x |
The input data tensor to be processed.
TYPE:
|
attention_mask |
An optional mask tensor for masking out certain elements during attention computation.
TYPE:
|
head_mask |
An optional mask tensor for masking out specific attention heads.
TYPE:
|
output_attentions |
A flag indicating whether to output attention weights.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
None
|
This method does not return any value explicitly; it updates internal states and outputs intermediate results. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the provided 'x' tensor is not compatible for processing. |
RuntimeError
|
If an error occurs during the attention mechanism computations. |
TypeError
|
If incorrect data types are provided for the input parameters. |
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
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 |
|
mindnlp.transformers.models.gpt.modeling_gpt.Attention.merge_heads(x)
¶
Merge the heads of the attention mechanism.
PARAMETER | DESCRIPTION |
---|---|
self |
An instance of the Attention class.
|
x |
A tensor representing the input data. It should have a shape of (batch_size, num_heads, seq_len, head_dim).
|
RETURNS | DESCRIPTION |
---|---|
None |
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 |
|
mindnlp.transformers.models.gpt.modeling_gpt.Attention.prune_heads(heads)
¶
Description
This method prunes the attention heads based on the input 'heads' list and updates the necessary attributes of the Attention class accordingly.
PARAMETER | DESCRIPTION |
---|---|
self |
An instance of the Attention class.
TYPE:
|
heads |
The list of attention heads to be pruned.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
None
|
|
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
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 |
|
mindnlp.transformers.models.gpt.modeling_gpt.Attention.split_heads(x, k=False)
¶
Splits the input tensor into multiple "head" tensors along the last dimension.
PARAMETER | DESCRIPTION |
---|---|
self |
The instance of the Attention class.
TYPE:
|
x |
The input tensor to be split into multiple "head" tensors. It should have a shape of (batch_size, seq_len, d_model).
TYPE:
|
k |
A boolean flag indicating whether to transpose the dimensions of the output tensors. Default is False.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
torch.Tensor or None: If |
RAISES | DESCRIPTION |
---|---|
None
|
This method does not raise any exceptions. |
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 |
|
mindnlp.transformers.models.gpt.modeling_gpt.Block
¶
Bases: Module
This class represents a block in a neural network model. It is a subclass of nn.Module and is used for building transformer models.
ATTRIBUTE | DESCRIPTION |
---|---|
attn |
The attention module of the block.
TYPE:
|
ln_1 |
The first layer normalization module.
TYPE:
|
mlp |
The multi-layer perceptron module.
TYPE:
|
ln_2 |
The second layer normalization module.
TYPE:
|
METHOD | DESCRIPTION |
---|---|
__init__ |
Initializes a new instance of the Block class. Args:
|
forward |
Constructs the block by performing the necessary computations on the input. Args:
Returns:
|
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
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 |
|
mindnlp.transformers.models.gpt.modeling_gpt.Block.__init__(n_positions, config, scale=False)
¶
Initializes a Block object.
PARAMETER | DESCRIPTION |
---|---|
self |
The instance of the Block class.
TYPE:
|
n_positions |
The number of positions.
TYPE:
|
config |
The configuration object.
TYPE:
|
scale |
A flag to indicate scaling. Defaults to False.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
None. |
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 |
|
mindnlp.transformers.models.gpt.modeling_gpt.Block.forward(x, attention_mask=None, head_mask=None, output_attentions=False)
¶
Constructs a block in the given class.
PARAMETER | DESCRIPTION |
---|---|
self |
An instance of the Block class.
TYPE:
|
x |
The input tensor.
|
attention_mask |
An optional attention mask tensor. Default is None.
TYPE:
|
head_mask |
An optional head mask tensor. Default is None.
TYPE:
|
output_attentions |
Whether to output attentions. Default is False.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
list
|
A list containing the output tensor and other optional attentions. |
This method forwards a block by performing the following steps:
- Calculate attention outputs using the 'attn' method, passing the input tensor, attention mask, head mask, and output attentions flag as parameters. Store the result in 'attn_outputs'.
- Retrieve the first element from 'attn_outputs' and assign it to 'a'.
- Add 'x' and 'a' and apply layer normalization using the 'ln_1' method. Store the result in 'n'.
- Apply multi-layer perceptron (MLP) to 'n' using the 'mlp' method. Store the result in 'm'.
- Add 'n' and 'm' and apply layer normalization using the 'ln_2' method. Store the result in 'h'.
- Create a list 'outputs' containing 'h' as the first element, followed by any additional elements from 'attn_outputs'.
- Return 'outputs'.
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
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 |
|
mindnlp.transformers.models.gpt.modeling_gpt.GPTDoubleHeadsModel
¶
Bases: GPTPreTrainedModel
This class represents a GPT (Generative Pre-trained Transformer) model with double heads. It is used for language modeling and multiple choice classification tasks. The GPTDoubleHeadsModel inherits from the GPTPreTrainedModel class.
The GPTDoubleHeadsModel class contains methods for initializing the model, getting and setting the output embeddings,
and forwarding the model. It also includes a detailed docstring for the forward
method,
which describes the input parameters, return values, and provides examples of how to use the method.
To use the GPTDoubleHeadsModel, follow these steps:
- Instantiate the GPTDoubleHeadsModel class, passing the
config
parameter. - Use the
get_output_embeddings
method to get the output embeddings of the model. - Use the
set_output_embeddings
method to set new embeddings for the model. - Use the
forward
method to perform language modeling and multiple choice classification tasks. The method takes various input tensors and returns the model outputs, including logits for language modeling and multiple choice classification.
Example
>>> from transformers import AutoTokenizer, GPTDoubleHeadsModel
...
>>> tokenizer = AutoTokenizer.from_pretrained("openai-gpt")
>>> model = GPTDoubleHeadsModel.from_pretrained("openai-gpt")
>>> tokenizer.add_special_tokens({"cls_token": "[CLS]"})
>>> model.resize_token_embeddings(len(tokenizer))
...
>>> choices = ["Hello, my dog is cute [CLS]", "Hello, my cat is cute [CLS]"]
>>> input_ids = tokenizer.encode_batch(choices)
>>> mc_token_ids = [len(ids) - 1 for ids in input_ids]
...
>>> outputs = model.forward(input_ids, mc_token_ids=mc_token_ids)
>>> lm_logits = outputs.logits
>>> mc_logits = outputs.mc_logits
For more details on how to use the GPTDoubleHeadsModel class, refer to the documentation and examples provided in the code.
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
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 1008 1009 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 |
|
mindnlp.transformers.models.gpt.modeling_gpt.GPTDoubleHeadsModel.__init__(config)
¶
Initializes an instance of the GPTDoubleHeadsModel class.
PARAMETER | DESCRIPTION |
---|---|
self |
The current object.
|
config |
An instance of the GPTConfig class that holds the configuration settings for the GPT model.
|
RETURNS | DESCRIPTION |
---|---|
None |
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 |
|
mindnlp.transformers.models.gpt.modeling_gpt.GPTDoubleHeadsModel.forward(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, mc_token_ids=None, labels=None, mc_labels=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
TYPE:
|
mc_labels |
Labels for computing the multiple choice classification loss. Indices should be in
TYPE:
|
Return
Union[Tuple[mindspore.Tensor], GPTDoubleHeadsModelOutput]
Example
>>> from transformers import AutoTokenizer, OpenAIGPTDoubleHeadsModel
...
...
>>> tokenizer = AutoTokenizer.from_pretrained("openai-gpt")
>>> model = OpenAIGPTDoubleHeadsModel.from_pretrained("openai-gpt")
>>> tokenizer.add_special_tokens(
... {"cls_token": "[CLS]"}
... ) # Add a [CLS] to the vocabulary (we should train it also!)
>>> model.resize_token_embeddings(len(tokenizer))
...
>>> choices = ["Hello, my dog is cute [CLS]", "Hello, my cat is cute [CLS]"]
>>> input_ids = torch.tensor([tokenizer.encode(s) for s in choices]).unsqueeze(0) # Batch size 1, 2 choices
>>> mc_token_ids = torch.tensor([input_ids.shape[-1] - 1, input_ids.shape[-1] - 1]).unsqueeze(0) # Batch size 1
...
>>> outputs = model(input_ids, mc_token_ids=mc_token_ids)
>>> lm_logits = outputs.logits
>>> mc_logits = outputs.mc_logits
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
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 |
|
mindnlp.transformers.models.gpt.modeling_gpt.GPTDoubleHeadsModel.get_output_embeddings()
¶
Returns the output embeddings for the GPTDoubleHeadsModel.
PARAMETER | DESCRIPTION |
---|---|
self |
An instance of the GPTDoubleHeadsModel class.
|
RETURNS | DESCRIPTION |
---|---|
None |
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 |
|
mindnlp.transformers.models.gpt.modeling_gpt.GPTDoubleHeadsModel.set_output_embeddings(new_embeddings)
¶
Sets the output embeddings of the GPTDoubleHeadsModel.
PARAMETER | DESCRIPTION |
---|---|
self |
The instance of the GPTDoubleHeadsModel class.
TYPE:
|
new_embeddings |
The new embeddings to be set as the output embeddings. This can be an object of any type.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
None. |
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 |
|
mindnlp.transformers.models.gpt.modeling_gpt.GPTDoubleHeadsModelOutput
dataclass
¶
Bases: ModelOutput
Base class for outputs of models predicting if two sentences are consecutive or not.
PARAMETER | DESCRIPTION |
---|---|
loss |
Language modeling loss.
TYPE:
|
mc_loss |
Multiple choice classification loss.
TYPE:
|
logits |
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
TYPE:
|
mc_logits |
Prediction scores of the multiple choice classification head (scores for each choice before SoftMax).
TYPE:
|
Source code in mindnlp/transformers/models/gpt/modeling_gpt.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 533 534 535 536 537 538 539 540 |
|
mindnlp.transformers.models.gpt.modeling_gpt.GPTForSequenceClassification
¶
Bases: GPTPreTrainedModel
This class 'GPTForSequenceClassification' represents a sequence classification model based on the GPT (Generative Pre-trained Transformer) architecture. It is designed to classify sequences based on the provided input.
This class inherits from the 'GPTPreTrainedModel' class, which provides the basic functionality for a pre-trained GPT model.
The class contains an initializer method 'init' which takes a 'config' parameter. It calls the initializer of the parent class and initializes the 'num_labels' attribute with the 'num_labels' value from the 'config'. It also initializes a 'transformer' attribute with an instance of the 'GPTModel' class from the 'config'. Additionally, it creates a 'score' attribute which is a neural network layer with a dense layer of shape '(config.n_embd, num_labels)' and no bias. Finally, it calls the 'post_init' method.
The 'forward' method is responsible for forwarding the sequence classification model. It takes several optional input tensors as parameters, including 'input_ids', 'attention_mask', 'token_type_ids', 'position_ids', 'head_mask', 'inputs_embeds', 'labels', 'output_attentions', 'output_hidden_states', and 'return_dict'. It returns a Tuple of tensors or a 'SequenceClassifierOutput' object.
The 'labels' parameter is an optional tensor of shape '(batch_size,)', which provides the labels for computing the sequence classification/regression loss. The indices in 'labels' should be in the range of '[0, ..., config.num_labels - 1]'. If 'config.num_labels == 1', a regression loss (Mean-Square loss) is computed. If 'config.num_labels > 1', a classification loss (Cross-Entropy) is computed.
The 'return_dict' parameter indicates whether the method should return a 'SequenceClassifierOutput' object. If 'return_dict' is not provided, it defaults to the value of 'self.config.use_return_dict'.
The method first calls the 'transformer' model with the provided input tensors and other optional parameters to obtain the transformer outputs, including the 'hidden_states' tensor. Then, it passes the 'hidden_states' tensor through the 'score' layer to obtain the 'logits' tensor.
Next, the method checks the shape of the 'input_ids' tensor to determine the batch size. If 'input_ids' is not None, the shape of 'input_ids' is used to calculate the sequence lengths. If 'self.config.pad_token_id' is not None, the method checks for padding tokens in 'input_ids' and calculates the sequence lengths accordingly. If 'input_ids' is None, the sequence lengths are set to -1.
The method then selects the relevant logits based on the sequence lengths. If 'sequence_lengths' is an integer, the method uses it to index the 'logits' tensor. Otherwise, it uses the 'sequence_lengths' tensor to gather the relevant logits.
The 'loss' variable is set to None initially. If 'labels' is provided, the method determines the 'problem_type' based on the 'config' and the shape and dtype of 'labels'. Depending on the 'problem_type', the method calculates the loss using operations provided by the 'ops' module.
Finally, depending on the 'return_dict' parameter, the method either returns a Tuple of tensors or a 'SequenceClassifierOutput' object containing the 'loss', 'logits', 'hidden_states', and 'attentions'.
Note
This docstring does not include method signatures or any other code for clarity.
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
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 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 |
|
mindnlp.transformers.models.gpt.modeling_gpt.GPTForSequenceClassification.__init__(config)
¶
Initializes an instance of GPTForSequenceClassification.
PARAMETER | DESCRIPTION |
---|---|
self |
The instance itself. |
config |
An object containing configuration settings for the model.
|
RETURNS | DESCRIPTION |
---|---|
None. |
RAISES | DESCRIPTION |
---|---|
NotImplementedError
|
If the method 'post_init' is not implemented in the derived class. |
TypeError
|
If the configuration settings provided are not compatible with the GPTModel. |
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 |
|
mindnlp.transformers.models.gpt.modeling_gpt.GPTForSequenceClassification.forward(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=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
TYPE:
|
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 |
|
mindnlp.transformers.models.gpt.modeling_gpt.GPTLMHeadModel
¶
Bases: GPTPreTrainedModel
This class represents a language model head for the Generative Pre-trained Transformer (GPT) model. It is used for generating language predictions and is designed to be compatible with the GPT architecture.
The GPTLMHeadModel class provides methods for initializing the model with a configuration, getting and setting output embeddings, forwarding language model outputs, and preparing inputs for generation. It inherits from the GPTPreTrainedModel class.
METHOD | DESCRIPTION |
---|---|
__init__ |
Initializes the model with a given configuration. |
get_output_embeddings |
Returns the output embeddings of the model. |
set_output_embeddings |
Sets new output embeddings for the model. |
forward |
Constructs language model outputs based on input features. |
prepare_inputs_for_generation |
Prepares input data for language generation. |
The forward method takes various input arguments for language modeling and returns model outputs, including logits and hidden states. The prepare_inputs_for_generation method prepares input data specifically for language generation tasks.
Note
The GPTLMHeadModel class is designed for use in natural language processing tasks and is a part of the GPT model framework.
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
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 901 902 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 |
|
mindnlp.transformers.models.gpt.modeling_gpt.GPTLMHeadModel.__init__(config)
¶
Initializes a new instance of the GPTLMHeadModel class.
PARAMETER | DESCRIPTION |
---|---|
self |
The instance of the GPTLMHeadModel class.
TYPE:
|
config |
The configuration object containing model parameters.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
None. |
RAISES | DESCRIPTION |
---|---|
ValueError
|
If the configuration object is missing or invalid. |
TypeError
|
If the configuration object is not of type Config. |
RuntimeError
|
If there are issues during model initialization. |
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 |
|
mindnlp.transformers.models.gpt.modeling_gpt.GPTLMHeadModel.forward(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, labels=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
TYPE:
|
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
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 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 |
|
mindnlp.transformers.models.gpt.modeling_gpt.GPTLMHeadModel.get_output_embeddings()
¶
Method to retrieve the output embeddings from the GPTLMHeadModel.
PARAMETER | DESCRIPTION |
---|---|
self |
The instance of the GPTLMHeadModel class. This parameter refers to the current instance of the GPTLMHeadModel class.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
The 'lm_head' attribute of the GPTLMHeadModel instance. |
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 |
|
mindnlp.transformers.models.gpt.modeling_gpt.GPTLMHeadModel.prepare_inputs_for_generation(input_ids, **kwargs)
¶
Prepare inputs for generation.
PARAMETER | DESCRIPTION |
---|---|
self |
The instance of the GPTLMHeadModel class.
TYPE:
|
input_ids |
The input tensor containing the token ids for the generation.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Dict[str, Any]
|
Dict[str, Any]: A dictionary containing the prepared input_ids. |
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 |
|
mindnlp.transformers.models.gpt.modeling_gpt.GPTLMHeadModel.set_output_embeddings(new_embeddings)
¶
This method sets the output embeddings for the GPTLMHeadModel.
PARAMETER | DESCRIPTION |
---|---|
self |
The instance of the GPTLMHeadModel class.
TYPE:
|
new_embeddings |
The new embeddings to be set as the output embeddings for the model. It should be of the same type as the existing embeddings.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
None
|
. |
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 |
|
mindnlp.transformers.models.gpt.modeling_gpt.GPTModel
¶
Bases: GPTPreTrainedModel
This class represents a GPT (Generative Pre-trained Transformer) model for natural language processing tasks. It inherits from the GPTPreTrainedModel class and implements the GPT architecture for generating text based on input sequences. The model includes methods for initializing embeddings, pruning heads, and forwarding the model for inference or training.
ATTRIBUTE | DESCRIPTION |
---|---|
config |
The configuration for the GPTModel, including parameters such as vocab_size, n_embd, n_positions, embd_pdrop, and n_layer.
|
METHOD | DESCRIPTION |
---|---|
__init__ |
Initializes the GPTModel with the given configuration. |
get_input_embeddings |
Returns the input embeddings used in the model. |
set_input_embeddings |
Sets new input embeddings for the model. |
_prune_heads) |
Prunes specified heads of the model based on the provided dictionary of layer numbers and heads to prune. |
forward |
Constructs the GPTModel for inference or training based on the input data and configuration. |
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
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 686 687 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 |
|
mindnlp.transformers.models.gpt.modeling_gpt.GPTModel.__init__(config)
¶
Initializes a GPTModel instance with the provided configuration.
PARAMETER | DESCRIPTION |
---|---|
self |
The GPTModel instance to be initialized.
TYPE:
|
config |
The configuration object containing parameters for the model.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
None. |
RAISES | DESCRIPTION |
---|---|
TypeError
|
If config is not of the expected object type. |
ValueError
|
If any of the configuration parameters are invalid or out of range. |
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
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 |
|
mindnlp.transformers.models.gpt.modeling_gpt.GPTModel.forward(input_ids=None, attention_mask=None, token_type_ids=None, position_ids=None, head_mask=None, inputs_embeds=None, output_attentions=None, output_hidden_states=None, return_dict=None)
¶
Constructs the GPTModel.
PARAMETER | DESCRIPTION |
---|---|
self |
The instance of the class.
|
input_ids |
The input tensor of shape [batch_size, sequence_length] containing the input IDs.
TYPE:
|
attention_mask |
The attention mask tensor of shape [batch_size, sequence_length] containing the attention mask.
TYPE:
|
token_type_ids |
The token type IDs tensor of shape [batch_size, sequence_length] containing the token type IDs.
TYPE:
|
position_ids |
The position IDs tensor of shape [batch_size, sequence_length] containing the position IDs.
TYPE:
|
head_mask |
The head mask tensor of shape [num_heads] containing the head mask.
TYPE:
|
inputs_embeds |
The inputs embeddings tensor of shape [batch_size, sequence_length, hidden_size] containing the input embeddings.
TYPE:
|
output_attentions |
Whether to output attentions. If not provided, it uses the value from the configuration.
TYPE:
|
output_hidden_states |
Whether to output hidden states. If not provided, it uses the value from the configuration.
TYPE:
|
return_dict |
Whether to return a BaseModelOutput instead of a tuple. If not provided, it uses the value from the configuration.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Union[Tuple[Tensor], BaseModelOutput]
|
Union[Tuple[mindspore.Tensor], BaseModelOutput]: The output of the GPTModel.
|
RAISES | DESCRIPTION |
---|---|
ValueError
|
If both input_ids and inputs_embeds are specified at the same time. |
ValueError
|
If neither input_ids nor inputs_embeds are specified. |
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
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 686 687 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 |
|
mindnlp.transformers.models.gpt.modeling_gpt.GPTModel.get_input_embeddings()
¶
This method retrieves the input embeddings from the GPTModel.
PARAMETER | DESCRIPTION |
---|---|
self |
The instance of the GPTModel class.
|
RETURNS | DESCRIPTION |
---|---|
None. |
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
597 598 599 600 601 602 603 604 605 606 607 608 609 610 |
|
mindnlp.transformers.models.gpt.modeling_gpt.GPTModel.set_input_embeddings(new_embeddings)
¶
Sets the input embeddings for the GPTModel.
PARAMETER | DESCRIPTION |
---|---|
self |
An instance of the GPTModel class.
TYPE:
|
new_embeddings |
The new input embeddings to be set.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
None. |
Description
This method allows for updating the input embeddings of the GPTModel by assigning the provided 'new_embeddings' to the 'tokens_embed' attribute. The 'tokens_embed' attribute is used by the model during tokenization and embedding stages.
The 'self' parameter refers to the current instance of the GPTModel class, while the 'new_embeddings' parameter represents the new input embeddings to be assigned. The 'new_embeddings' can be of any data type and should contain the updated embeddings.
Note that the 'tokens_embed' attribute is expected to be updated directly by this method. Any existing input embeddings will be overwritten.
Example
>>> model = GPTModel()
>>> new_embeddings = get_new_embeddings()
>>> model.set_input_embeddings(new_embeddings)
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
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 |
|
mindnlp.transformers.models.gpt.modeling_gpt.GPTPreTrainedModel
¶
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/gpt/modeling_gpt.py
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 |
|
mindnlp.transformers.models.gpt.modeling_gpt.MLP
¶
Bases: Module
MLP is a class that represents a multi-layer perceptron (MLP) model.
MLP is a neural network model that consists of multiple layers of perceptrons or artificial neurons. Each layer is fully connected to the next layer, and the final layer produces the output. The MLP class inherits from the nn.Module class, which is a base class for all neural network modules in the PyTorch framework.
The MLP class has the following attributes:
- n_state: an integer representing the number of output channels in the first convolutional layer.
- config: an object containing various configuration parameters for the MLP model.
The MLP class has the following methods:
- init(self, n_state, config): Initializes the MLP object. It takes two parameters: n_state, which represents the number of output channels in the first convolutional layer, and config, which is an object containing configuration parameters for the MLP model. Inside the method, it initializes the parent class (nn.Module), sets the number of input channels (nx) to the value specified in the config, creates a 1-dimensional convolutional layer (self.c_fc) with n_state output channels and nx input channels, creates another 1-dimensional convolutional layer (self.c_proj) with nx output channels and n_state input channels, sets the activation function (self.act) to the value specified in the config, and sets the dropout probability (self.dropout) to the value specified in the config.
- forward(self, x): Constructs the MLP model. It takes one parameter, x, which represents the input tensor. Inside the method, it applies the activation function to the output of the first convolutional layer (self.c_fc), applies the second convolutional layer (self.c_proj) to the result, and returns the output after applying dropout (self.dropout).
Note
The MLP class assumes the existence of the ACT_FNS dictionary, which maps activation function names to their corresponding functions.
Example
>>> config = MLPConfig(n_embd=128, afn='relu', resid_pdrop=0.2)
>>> mlp = MLP(n_state=64, config=config)
>>> input_tensor = torch.randn(10, 128)
>>> output = mlp.forward(input_tensor)
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
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 |
|
mindnlp.transformers.models.gpt.modeling_gpt.MLP.__init__(n_state, config)
¶
Initializes an instance of the MLP class.
PARAMETER | DESCRIPTION |
---|---|
self |
The instance of the MLP class.
|
n_state |
Number of states for the MLP.
TYPE:
|
config |
Configuration object containing parameters for the MLP.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
None. |
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 |
|
mindnlp.transformers.models.gpt.modeling_gpt.MLP.forward(x)
¶
Constructs the output of the Multi-Layer Perceptron (MLP) model.
PARAMETER | DESCRIPTION |
---|---|
self |
The instance of the MLP class.
TYPE:
|
x |
The input tensor to be processed by the MLP.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
The forwarded output tensor after passing through the MLP layers. |
Source code in mindnlp/transformers/models/gpt/modeling_gpt.py
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 |
|
mindnlp.transformers.models.gpt.configuration_gpt
¶
OpenAI GPT configuration
mindnlp.transformers.models.gpt.configuration_gpt.GPTConfig
¶
Bases: PretrainedConfig
This is the configuration class to store the configuration of a [OpenAIGPTModel
] or a [TFOpenAIGPTModel
]. It is
used to instantiate a GPT 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 GPT
openai-gpt architecture from OpenAI.
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 GPT-2 model. Defines the number of different tokens that can be represented by the
TYPE:
|
n_positions |
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:
|
n_embd |
Dimensionality of the embeddings and hidden states.
TYPE:
|
n_layer |
Number of hidden layers in the Transformer encoder.
TYPE:
|
n_head |
Number of attention heads for each attention layer in the Transformer encoder.
TYPE:
|
afn |
The non-linear activation function (function or string) in the encoder and pooler. If string,
TYPE:
|
resid_pdrop |
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
TYPE:
|
embd_pdrop |
The dropout ratio for the embeddings.
TYPE:
|
attn_pdrop |
The dropout ratio for the attention.
TYPE:
|
layer_norm_epsilon |
The epsilon to use in the layer normalization layers
TYPE:
|
initializer_range |
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
TYPE:
|
summary_type |
Argument used when doing sequence summary, used in the models [
TYPE:
|
summary_use_proj |
Argument used when doing sequence summary, used in the models [ Whether or not to add a projection after the vector extraction.
TYPE:
|
summary_activation |
Argument used when doing sequence summary, used in the models [ Pass
TYPE:
|
summary_proj_to_labels |
Argument used when doing sequence summary, used in the models [ Whether the projection outputs should have
TYPE:
|
summary_first_dropout |
Argument used when doing sequence summary, used in the models [ The dropout ratio to be used after the projection and activation.
TYPE:
|
Example
>>> from transformers import OpenAIGPTConfig, OpenAIGPTModel
...
>>> # Initializing a GPT configuration
>>> configuration = OpenAIGPTConfig()
...
>>> # Initializing a model (with random weights) from the configuration
>>> model = OpenAIGPTModel(configuration)
...
>>> # Accessing the model configuration
>>> configuration = model.config
Source code in mindnlp/transformers/models/gpt/configuration_gpt.py
27 28 29 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 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 |
|
mindnlp.transformers.models.gpt.configuration_gpt.GPTConfig.__init__(vocab_size=40478, n_positions=512, n_embd=768, n_layer=12, n_head=12, afn='gelu', resid_pdrop=0.1, embd_pdrop=0.1, attn_pdrop=0.1, layer_norm_epsilon=1e-05, initializer_range=0.02, summary_type='cls_index', summary_use_proj=True, summary_activation=None, summary_proj_to_labels=True, summary_first_dropout=0.1, **kwargs)
¶
Initializes a GPTConfig object with the provided parameters.
PARAMETER | DESCRIPTION |
---|---|
vocab_size |
The size of the vocabulary.
TYPE:
|
n_positions |
The number of positions.
TYPE:
|
n_embd |
The embedding dimension.
TYPE:
|
n_layer |
The number of layers.
TYPE:
|
n_head |
The number of attention heads.
TYPE:
|
afn |
The activation function to be used.
TYPE:
|
resid_pdrop |
The dropout probability for residual connections.
TYPE:
|
embd_pdrop |
The dropout probability for the embeddings.
TYPE:
|
attn_pdrop |
The dropout probability for attention layers.
TYPE:
|
layer_norm_epsilon |
The epsilon value for layer normalization.
TYPE:
|
initializer_range |
The range of the initializer.
TYPE:
|
summary_type |
The type of summary to be used.
TYPE:
|
summary_use_proj |
Whether to use projection in summary.
TYPE:
|
summary_activation |
The activation function for the summary.
TYPE:
|
summary_proj_to_labels |
Whether to project the summary to labels.
TYPE:
|
summary_first_dropout |
The dropout probability for the first layer of the summary.
TYPE:
|
**kwargs |
Additional keyword arguments.
DEFAULT:
|
RETURNS | DESCRIPTION |
---|---|
None. |
Source code in mindnlp/transformers/models/gpt/configuration_gpt.py
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 |
|
mindnlp.transformers.models.gpt.tokenization_gpt
¶
Tokenization classes for OpenAI GPT.
mindnlp.transformers.models.gpt.tokenization_gpt.BasicTokenizer
¶
Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
PARAMETER | DESCRIPTION |
---|---|
do_lower_case |
Whether or not to lowercase the input when tokenizing.
TYPE:
|
never_split |
Collection of tokens which will never be split during tokenization. Only has an effect when
TYPE:
|
tokenize_chinese_chars |
Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see this issue).
TYPE:
|
strip_accents |
Whether or not to strip all accents. If this option is not specified, then it will be determined by the
value for
TYPE:
|
do_split_on_punc |
In some instances we want to skip the basic punctuation splitting so that later tokenization can capture the full context of the words, such as contractions.
TYPE:
|
Source code in mindnlp/transformers/models/gpt/tokenization_gpt.py
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 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 |
|
mindnlp.transformers.models.gpt.tokenization_gpt.BasicTokenizer.__init__(do_lower_case=True, never_split=None, tokenize_chinese_chars=True, strip_accents=None, do_split_on_punc=True)
¶
Initializes an instance of the BasicTokenizer class.
PARAMETER | DESCRIPTION |
---|---|
self |
The instance of the BasicTokenizer class.
TYPE:
|
do_lower_case |
Indicates whether text should be converted to lowercase. Default is True.
TYPE:
|
never_split |
List of tokens that should never be split. Default is an empty list.
TYPE:
|
tokenize_chinese_chars |
Indicates whether Chinese characters should be tokenized. Default is True.
TYPE:
|
strip_accents |
Specifies the type of accents to remove. Default is None.
TYPE:
|
do_split_on_punc |
Indicates whether to split on punctuation. Default is True.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
None. |
Source code in mindnlp/transformers/models/gpt/tokenization_gpt.py
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 |
|
mindnlp.transformers.models.gpt.tokenization_gpt.BasicTokenizer.tokenize(text, never_split=None)
¶
Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
Source code in mindnlp/transformers/models/gpt/tokenization_gpt.py
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 |
|
mindnlp.transformers.models.gpt.tokenization_gpt.GPTTokenizer
¶
Bases: PreTrainedTokenizer
Construct a GPT Tokenizer. Based on Byte-Pair-Encoding with the following peculiarities:
- lowercases all inputs,
- uses
SpaCy
tokenizer andftfy
for pre-BPE tokenization if they are installed, fallback to BERT'sBasicTokenizer
if not.
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:
|
merges_file |
Path to the merges file.
TYPE:
|
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:
|
Source code in mindnlp/transformers/models/gpt/tokenization_gpt.py
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 |
|
mindnlp.transformers.models.gpt.tokenization_gpt.GPTTokenizer.do_lower_case
property
¶
Toggle the lower case flag for the GPTTokenizer object.
PARAMETER | DESCRIPTION |
---|---|
self |
An instance of the GPTTokenizer class.
|
RETURNS | DESCRIPTION |
---|---|
None. |
This method is used to toggle the lower case flag for the GPTTokenizer object. When the lower case flag is set to True, the tokenizer will convert all text to lower case. When the flag is set to False, the tokenizer will preserve the original casing of the text.
Note that changing the lower case flag will affect the tokenization behavior of the GPTTokenizer object. It is recommended to set the lower case flag before tokenizing any text using the tokenizer. By default, the lower case flag is set to True.
Example
>>> tokenizer = GPTTokenizer()
>>> tokenizer.do_lower_case = False
...
mindnlp.transformers.models.gpt.tokenization_gpt.GPTTokenizer.vocab_size
property
¶
Method to retrieve the vocabulary size of the GPTTokenizer instance.
PARAMETER | DESCRIPTION |
---|---|
self |
GPTTokenizer The instance of GPTTokenizer for which the vocabulary size is to be determined. It is automatically passed when the method is called.
|
RETURNS | DESCRIPTION |
---|---|
int
|
The vocabulary size of the GPTTokenizer instance, which is the length of the encoder used by the tokenizer. |
RAISES | DESCRIPTION |
---|---|
None
|
This method does not raise any exceptions. |
mindnlp.transformers.models.gpt.tokenization_gpt.GPTTokenizer.__init__(vocab_file, merges_file, unk_token='<unk>', **kwargs)
¶
This method initializes an instance of the GPTTokenizer class.
PARAMETER | DESCRIPTION |
---|---|
self |
The instance of the GPTTokenizer class.
|
vocab_file |
The path to the vocabulary file containing the encoder information.
TYPE:
|
merges_file |
The path to the file containing merge operations for Byte Pair Encoding (BPE).
TYPE:
|
unk_token |
The token to represent unknown words. Defaults to '
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
None. |
RAISES | DESCRIPTION |
---|---|
ImportError
|
If the required packages 'ftfy' or 'spacy' are not installed, an ImportError is raised. |
FileNotFoundError
|
If the vocab_file or merges_file is not found, a FileNotFoundError is raised. |
JSONDecodeError
|
If there is an issue with decoding the vocabulary file, a JSONDecodeError is raised. |
IndexError
|
If there is an issue with processing the merges file, an IndexError is raised. |
Source code in mindnlp/transformers/models/gpt/tokenization_gpt.py
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 |
|
mindnlp.transformers.models.gpt.tokenization_gpt.GPTTokenizer.bpe(token)
¶
This method is part of the GPTTokenizer class and performs Byte Pair Encoding (BPE) on a given token.
PARAMETER | DESCRIPTION |
---|---|
self |
The instance of the GPTTokenizer class.
TYPE:
|
token |
The input token to be encoded using BPE. It should be a non-empty string.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
None
|
This method does not return any value but updates the cache with the encoded word. |
Source code in mindnlp/transformers/models/gpt/tokenization_gpt.py
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 |
|
mindnlp.transformers.models.gpt.tokenization_gpt.GPTTokenizer.convert_tokens_to_string(tokens)
¶
Converts a sequence of tokens (string) in a single string.
Source code in mindnlp/transformers/models/gpt/tokenization_gpt.py
474 475 476 477 |
|
mindnlp.transformers.models.gpt.tokenization_gpt.GPTTokenizer.get_vocab()
¶
This method returns the vocabulary of the GPTTokenizer.
PARAMETER | DESCRIPTION |
---|---|
self |
The instance of the GPTTokenizer class.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
dict
|
A dictionary containing the vocabulary, where the keys are the tokens and the values are their corresponding IDs. |
Source code in mindnlp/transformers/models/gpt/tokenization_gpt.py
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 |
|
mindnlp.transformers.models.gpt.tokenization_gpt.GPTTokenizer.save_vocabulary(save_directory, filename_prefix=None)
¶
Save the vocabulary files to the specified directory.
PARAMETER | DESCRIPTION |
---|---|
self |
The instance of the GPTTokenizer class.
|
save_directory |
The directory path where the vocabulary files will be saved.
TYPE:
|
filename_prefix |
An optional prefix to be added to the filenames. Default is None.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Tuple[str]
|
Tuple[str]: A tuple containing the paths to the saved vocabulary file and merge file. |
RAISES | DESCRIPTION |
---|---|
FileNotFoundError
|
If the specified save_directory does not exist. |
IOError
|
If there is an issue with writing the vocabulary files. |
ValueError
|
If the provided filename_prefix is invalid. |
RuntimeError
|
If the BPE merge indices are not consecutive, indicating a potential tokenizer corruption. |
Source code in mindnlp/transformers/models/gpt/tokenization_gpt.py
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 |
|
mindnlp.transformers.models.gpt.tokenization_gpt.get_pairs(word)
¶
Return set of symbol pairs in a word. word is represented as tuple of symbols (symbols being variable-length strings)
Source code in mindnlp/transformers/models/gpt/tokenization_gpt.py
233 234 235 236 237 238 239 240 241 242 243 |
|
mindnlp.transformers.models.gpt.tokenization_gpt.text_standardize(text)
¶
fixes some issues the spacy tokenizer had on books corpus also does some whitespace standardization
Source code in mindnlp/transformers/models/gpt/tokenization_gpt.py
246 247 248 249 250 251 252 253 254 255 256 257 258 |
|
mindnlp.transformers.models.gpt.tokenization_gpt.whitespace_tokenize(text)
¶
Runs basic whitespace cleaning and splitting on a piece of text.
Source code in mindnlp/transformers/models/gpt/tokenization_gpt.py
45 46 47 48 49 50 51 |
|
mindnlp.transformers.models.gpt.tokenization_gpt_fast
¶
Fast Tokenization classes for OpenAI GPT.
mindnlp.transformers.models.gpt.tokenization_gpt_fast.GPTTokenizerFast
¶
Bases: PreTrainedTokenizerFast
Construct a "fast" GPT Tokenizer (backed by HuggingFace's tokenizers library). Based on Byte-Pair-Encoding with the following peculiarities:
- lower case all inputs
- uses BERT's BasicTokenizer for pre-BPE tokenization
This tokenizer inherits from [PreTrainedTokenizerFast
] 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:
|
merges_file |
Path to the merges file.
TYPE:
|
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:
|
Source code in mindnlp/transformers/models/gpt/tokenization_gpt_fast.py
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 |
|
mindnlp.transformers.models.gpt.tokenization_gpt_fast.GPTTokenizerFast.do_lower_case
property
¶
Method 'do_lower_case' in the class 'GPTTokenizerFast'.
PARAMETER | DESCRIPTION |
---|---|
self |
This parameter refers to the instance of the class itself. It is required for accessing the object's attributes and methods.
|
RETURNS | DESCRIPTION |
---|---|
True
|
This method always returns a boolean value of True indicating that lowercasing is enabled. |
mindnlp.transformers.models.gpt.tokenization_gpt_fast.GPTTokenizerFast.__init__(vocab_file=None, merges_file=None, tokenizer_file=None, unk_token='<unk>', **kwargs)
¶
Initialize a GPTTokenizerFast object.
PARAMETER | DESCRIPTION |
---|---|
vocab_file |
Path to the vocabulary file. Default is None.
TYPE:
|
merges_file |
Path to the merges file. Default is None.
TYPE:
|
tokenizer_file |
Path to the tokenizer file. Default is None.
TYPE:
|
unk_token |
The token to represent unknown words. Default is '
TYPE:
|
**kwargs |
Additional keyword arguments.
DEFAULT:
|
RETURNS | DESCRIPTION |
---|---|
None. |
Source code in mindnlp/transformers/models/gpt/tokenization_gpt_fast.py
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
|
mindnlp.transformers.models.gpt.tokenization_gpt_fast.GPTTokenizerFast.save_vocabulary(save_directory, filename_prefix=None)
¶
Save the vocabulary files generated by the GPTTokenizerFast instance to the specified directory.
PARAMETER | DESCRIPTION |
---|---|
self |
The GPTTokenizerFast instance.
TYPE:
|
save_directory |
The directory where the vocabulary files will be saved.
TYPE:
|
filename_prefix |
An optional prefix to be added to the filenames of the vocabulary files. Default is None.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
Tuple[str]
|
Tuple[str]: A tuple containing the filenames of the saved vocabulary files. |
This method saves the vocabulary files generated by the GPTTokenizerFast instance to the specified directory. The save_directory parameter should be a valid directory path. If filename_prefix is provided, it will be added as a prefix to the filenames of the vocabulary files. The method returns a tuple containing the filenames of the saved vocabulary files.
Source code in mindnlp/transformers/models/gpt/tokenization_gpt_fast.py
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 |
|