squad.py 28 KB

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