squad.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  1. # Copyright 2020 The HuggingFace Team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import json
  15. import os
  16. from functools import partial
  17. from multiprocessing import Pool, cpu_count
  18. import numpy as np
  19. from tqdm import tqdm
  20. from ...models.bert.tokenization_bert import whitespace_tokenize
  21. from ...tokenization_utils_base import BatchEncoding, PreTrainedTokenizerBase, TruncationStrategy
  22. from ...utils import is_tf_available, is_torch_available, logging
  23. from .utils import DataProcessor
  24. # Store the tokenizers which insert 2 separators tokens
  25. MULTI_SEP_TOKENS_TOKENIZERS_SET = {"roberta", "camembert", "bart", "mpnet"}
  26. if is_torch_available():
  27. import torch
  28. from torch.utils.data import TensorDataset
  29. if is_tf_available():
  30. import tensorflow as tf
  31. logger = logging.get_logger(__name__)
  32. def _improve_answer_span(doc_tokens, input_start, input_end, tokenizer, orig_answer_text):
  33. """Returns tokenized answer spans that better match the annotated answer."""
  34. tok_answer_text = " ".join(tokenizer.tokenize(orig_answer_text))
  35. for new_start in range(input_start, input_end + 1):
  36. for new_end in range(input_end, new_start - 1, -1):
  37. text_span = " ".join(doc_tokens[new_start : (new_end + 1)])
  38. if text_span == tok_answer_text:
  39. return (new_start, new_end)
  40. return (input_start, input_end)
  41. def _check_is_max_context(doc_spans, cur_span_index, position):
  42. """Check if this is the 'max context' doc span for the token."""
  43. best_score = None
  44. best_span_index = None
  45. for span_index, doc_span in enumerate(doc_spans):
  46. end = doc_span.start + doc_span.length - 1
  47. if position < doc_span.start:
  48. continue
  49. if position > end:
  50. continue
  51. num_left_context = position - doc_span.start
  52. num_right_context = end - position
  53. score = min(num_left_context, num_right_context) + 0.01 * doc_span.length
  54. if best_score is None or score > best_score:
  55. best_score = score
  56. best_span_index = span_index
  57. return cur_span_index == best_span_index
  58. def _new_check_is_max_context(doc_spans, cur_span_index, position):
  59. """Check if this is the 'max context' doc span for the token."""
  60. # if len(doc_spans) == 1:
  61. # return True
  62. best_score = None
  63. best_span_index = None
  64. for span_index, doc_span in enumerate(doc_spans):
  65. end = doc_span["start"] + doc_span["length"] - 1
  66. if position < doc_span["start"]:
  67. continue
  68. if position > end:
  69. continue
  70. num_left_context = position - doc_span["start"]
  71. num_right_context = end - position
  72. score = min(num_left_context, num_right_context) + 0.01 * doc_span["length"]
  73. if best_score is None or score > best_score:
  74. best_score = score
  75. best_span_index = span_index
  76. return cur_span_index == best_span_index
  77. def _is_whitespace(c):
  78. if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F:
  79. return True
  80. return False
  81. def squad_convert_example_to_features(
  82. example, max_seq_length, doc_stride, max_query_length, padding_strategy, is_training
  83. ):
  84. features = []
  85. if is_training and not example.is_impossible:
  86. # Get start and end position
  87. start_position = example.start_position
  88. end_position = example.end_position
  89. # If the answer cannot be found in the text, then skip this example.
  90. actual_text = " ".join(example.doc_tokens[start_position : (end_position + 1)])
  91. cleaned_answer_text = " ".join(whitespace_tokenize(example.answer_text))
  92. if actual_text.find(cleaned_answer_text) == -1:
  93. logger.warning(f"Could not find answer: '{actual_text}' vs. '{cleaned_answer_text}'")
  94. return []
  95. tok_to_orig_index = []
  96. orig_to_tok_index = []
  97. all_doc_tokens = []
  98. for i, token in enumerate(example.doc_tokens):
  99. orig_to_tok_index.append(len(all_doc_tokens))
  100. if tokenizer.__class__.__name__ in [
  101. "RobertaTokenizer",
  102. "LongformerTokenizer",
  103. "BartTokenizer",
  104. "RobertaTokenizerFast",
  105. "LongformerTokenizerFast",
  106. "BartTokenizerFast",
  107. ]:
  108. sub_tokens = tokenizer.tokenize(token, add_prefix_space=True)
  109. else:
  110. sub_tokens = tokenizer.tokenize(token)
  111. for sub_token in sub_tokens:
  112. tok_to_orig_index.append(i)
  113. all_doc_tokens.append(sub_token)
  114. if is_training and not example.is_impossible:
  115. tok_start_position = orig_to_tok_index[example.start_position]
  116. if example.end_position < len(example.doc_tokens) - 1:
  117. tok_end_position = orig_to_tok_index[example.end_position + 1] - 1
  118. else:
  119. tok_end_position = len(all_doc_tokens) - 1
  120. (tok_start_position, tok_end_position) = _improve_answer_span(
  121. all_doc_tokens, tok_start_position, tok_end_position, tokenizer, example.answer_text
  122. )
  123. spans = []
  124. truncated_query = tokenizer.encode(
  125. example.question_text, add_special_tokens=False, truncation=True, max_length=max_query_length
  126. )
  127. # Tokenizers who insert 2 SEP tokens in-between <context> & <question> need to have special handling
  128. # in the way they compute mask of added tokens.
  129. tokenizer_type = type(tokenizer).__name__.replace("Tokenizer", "").lower()
  130. sequence_added_tokens = (
  131. tokenizer.model_max_length - tokenizer.max_len_single_sentence + 1
  132. if tokenizer_type in MULTI_SEP_TOKENS_TOKENIZERS_SET
  133. else tokenizer.model_max_length - tokenizer.max_len_single_sentence
  134. )
  135. sequence_pair_added_tokens = tokenizer.model_max_length - tokenizer.max_len_sentences_pair
  136. span_doc_tokens = all_doc_tokens
  137. while len(spans) * doc_stride < len(all_doc_tokens):
  138. # Define the side we want to truncate / pad and the text/pair sorting
  139. if tokenizer.padding_side == "right":
  140. texts = truncated_query
  141. pairs = span_doc_tokens
  142. truncation = TruncationStrategy.ONLY_SECOND.value
  143. else:
  144. texts = span_doc_tokens
  145. pairs = truncated_query
  146. truncation = TruncationStrategy.ONLY_FIRST.value
  147. encoded_dict = tokenizer.encode_plus( # TODO(thom) update this logic
  148. texts,
  149. pairs,
  150. truncation=truncation,
  151. padding=padding_strategy,
  152. max_length=max_seq_length,
  153. return_overflowing_tokens=True,
  154. stride=max_seq_length - doc_stride - len(truncated_query) - sequence_pair_added_tokens,
  155. return_token_type_ids=True,
  156. )
  157. paragraph_len = min(
  158. len(all_doc_tokens) - len(spans) * doc_stride,
  159. max_seq_length - len(truncated_query) - sequence_pair_added_tokens,
  160. )
  161. if tokenizer.pad_token_id in encoded_dict["input_ids"]:
  162. if tokenizer.padding_side == "right":
  163. non_padded_ids = encoded_dict["input_ids"][: encoded_dict["input_ids"].index(tokenizer.pad_token_id)]
  164. else:
  165. last_padding_id_position = (
  166. len(encoded_dict["input_ids"]) - 1 - encoded_dict["input_ids"][::-1].index(tokenizer.pad_token_id)
  167. )
  168. non_padded_ids = encoded_dict["input_ids"][last_padding_id_position + 1 :]
  169. else:
  170. non_padded_ids = encoded_dict["input_ids"]
  171. tokens = tokenizer.convert_ids_to_tokens(non_padded_ids)
  172. token_to_orig_map = {}
  173. for i in range(paragraph_len):
  174. index = len(truncated_query) + sequence_added_tokens + i if tokenizer.padding_side == "right" else i
  175. token_to_orig_map[index] = tok_to_orig_index[len(spans) * doc_stride + i]
  176. encoded_dict["paragraph_len"] = paragraph_len
  177. encoded_dict["tokens"] = tokens
  178. encoded_dict["token_to_orig_map"] = token_to_orig_map
  179. encoded_dict["truncated_query_with_special_tokens_length"] = len(truncated_query) + sequence_added_tokens
  180. encoded_dict["token_is_max_context"] = {}
  181. encoded_dict["start"] = len(spans) * doc_stride
  182. encoded_dict["length"] = paragraph_len
  183. spans.append(encoded_dict)
  184. if "overflowing_tokens" not in encoded_dict or (
  185. "overflowing_tokens" in encoded_dict and len(encoded_dict["overflowing_tokens"]) == 0
  186. ):
  187. break
  188. span_doc_tokens = encoded_dict["overflowing_tokens"]
  189. for doc_span_index in range(len(spans)):
  190. for j in range(spans[doc_span_index]["paragraph_len"]):
  191. is_max_context = _new_check_is_max_context(spans, doc_span_index, doc_span_index * doc_stride + j)
  192. index = (
  193. j
  194. if tokenizer.padding_side == "left"
  195. else spans[doc_span_index]["truncated_query_with_special_tokens_length"] + j
  196. )
  197. spans[doc_span_index]["token_is_max_context"][index] = is_max_context
  198. for span in spans:
  199. # Identify the position of the CLS token
  200. cls_index = span["input_ids"].index(tokenizer.cls_token_id)
  201. # p_mask: mask with 1 for token than cannot be in the answer (0 for token which can be in an answer)
  202. # Original TF implementation also keep the classification token (set to 0)
  203. p_mask = np.ones_like(span["token_type_ids"])
  204. if tokenizer.padding_side == "right":
  205. p_mask[len(truncated_query) + sequence_added_tokens :] = 0
  206. else:
  207. p_mask[-len(span["tokens"]) : -(len(truncated_query) + sequence_added_tokens)] = 0
  208. pad_token_indices = np.where(span["input_ids"] == tokenizer.pad_token_id)
  209. special_token_indices = np.asarray(
  210. tokenizer.get_special_tokens_mask(span["input_ids"], already_has_special_tokens=True)
  211. ).nonzero()
  212. p_mask[pad_token_indices] = 1
  213. p_mask[special_token_indices] = 1
  214. # Set the cls index to 0: the CLS index can be used for impossible answers
  215. p_mask[cls_index] = 0
  216. span_is_impossible = example.is_impossible
  217. start_position = 0
  218. end_position = 0
  219. if is_training and not span_is_impossible:
  220. # For training, if our document chunk does not contain an annotation
  221. # we throw it out, since there is nothing to predict.
  222. doc_start = span["start"]
  223. doc_end = span["start"] + span["length"] - 1
  224. out_of_span = False
  225. if not (tok_start_position >= doc_start and tok_end_position <= doc_end):
  226. out_of_span = True
  227. if out_of_span:
  228. start_position = cls_index
  229. end_position = cls_index
  230. span_is_impossible = True
  231. else:
  232. if tokenizer.padding_side == "left":
  233. doc_offset = 0
  234. else:
  235. doc_offset = len(truncated_query) + sequence_added_tokens
  236. start_position = tok_start_position - doc_start + doc_offset
  237. end_position = tok_end_position - doc_start + doc_offset
  238. features.append(
  239. SquadFeatures(
  240. span["input_ids"],
  241. span["attention_mask"],
  242. span["token_type_ids"],
  243. cls_index,
  244. p_mask.tolist(),
  245. example_index=0, # Can not set unique_id and example_index here. They will be set after multiple processing.
  246. unique_id=0,
  247. paragraph_len=span["paragraph_len"],
  248. token_is_max_context=span["token_is_max_context"],
  249. tokens=span["tokens"],
  250. token_to_orig_map=span["token_to_orig_map"],
  251. start_position=start_position,
  252. end_position=end_position,
  253. is_impossible=span_is_impossible,
  254. qas_id=example.qas_id,
  255. )
  256. )
  257. return features
  258. def squad_convert_example_to_features_init(tokenizer_for_convert: PreTrainedTokenizerBase):
  259. global tokenizer
  260. tokenizer = tokenizer_for_convert
  261. def squad_convert_examples_to_features(
  262. examples,
  263. tokenizer,
  264. max_seq_length,
  265. doc_stride,
  266. max_query_length,
  267. is_training,
  268. padding_strategy="max_length",
  269. return_dataset=False,
  270. threads=1,
  271. tqdm_enabled=True,
  272. ):
  273. """
  274. Converts a list of examples into a list of features that can be directly given as input to a model. It is
  275. model-dependant and takes advantage of many of the tokenizer's features to create the model's inputs.
  276. Args:
  277. examples: list of [`~data.processors.squad.SquadExample`]
  278. tokenizer: an instance of a child of [`PreTrainedTokenizer`]
  279. max_seq_length: The maximum sequence length of the inputs.
  280. doc_stride: The stride used when the context is too large and is split across several features.
  281. max_query_length: The maximum length of the query.
  282. is_training: whether to create features for model evaluation or model training.
  283. padding_strategy: Default to "max_length". Which padding strategy to use
  284. return_dataset: Default False. Either 'pt' or 'tf'.
  285. if 'pt': returns a torch.data.TensorDataset, if 'tf': returns a tf.data.Dataset
  286. threads: multiple processing threads.
  287. Returns:
  288. list of [`~data.processors.squad.SquadFeatures`]
  289. Example:
  290. ```python
  291. processor = SquadV2Processor()
  292. examples = processor.get_dev_examples(data_dir)
  293. features = squad_convert_examples_to_features(
  294. examples=examples,
  295. tokenizer=tokenizer,
  296. max_seq_length=args.max_seq_length,
  297. doc_stride=args.doc_stride,
  298. max_query_length=args.max_query_length,
  299. is_training=not evaluate,
  300. )
  301. ```"""
  302. # Defining helper methods
  303. features = []
  304. threads = min(threads, cpu_count())
  305. with Pool(threads, initializer=squad_convert_example_to_features_init, initargs=(tokenizer,)) as p:
  306. annotate_ = partial(
  307. squad_convert_example_to_features,
  308. max_seq_length=max_seq_length,
  309. doc_stride=doc_stride,
  310. max_query_length=max_query_length,
  311. padding_strategy=padding_strategy,
  312. is_training=is_training,
  313. )
  314. features = list(
  315. tqdm(
  316. p.imap(annotate_, examples, chunksize=32),
  317. total=len(examples),
  318. desc="convert squad examples to features",
  319. disable=not tqdm_enabled,
  320. )
  321. )
  322. new_features = []
  323. unique_id = 1000000000
  324. example_index = 0
  325. for example_features in tqdm(
  326. features, total=len(features), desc="add example index and unique id", disable=not tqdm_enabled
  327. ):
  328. if not example_features:
  329. continue
  330. for example_feature in example_features:
  331. example_feature.example_index = example_index
  332. example_feature.unique_id = unique_id
  333. new_features.append(example_feature)
  334. unique_id += 1
  335. example_index += 1
  336. features = new_features
  337. del new_features
  338. if return_dataset == "pt":
  339. if not is_torch_available():
  340. raise RuntimeError("PyTorch must be installed to return a PyTorch dataset.")
  341. # Convert to Tensors and build dataset
  342. all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long)
  343. all_attention_masks = torch.tensor([f.attention_mask for f in features], dtype=torch.long)
  344. all_token_type_ids = torch.tensor([f.token_type_ids for f in features], dtype=torch.long)
  345. all_cls_index = torch.tensor([f.cls_index for f in features], dtype=torch.long)
  346. all_p_mask = torch.tensor([f.p_mask for f in features], dtype=torch.float)
  347. all_is_impossible = torch.tensor([f.is_impossible for f in features], dtype=torch.float)
  348. if not is_training:
  349. all_feature_index = torch.arange(all_input_ids.size(0), dtype=torch.long)
  350. dataset = TensorDataset(
  351. all_input_ids, all_attention_masks, all_token_type_ids, all_feature_index, all_cls_index, all_p_mask
  352. )
  353. else:
  354. all_start_positions = torch.tensor([f.start_position for f in features], dtype=torch.long)
  355. all_end_positions = torch.tensor([f.end_position for f in features], dtype=torch.long)
  356. dataset = TensorDataset(
  357. all_input_ids,
  358. all_attention_masks,
  359. all_token_type_ids,
  360. all_start_positions,
  361. all_end_positions,
  362. all_cls_index,
  363. all_p_mask,
  364. all_is_impossible,
  365. )
  366. return features, dataset
  367. elif return_dataset == "tf":
  368. if not is_tf_available():
  369. raise RuntimeError("TensorFlow must be installed to return a TensorFlow dataset.")
  370. def gen():
  371. for i, ex in enumerate(features):
  372. if ex.token_type_ids is None:
  373. yield (
  374. {
  375. "input_ids": ex.input_ids,
  376. "attention_mask": ex.attention_mask,
  377. "feature_index": i,
  378. "qas_id": ex.qas_id,
  379. },
  380. {
  381. "start_positions": ex.start_position,
  382. "end_positions": ex.end_position,
  383. "cls_index": ex.cls_index,
  384. "p_mask": ex.p_mask,
  385. "is_impossible": ex.is_impossible,
  386. },
  387. )
  388. else:
  389. yield (
  390. {
  391. "input_ids": ex.input_ids,
  392. "attention_mask": ex.attention_mask,
  393. "token_type_ids": ex.token_type_ids,
  394. "feature_index": i,
  395. "qas_id": ex.qas_id,
  396. },
  397. {
  398. "start_positions": ex.start_position,
  399. "end_positions": ex.end_position,
  400. "cls_index": ex.cls_index,
  401. "p_mask": ex.p_mask,
  402. "is_impossible": ex.is_impossible,
  403. },
  404. )
  405. # Why have we split the batch into a tuple? PyTorch just has a list of tensors.
  406. if "token_type_ids" in tokenizer.model_input_names:
  407. train_types = (
  408. {
  409. "input_ids": tf.int32,
  410. "attention_mask": tf.int32,
  411. "token_type_ids": tf.int32,
  412. "feature_index": tf.int64,
  413. "qas_id": tf.string,
  414. },
  415. {
  416. "start_positions": tf.int64,
  417. "end_positions": tf.int64,
  418. "cls_index": tf.int64,
  419. "p_mask": tf.int32,
  420. "is_impossible": tf.int32,
  421. },
  422. )
  423. train_shapes = (
  424. {
  425. "input_ids": tf.TensorShape([None]),
  426. "attention_mask": tf.TensorShape([None]),
  427. "token_type_ids": tf.TensorShape([None]),
  428. "feature_index": tf.TensorShape([]),
  429. "qas_id": tf.TensorShape([]),
  430. },
  431. {
  432. "start_positions": tf.TensorShape([]),
  433. "end_positions": tf.TensorShape([]),
  434. "cls_index": tf.TensorShape([]),
  435. "p_mask": tf.TensorShape([None]),
  436. "is_impossible": tf.TensorShape([]),
  437. },
  438. )
  439. else:
  440. train_types = (
  441. {"input_ids": tf.int32, "attention_mask": tf.int32, "feature_index": tf.int64, "qas_id": tf.string},
  442. {
  443. "start_positions": tf.int64,
  444. "end_positions": tf.int64,
  445. "cls_index": tf.int64,
  446. "p_mask": tf.int32,
  447. "is_impossible": tf.int32,
  448. },
  449. )
  450. train_shapes = (
  451. {
  452. "input_ids": tf.TensorShape([None]),
  453. "attention_mask": tf.TensorShape([None]),
  454. "feature_index": tf.TensorShape([]),
  455. "qas_id": tf.TensorShape([]),
  456. },
  457. {
  458. "start_positions": tf.TensorShape([]),
  459. "end_positions": tf.TensorShape([]),
  460. "cls_index": tf.TensorShape([]),
  461. "p_mask": tf.TensorShape([None]),
  462. "is_impossible": tf.TensorShape([]),
  463. },
  464. )
  465. return tf.data.Dataset.from_generator(gen, train_types, train_shapes)
  466. else:
  467. return features
  468. class SquadProcessor(DataProcessor):
  469. """
  470. Processor for the SQuAD data set. overridden by SquadV1Processor and SquadV2Processor, used by the version 1.1 and
  471. version 2.0 of SQuAD, respectively.
  472. """
  473. train_file = None
  474. dev_file = None
  475. def _get_example_from_tensor_dict(self, tensor_dict, evaluate=False):
  476. if not evaluate:
  477. answer = tensor_dict["answers"]["text"][0].numpy().decode("utf-8")
  478. answer_start = tensor_dict["answers"]["answer_start"][0].numpy()
  479. answers = []
  480. else:
  481. answers = [
  482. {"answer_start": start.numpy(), "text": text.numpy().decode("utf-8")}
  483. for start, text in zip(tensor_dict["answers"]["answer_start"], tensor_dict["answers"]["text"])
  484. ]
  485. answer = None
  486. answer_start = None
  487. return SquadExample(
  488. qas_id=tensor_dict["id"].numpy().decode("utf-8"),
  489. question_text=tensor_dict["question"].numpy().decode("utf-8"),
  490. context_text=tensor_dict["context"].numpy().decode("utf-8"),
  491. answer_text=answer,
  492. start_position_character=answer_start,
  493. title=tensor_dict["title"].numpy().decode("utf-8"),
  494. answers=answers,
  495. )
  496. def get_examples_from_dataset(self, dataset, evaluate=False):
  497. """
  498. Creates a list of [`~data.processors.squad.SquadExample`] using a TFDS dataset.
  499. Args:
  500. dataset: The tfds dataset loaded from *tensorflow_datasets.load("squad")*
  501. evaluate: Boolean specifying if in evaluation mode or in training mode
  502. Returns:
  503. List of SquadExample
  504. Examples:
  505. ```python
  506. >>> import tensorflow_datasets as tfds
  507. >>> dataset = tfds.load("squad")
  508. >>> training_examples = get_examples_from_dataset(dataset, evaluate=False)
  509. >>> evaluation_examples = get_examples_from_dataset(dataset, evaluate=True)
  510. ```"""
  511. if evaluate:
  512. dataset = dataset["validation"]
  513. else:
  514. dataset = dataset["train"]
  515. examples = []
  516. for tensor_dict in tqdm(dataset):
  517. examples.append(self._get_example_from_tensor_dict(tensor_dict, evaluate=evaluate))
  518. return examples
  519. def get_train_examples(self, data_dir, filename=None):
  520. """
  521. Returns the training examples from the data directory.
  522. Args:
  523. data_dir: Directory containing the data files used for training and evaluating.
  524. filename: None by default, specify this if the training file has a different name than the original one
  525. which is `train-v1.1.json` and `train-v2.0.json` for squad versions 1.1 and 2.0 respectively.
  526. """
  527. if data_dir is None:
  528. data_dir = ""
  529. if self.train_file is None:
  530. raise ValueError("SquadProcessor should be instantiated via SquadV1Processor or SquadV2Processor")
  531. with open(
  532. os.path.join(data_dir, self.train_file if filename is None else filename), "r", encoding="utf-8"
  533. ) as reader:
  534. input_data = json.load(reader)["data"]
  535. return self._create_examples(input_data, "train")
  536. def get_dev_examples(self, data_dir, filename=None):
  537. """
  538. Returns the evaluation example from the data directory.
  539. Args:
  540. data_dir: Directory containing the data files used for training and evaluating.
  541. filename: None by default, specify this if the evaluation file has a different name than the original one
  542. which is `dev-v1.1.json` and `dev-v2.0.json` for squad versions 1.1 and 2.0 respectively.
  543. """
  544. if data_dir is None:
  545. data_dir = ""
  546. if self.dev_file is None:
  547. raise ValueError("SquadProcessor should be instantiated via SquadV1Processor or SquadV2Processor")
  548. with open(
  549. os.path.join(data_dir, self.dev_file if filename is None else filename), "r", encoding="utf-8"
  550. ) as reader:
  551. input_data = json.load(reader)["data"]
  552. return self._create_examples(input_data, "dev")
  553. def _create_examples(self, input_data, set_type):
  554. is_training = set_type == "train"
  555. examples = []
  556. for entry in tqdm(input_data):
  557. title = entry["title"]
  558. for paragraph in entry["paragraphs"]:
  559. context_text = paragraph["context"]
  560. for qa in paragraph["qas"]:
  561. qas_id = qa["id"]
  562. question_text = qa["question"]
  563. start_position_character = None
  564. answer_text = None
  565. answers = []
  566. is_impossible = qa.get("is_impossible", False)
  567. if not is_impossible:
  568. if is_training:
  569. answer = qa["answers"][0]
  570. answer_text = answer["text"]
  571. start_position_character = answer["answer_start"]
  572. else:
  573. answers = qa["answers"]
  574. example = SquadExample(
  575. qas_id=qas_id,
  576. question_text=question_text,
  577. context_text=context_text,
  578. answer_text=answer_text,
  579. start_position_character=start_position_character,
  580. title=title,
  581. is_impossible=is_impossible,
  582. answers=answers,
  583. )
  584. examples.append(example)
  585. return examples
  586. class SquadV1Processor(SquadProcessor):
  587. train_file = "train-v1.1.json"
  588. dev_file = "dev-v1.1.json"
  589. class SquadV2Processor(SquadProcessor):
  590. train_file = "train-v2.0.json"
  591. dev_file = "dev-v2.0.json"
  592. class SquadExample:
  593. """
  594. A single training/test example for the Squad dataset, as loaded from disk.
  595. Args:
  596. qas_id: The example's unique identifier
  597. question_text: The question string
  598. context_text: The context string
  599. answer_text: The answer string
  600. start_position_character: The character position of the start of the answer
  601. title: The title of the example
  602. answers: None by default, this is used during evaluation. Holds answers as well as their start positions.
  603. is_impossible: False by default, set to True if the example has no possible answer.
  604. """
  605. def __init__(
  606. self,
  607. qas_id,
  608. question_text,
  609. context_text,
  610. answer_text,
  611. start_position_character,
  612. title,
  613. answers=[],
  614. is_impossible=False,
  615. ):
  616. self.qas_id = qas_id
  617. self.question_text = question_text
  618. self.context_text = context_text
  619. self.answer_text = answer_text
  620. self.title = title
  621. self.is_impossible = is_impossible
  622. self.answers = answers
  623. self.start_position, self.end_position = 0, 0
  624. doc_tokens = []
  625. char_to_word_offset = []
  626. prev_is_whitespace = True
  627. # Split on whitespace so that different tokens may be attributed to their original position.
  628. for c in self.context_text:
  629. if _is_whitespace(c):
  630. prev_is_whitespace = True
  631. else:
  632. if prev_is_whitespace:
  633. doc_tokens.append(c)
  634. else:
  635. doc_tokens[-1] += c
  636. prev_is_whitespace = False
  637. char_to_word_offset.append(len(doc_tokens) - 1)
  638. self.doc_tokens = doc_tokens
  639. self.char_to_word_offset = char_to_word_offset
  640. # Start and end positions only has a value during evaluation.
  641. if start_position_character is not None and not is_impossible:
  642. self.start_position = char_to_word_offset[start_position_character]
  643. self.end_position = char_to_word_offset[
  644. min(start_position_character + len(answer_text) - 1, len(char_to_word_offset) - 1)
  645. ]
  646. class SquadFeatures:
  647. """
  648. Single squad example features to be fed to a model. Those features are model-specific and can be crafted from
  649. [`~data.processors.squad.SquadExample`] using the
  650. :method:*~transformers.data.processors.squad.squad_convert_examples_to_features* method.
  651. Args:
  652. input_ids: Indices of input sequence tokens in the vocabulary.
  653. attention_mask: Mask to avoid performing attention on padding token indices.
  654. token_type_ids: Segment token indices to indicate first and second portions of the inputs.
  655. cls_index: the index of the CLS token.
  656. p_mask: Mask identifying tokens that can be answers vs. tokens that cannot.
  657. Mask with 1 for tokens than cannot be in the answer and 0 for token that can be in an answer
  658. example_index: the index of the example
  659. unique_id: The unique Feature identifier
  660. paragraph_len: The length of the context
  661. token_is_max_context:
  662. List of booleans identifying which tokens have their maximum context in this feature object. If a token
  663. does not have their maximum context in this feature object, it means that another feature object has more
  664. information related to that token and should be prioritized over this feature for that token.
  665. tokens: list of tokens corresponding to the input ids
  666. token_to_orig_map: mapping between the tokens and the original text, needed in order to identify the answer.
  667. start_position: start of the answer token index
  668. end_position: end of the answer token index
  669. encoding: optionally store the BatchEncoding with the fast-tokenizer alignment methods.
  670. """
  671. def __init__(
  672. self,
  673. input_ids,
  674. attention_mask,
  675. token_type_ids,
  676. cls_index,
  677. p_mask,
  678. example_index,
  679. unique_id,
  680. paragraph_len,
  681. token_is_max_context,
  682. tokens,
  683. token_to_orig_map,
  684. start_position,
  685. end_position,
  686. is_impossible,
  687. qas_id: str = None,
  688. encoding: BatchEncoding = None,
  689. ):
  690. self.input_ids = input_ids
  691. self.attention_mask = attention_mask
  692. self.token_type_ids = token_type_ids
  693. self.cls_index = cls_index
  694. self.p_mask = p_mask
  695. self.example_index = example_index
  696. self.unique_id = unique_id
  697. self.paragraph_len = paragraph_len
  698. self.token_is_max_context = token_is_max_context
  699. self.tokens = tokens
  700. self.token_to_orig_map = token_to_orig_map
  701. self.start_position = start_position
  702. self.end_position = end_position
  703. self.is_impossible = is_impossible
  704. self.qas_id = qas_id
  705. self.encoding = encoding
  706. class SquadResult:
  707. """
  708. Constructs a SquadResult which can be used to evaluate a model's output on the SQuAD dataset.
  709. Args:
  710. unique_id: The unique identifier corresponding to that example.
  711. start_logits: The logits corresponding to the start of the answer
  712. end_logits: The logits corresponding to the end of the answer
  713. """
  714. def __init__(self, unique_id, start_logits, end_logits, start_top_index=None, end_top_index=None, cls_logits=None):
  715. self.start_logits = start_logits
  716. self.end_logits = end_logits
  717. self.unique_id = unique_id
  718. if start_top_index:
  719. self.start_top_index = start_top_index
  720. self.end_top_index = end_top_index
  721. self.cls_logits = cls_logits