data_collator.py 103 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182
  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 multiprocessing as mp
  15. import random
  16. import warnings
  17. from collections.abc import Mapping
  18. from dataclasses import dataclass
  19. from random import randint
  20. from typing import Any, Callable, Optional, Union
  21. import numpy as np
  22. from ..tokenization_utils_base import PreTrainedTokenizerBase
  23. from ..utils import PaddingStrategy
  24. InputDataClass = Any
  25. """
  26. A DataCollator is a function that takes a list of samples from a Dataset and collate them into a batch, as a dictionary
  27. of PyTorch/TensorFlow tensors or NumPy arrays.
  28. """
  29. DataCollator = Callable[[list[InputDataClass]], dict[str, Any]]
  30. class DataCollatorMixin:
  31. def __call__(self, features, return_tensors: Optional[str] = None):
  32. if return_tensors is None:
  33. return_tensors = self.return_tensors
  34. if return_tensors == "tf":
  35. return self.tf_call(features)
  36. elif return_tensors == "pt":
  37. return self.torch_call(features)
  38. elif return_tensors == "np":
  39. return self.numpy_call(features)
  40. else:
  41. raise ValueError(f"Framework '{return_tensors}' not recognized!")
  42. def pad_without_fast_tokenizer_warning(tokenizer, *pad_args, **pad_kwargs):
  43. """
  44. Pads without triggering the warning about how using the pad function is sub-optimal when using a fast tokenizer.
  45. """
  46. # To avoid errors when using Feature extractors
  47. if not hasattr(tokenizer, "deprecation_warnings"):
  48. return tokenizer.pad(*pad_args, **pad_kwargs)
  49. # Save the state of the warning, then disable it
  50. warning_state = tokenizer.deprecation_warnings.get("Asking-to-pad-a-fast-tokenizer", False)
  51. tokenizer.deprecation_warnings["Asking-to-pad-a-fast-tokenizer"] = True
  52. try:
  53. padded = tokenizer.pad(*pad_args, **pad_kwargs)
  54. finally:
  55. # Restore the state of the warning.
  56. tokenizer.deprecation_warnings["Asking-to-pad-a-fast-tokenizer"] = warning_state
  57. return padded
  58. def default_data_collator(features: list[InputDataClass], return_tensors="pt") -> dict[str, Any]:
  59. """
  60. Very simple data collator that simply collates batches of dict-like objects and performs special handling for
  61. potential keys named:
  62. - `label`: handles a single value (int or float) per object
  63. - `label_ids`: handles a list of values per object
  64. Does not do any additional preprocessing: property names of the input object will be used as corresponding inputs
  65. to the model. See glue and ner for example of how it's useful.
  66. """
  67. # In this function we'll make the assumption that all `features` in the batch
  68. # have the same attributes.
  69. # So we will look at the first element as a proxy for what attributes exist
  70. # on the whole batch.
  71. if return_tensors == "pt":
  72. return torch_default_data_collator(features)
  73. elif return_tensors == "tf":
  74. return tf_default_data_collator(features)
  75. elif return_tensors == "np":
  76. return numpy_default_data_collator(features)
  77. @dataclass
  78. class DefaultDataCollator(DataCollatorMixin):
  79. """
  80. Very simple data collator that simply collates batches of dict-like objects and performs special handling for
  81. potential keys named:
  82. - `label`: handles a single value (int or float) per object
  83. - `label_ids`: handles a list of values per object
  84. Does not do any additional preprocessing: property names of the input object will be used as corresponding inputs
  85. to the model. See glue and ner for example of how it's useful.
  86. This is an object (like other data collators) rather than a pure function like default_data_collator. This can be
  87. helpful if you need to set a return_tensors value at initialization.
  88. Args:
  89. return_tensors (`str`, *optional*, defaults to `"pt"`):
  90. The type of Tensor to return. Allowable values are "np", "pt" and "tf".
  91. """
  92. return_tensors: str = "pt"
  93. def __call__(self, features: list[dict[str, Any]], return_tensors=None) -> dict[str, Any]:
  94. if return_tensors is None:
  95. return_tensors = self.return_tensors
  96. return default_data_collator(features, return_tensors)
  97. def torch_default_data_collator(features: list[InputDataClass]) -> dict[str, Any]:
  98. import torch
  99. if not isinstance(features[0], Mapping):
  100. features = [vars(f) for f in features]
  101. first = features[0]
  102. batch = {}
  103. # Special handling for labels.
  104. # Ensure that tensor is created with the correct type
  105. # (it should be automatically the case, but let's make sure of it.)
  106. if "label" in first and first["label"] is not None:
  107. label = first["label"].item() if isinstance(first["label"], torch.Tensor) else first["label"]
  108. dtype = torch.long if isinstance(label, int) else torch.float
  109. batch["labels"] = torch.tensor([f["label"] for f in features], dtype=dtype)
  110. elif "label_ids" in first and first["label_ids"] is not None:
  111. if isinstance(first["label_ids"], torch.Tensor):
  112. batch["labels"] = torch.stack([f["label_ids"] for f in features])
  113. else:
  114. dtype = torch.long if isinstance(first["label_ids"][0], int) else torch.float
  115. batch["labels"] = torch.tensor([f["label_ids"] for f in features], dtype=dtype)
  116. # Handling of all other possible keys.
  117. # Again, we will use the first element to figure out which key/values are not None for this model.
  118. for k, v in first.items():
  119. if k not in ("label", "label_ids") and v is not None and not isinstance(v, str):
  120. if isinstance(v, torch.Tensor):
  121. batch[k] = torch.stack([f[k] for f in features])
  122. elif isinstance(v, np.ndarray):
  123. batch[k] = torch.from_numpy(np.stack([f[k] for f in features]))
  124. else:
  125. batch[k] = torch.tensor([f[k] for f in features])
  126. return batch
  127. def tf_default_data_collator(features: list[InputDataClass]) -> dict[str, Any]:
  128. import tensorflow as tf
  129. if not isinstance(features[0], Mapping):
  130. features = [vars(f) for f in features]
  131. first = features[0]
  132. batch = {}
  133. # Special handling for labels.
  134. # Ensure that tensor is created with the correct type
  135. # (it should be automatically the case, but let's make sure of it.)
  136. if "label" in first and first["label"] is not None:
  137. label_col_name = "label"
  138. elif "label_ids" in first and first["label_ids"] is not None:
  139. label_col_name = "label_ids"
  140. elif "labels" in first and first["labels"] is not None:
  141. label_col_name = "labels"
  142. else:
  143. label_col_name = None
  144. if label_col_name is not None:
  145. if isinstance(first[label_col_name], tf.Tensor):
  146. dtype = tf.int64 if first[label_col_name].dtype.is_integer else tf.float32
  147. elif isinstance(first[label_col_name], (np.ndarray, np.generic)):
  148. dtype = tf.int64 if np.issubdtype(first[label_col_name].dtype, np.integer) else tf.float32
  149. elif isinstance(first[label_col_name], (tuple, list)):
  150. dtype = tf.int64 if isinstance(first[label_col_name][0], int) else tf.float32
  151. else:
  152. dtype = tf.int64 if isinstance(first[label_col_name], int) else tf.float32
  153. batch["labels"] = tf.convert_to_tensor([f[label_col_name] for f in features], dtype=dtype)
  154. # Handling of all other possible keys.
  155. # Again, we will use the first element to figure out which key/values are not None for this model.
  156. for k, v in first.items():
  157. if k not in ("label", "label_ids", "labels") and v is not None and not isinstance(v, str):
  158. if isinstance(v, (tf.Tensor, np.ndarray)):
  159. batch[k] = tf.stack([f[k] for f in features])
  160. else:
  161. batch[k] = tf.convert_to_tensor([f[k] for f in features])
  162. return batch
  163. def numpy_default_data_collator(features: list[InputDataClass]) -> dict[str, Any]:
  164. if not isinstance(features[0], Mapping):
  165. features = [vars(f) for f in features]
  166. first = features[0]
  167. batch = {}
  168. # Special handling for labels.
  169. # Ensure that tensor is created with the correct type
  170. # (it should be automatically the case, but let's make sure of it.)
  171. if "label" in first and first["label"] is not None:
  172. label = first["label"].item() if isinstance(first["label"], np.ndarray) else first["label"]
  173. dtype = np.int64 if isinstance(label, int) else np.float32
  174. batch["labels"] = np.array([f["label"] for f in features], dtype=dtype)
  175. elif "label_ids" in first and first["label_ids"] is not None:
  176. if isinstance(first["label_ids"], np.ndarray):
  177. batch["labels"] = np.stack([f["label_ids"] for f in features])
  178. else:
  179. dtype = np.int64 if isinstance(first["label_ids"][0], int) else np.float32
  180. batch["labels"] = np.array([f["label_ids"] for f in features], dtype=dtype)
  181. # Handling of all other possible keys.
  182. # Again, we will use the first element to figure out which key/values are not None for this model.
  183. for k, v in first.items():
  184. if k not in ("label", "label_ids") and v is not None and not isinstance(v, str):
  185. if isinstance(v, np.ndarray):
  186. batch[k] = np.stack([f[k] for f in features])
  187. else:
  188. batch[k] = np.array([f[k] for f in features])
  189. return batch
  190. @dataclass
  191. class DataCollatorWithPadding:
  192. """
  193. Data collator that will dynamically pad the inputs received.
  194. Args:
  195. tokenizer ([`PreTrainedTokenizer`] or [`PreTrainedTokenizerFast`]):
  196. The tokenizer used for encoding the data.
  197. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):
  198. Select a strategy to pad the returned sequences (according to the model's padding side and padding index)
  199. among:
  200. - `True` or `'longest'` (default): Pad to the longest sequence in the batch (or no padding if only a single
  201. sequence is provided).
  202. - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
  203. acceptable input length for the model if that argument is not provided.
  204. - `False` or `'do_not_pad'`: No padding (i.e., can output a batch with sequences of different lengths).
  205. max_length (`int`, *optional*):
  206. Maximum length of the returned list and optionally padding length (see above).
  207. pad_to_multiple_of (`int`, *optional*):
  208. If set will pad the sequence to a multiple of the provided value.
  209. This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >=
  210. 7.0 (Volta).
  211. return_tensors (`str`, *optional*, defaults to `"pt"`):
  212. The type of Tensor to return. Allowable values are "np", "pt" and "tf".
  213. """
  214. tokenizer: PreTrainedTokenizerBase
  215. padding: Union[bool, str, PaddingStrategy] = True
  216. max_length: Optional[int] = None
  217. pad_to_multiple_of: Optional[int] = None
  218. return_tensors: str = "pt"
  219. def __call__(self, features: list[dict[str, Any]]) -> dict[str, Any]:
  220. batch = pad_without_fast_tokenizer_warning(
  221. self.tokenizer,
  222. features,
  223. padding=self.padding,
  224. max_length=self.max_length,
  225. pad_to_multiple_of=self.pad_to_multiple_of,
  226. return_tensors=self.return_tensors,
  227. )
  228. if "label" in batch:
  229. batch["labels"] = batch["label"]
  230. del batch["label"]
  231. if "label_ids" in batch:
  232. batch["labels"] = batch["label_ids"]
  233. del batch["label_ids"]
  234. return batch
  235. @dataclass
  236. class DataCollatorForTokenClassification(DataCollatorMixin):
  237. """
  238. Data collator that will dynamically pad the inputs received, as well as the labels.
  239. Args:
  240. tokenizer ([`PreTrainedTokenizer`] or [`PreTrainedTokenizerFast`]):
  241. The tokenizer used for encoding the data.
  242. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):
  243. Select a strategy to pad the returned sequences (according to the model's padding side and padding index)
  244. among:
  245. - `True` or `'longest'` (default): Pad to the longest sequence in the batch (or no padding if only a single
  246. sequence is provided).
  247. - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
  248. acceptable input length for the model if that argument is not provided.
  249. - `False` or `'do_not_pad'`: No padding (i.e., can output a batch with sequences of different lengths).
  250. max_length (`int`, *optional*):
  251. Maximum length of the returned list and optionally padding length (see above).
  252. pad_to_multiple_of (`int`, *optional*):
  253. If set will pad the sequence to a multiple of the provided value.
  254. This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >=
  255. 7.0 (Volta).
  256. label_pad_token_id (`int`, *optional*, defaults to -100):
  257. The id to use when padding the labels (-100 will be automatically ignore by PyTorch loss functions).
  258. return_tensors (`str`, *optional*, defaults to `"pt"`):
  259. The type of Tensor to return. Allowable values are "np", "pt" and "tf".
  260. """
  261. tokenizer: PreTrainedTokenizerBase
  262. padding: Union[bool, str, PaddingStrategy] = True
  263. max_length: Optional[int] = None
  264. pad_to_multiple_of: Optional[int] = None
  265. label_pad_token_id: int = -100
  266. return_tensors: str = "pt"
  267. def torch_call(self, features):
  268. import torch
  269. label_name = "label" if "label" in features[0] else "labels"
  270. labels = [feature[label_name] for feature in features] if label_name in features[0] else None
  271. no_labels_features = [{k: v for k, v in feature.items() if k != label_name} for feature in features]
  272. batch = pad_without_fast_tokenizer_warning(
  273. self.tokenizer,
  274. no_labels_features,
  275. padding=self.padding,
  276. max_length=self.max_length,
  277. pad_to_multiple_of=self.pad_to_multiple_of,
  278. return_tensors="pt",
  279. )
  280. if labels is None:
  281. return batch
  282. sequence_length = batch["input_ids"].shape[1]
  283. padding_side = self.tokenizer.padding_side
  284. def to_list(tensor_or_iterable):
  285. if isinstance(tensor_or_iterable, torch.Tensor):
  286. return tensor_or_iterable.tolist()
  287. return list(tensor_or_iterable)
  288. if padding_side == "right":
  289. batch[label_name] = [
  290. to_list(label) + [self.label_pad_token_id] * (sequence_length - len(label)) for label in labels
  291. ]
  292. else:
  293. batch[label_name] = [
  294. [self.label_pad_token_id] * (sequence_length - len(label)) + to_list(label) for label in labels
  295. ]
  296. batch[label_name] = torch.tensor(batch[label_name], dtype=torch.int64)
  297. return batch
  298. def tf_call(self, features):
  299. import tensorflow as tf
  300. label_name = "label" if "label" in features[0] else "labels"
  301. labels = [feature[label_name] for feature in features] if label_name in features[0] else None
  302. batch = pad_without_fast_tokenizer_warning(
  303. self.tokenizer,
  304. features,
  305. padding=self.padding,
  306. max_length=self.max_length,
  307. pad_to_multiple_of=self.pad_to_multiple_of,
  308. # Conversion to tensors will fail if we have labels as they are not of the same length yet.
  309. return_tensors="tf" if labels is None else None,
  310. )
  311. if labels is None:
  312. return batch
  313. sequence_length = tf.convert_to_tensor(batch["input_ids"]).shape[1]
  314. padding_side = self.tokenizer.padding_side
  315. if padding_side == "right":
  316. batch["labels"] = [
  317. list(label) + [self.label_pad_token_id] * (sequence_length - len(label)) for label in labels
  318. ]
  319. else:
  320. batch["labels"] = [
  321. [self.label_pad_token_id] * (sequence_length - len(label)) + list(label) for label in labels
  322. ]
  323. batch = {k: tf.convert_to_tensor(v, dtype=tf.int64) for k, v in batch.items()}
  324. return batch
  325. def numpy_call(self, features):
  326. label_name = "label" if "label" in features[0] else "labels"
  327. labels = [feature[label_name] for feature in features] if label_name in features[0] else None
  328. batch = pad_without_fast_tokenizer_warning(
  329. self.tokenizer,
  330. features,
  331. padding=self.padding,
  332. max_length=self.max_length,
  333. pad_to_multiple_of=self.pad_to_multiple_of,
  334. # Conversion to tensors will fail if we have labels as they are not of the same length yet.
  335. return_tensors="np" if labels is None else None,
  336. )
  337. if labels is None:
  338. return batch
  339. sequence_length = np.array(batch["input_ids"]).shape[1]
  340. padding_side = self.tokenizer.padding_side
  341. if padding_side == "right":
  342. batch["labels"] = [
  343. list(label) + [self.label_pad_token_id] * (sequence_length - len(label)) for label in labels
  344. ]
  345. else:
  346. batch["labels"] = [
  347. [self.label_pad_token_id] * (sequence_length - len(label)) + list(label) for label in labels
  348. ]
  349. batch = {k: np.array(v, dtype=np.int64) for k, v in batch.items()}
  350. return batch
  351. def _torch_collate_batch(examples, tokenizer, pad_to_multiple_of: Optional[int] = None):
  352. """Collate `examples` into a batch, using the information in `tokenizer` for padding if necessary."""
  353. import torch
  354. # Tensorize if necessary.
  355. if isinstance(examples[0], (list, tuple, np.ndarray)):
  356. examples = [torch.tensor(e, dtype=torch.long) for e in examples]
  357. length_of_first = examples[0].size(0)
  358. # Check if padding is necessary.
  359. are_tensors_same_length = all(x.size(0) == length_of_first for x in examples)
  360. if are_tensors_same_length and (pad_to_multiple_of is None or length_of_first % pad_to_multiple_of == 0):
  361. if not isinstance(examples, torch.Tensor):
  362. return torch.stack(examples, dim=0)
  363. # If yes, check if we have a `pad_token`.
  364. if tokenizer.pad_token is None:
  365. raise ValueError(
  366. "You are attempting to pad samples but the tokenizer you are using"
  367. f" ({tokenizer.__class__.__name__}) does not have a pad token."
  368. )
  369. # Creating the full tensor and filling it with our data.
  370. max_length = max(x.size(0) for x in examples)
  371. if pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
  372. max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
  373. result = examples[0].new_full([len(examples), max_length], tokenizer.pad_token_id)
  374. for i, example in enumerate(examples):
  375. if tokenizer.padding_side == "right":
  376. result[i, : example.shape[0]] = example
  377. else:
  378. result[i, -example.shape[0] :] = example
  379. return result
  380. def _tf_collate_batch(examples, tokenizer, pad_to_multiple_of: Optional[int] = None):
  381. import tensorflow as tf
  382. """Collate `examples` into a batch, using the information in `tokenizer` for padding if necessary."""
  383. # Tensorize if necessary.
  384. if isinstance(examples[0], (list, tuple)):
  385. examples = [tf.convert_to_tensor(e, dtype=tf.int64) for e in examples]
  386. # Check if padding is necessary.
  387. length_of_first = len(examples[0])
  388. are_tensors_same_length = all(len(x) == length_of_first for x in examples)
  389. if are_tensors_same_length and (pad_to_multiple_of is None or length_of_first % pad_to_multiple_of == 0):
  390. return tf.stack(examples, axis=0)
  391. # If yes, check if we have a `pad_token`.
  392. if tokenizer.pad_token is None:
  393. raise ValueError(
  394. "You are attempting to pad samples but the tokenizer you are using"
  395. f" ({tokenizer.__class__.__name__}) does not have a pad token."
  396. )
  397. # Creating the full tensor and filling it with our data.
  398. max_length = max(len(x) for x in examples)
  399. if pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
  400. max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
  401. # result = examples[0].new_full([len(examples), max_length], tokenizer.pad_token_id)
  402. result = []
  403. rank = tf.rank(examples[0])
  404. paddings = np.zeros((rank, 2), dtype=np.int32)
  405. for example in examples:
  406. if tokenizer.padding_side == "right":
  407. paddings[0, 1] = max_length - len(example)
  408. else:
  409. paddings[0, 0] = max_length - len(example)
  410. result.append(tf.pad(example, paddings, constant_values=tokenizer.pad_token_id))
  411. return tf.stack(result, axis=0)
  412. def _numpy_collate_batch(examples, tokenizer, pad_to_multiple_of: Optional[int] = None):
  413. """Collate `examples` into a batch, using the information in `tokenizer` for padding if necessary."""
  414. # Tensorize if necessary.
  415. if isinstance(examples[0], (list, tuple)):
  416. examples = [np.array(e, dtype=np.int64) for e in examples]
  417. # Check if padding is necessary.
  418. length_of_first = len(examples[0])
  419. are_tensors_same_length = all(len(x) == length_of_first for x in examples)
  420. if are_tensors_same_length and (pad_to_multiple_of is None or length_of_first % pad_to_multiple_of == 0):
  421. return np.stack(examples, axis=0)
  422. # If yes, check if we have a `pad_token`.
  423. if tokenizer.pad_token is None:
  424. raise ValueError(
  425. "You are attempting to pad samples but the tokenizer you are using"
  426. f" ({tokenizer.__class__.__name__}) does not have a pad token."
  427. )
  428. # Creating the full tensor and filling it with our data.
  429. max_length = max(len(x) for x in examples)
  430. if pad_to_multiple_of is not None and (max_length % pad_to_multiple_of != 0):
  431. max_length = ((max_length // pad_to_multiple_of) + 1) * pad_to_multiple_of
  432. result = np.full(shape=(len(examples), max_length), fill_value=tokenizer.pad_token_id, dtype=examples[0].dtype)
  433. for i, example in enumerate(examples):
  434. if tokenizer.padding_side == "right":
  435. result[i, : example.shape[0]] = example
  436. else:
  437. result[i, -example.shape[0] :] = example
  438. return result
  439. @dataclass
  440. class DataCollatorForMultipleChoice(DataCollatorMixin):
  441. """
  442. Data collator that dynamically pads a batch of nested examples for multiple choice, so that all choices
  443. of all examples have the same length.
  444. Args:
  445. tokenizer ([`PreTrainedTokenizer`] or [`PreTrainedTokenizerFast`]):
  446. The tokenizer used for encoding the data.
  447. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):
  448. Select a strategy to pad the returned sequences according to the model's padding side and padding index
  449. among:
  450. - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence
  451. is provided).
  452. - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
  453. acceptable input length for the model if that argument is not provided.
  454. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
  455. lengths).
  456. max_length (`int`, *optional*):
  457. Maximum length of the returned list and optionally padding length (see above).
  458. pad_to_multiple_of (`int`, *optional*):
  459. Pad the sequence to a multiple of the provided value.
  460. This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >=
  461. 7.5 (Volta).
  462. return_tensors (`str`, *optional*, defaults to `"pt"`):
  463. The type of Tensor to return. Allowable values are "np", "pt" and "tf".
  464. """
  465. tokenizer: PreTrainedTokenizerBase
  466. padding: Union[bool, str, PaddingStrategy] = True
  467. max_length: Optional[int] = None
  468. pad_to_multiple_of: Optional[int] = None
  469. return_tensors: str = "pt"
  470. def torch_call(self, examples: list[dict[str, Any]]): # Refactored implementation from the docs.
  471. import torch
  472. # Take labels out of the examples beforehand, because they aren't nested.
  473. label_name = "label" if "label" in examples[0] else "labels"
  474. labels = [example.pop(label_name) for example in examples]
  475. batch_size = len(examples)
  476. num_choices = len(examples[0]["input_ids"])
  477. # Go from e.g. 2 examples of 2 choices [{input_ids: [[1], [2]]}, {input_ids: [[3], [4]]}]
  478. # to 4 examples [{input_ids: [1]}, {input_ids: [2]}] + [{input_ids: [3]}, {input_ids: [4]}]
  479. flat_examples = sum(
  480. ([{k: v[i] for k, v in example.items()} for i in range(num_choices)] for example in examples), start=[]
  481. )
  482. # Pad all choices of all examples as if you're padding any other batch of examples.
  483. batch = self.tokenizer.pad(
  484. flat_examples,
  485. padding=self.padding,
  486. max_length=self.max_length,
  487. pad_to_multiple_of=self.pad_to_multiple_of,
  488. return_tensors="pt",
  489. )
  490. # Reshape from B*C x L into B x C x L, and add the labels back in.
  491. batch = {k: v.view(batch_size, num_choices, -1) for k, v in batch.items()}
  492. batch["labels"] = torch.tensor(labels, dtype=torch.int64)
  493. return batch
  494. def tf_call(self, features): # Implementation taken from the docs.
  495. import tensorflow as tf
  496. label_name = "label" if "label" in features[0] else "labels"
  497. labels = [feature.pop(label_name) for feature in features]
  498. batch_size = len(features)
  499. num_choices = len(features[0]["input_ids"])
  500. flattened_features = [
  501. [{k: v[i] for k, v in feature.items()} for i in range(num_choices)] for feature in features
  502. ]
  503. flattened_features = sum(flattened_features, []) # Sometimes written as list(chain(*flattened_features))
  504. batch = self.tokenizer.pad(
  505. flattened_features,
  506. padding=self.padding,
  507. max_length=self.max_length,
  508. pad_to_multiple_of=self.pad_to_multiple_of,
  509. return_tensors="tf",
  510. )
  511. batch = {k: tf.reshape(v, (batch_size, num_choices, -1)) for k, v in batch.items()}
  512. batch["labels"] = tf.convert_to_tensor(labels, dtype=tf.int64)
  513. return batch
  514. @dataclass
  515. class DataCollatorForSeq2Seq:
  516. """
  517. Data collator that will dynamically pad the inputs received, as well as the labels.
  518. Args:
  519. tokenizer ([`PreTrainedTokenizer`] or [`PreTrainedTokenizerFast`]):
  520. The tokenizer used for encoding the data.
  521. model ([`PreTrainedModel`], *optional*):
  522. The model that is being trained. If set and has the *prepare_decoder_input_ids_from_labels*, use it to
  523. prepare the *decoder_input_ids*
  524. This is useful when using *label_smoothing* to avoid calculating loss twice.
  525. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):
  526. Select a strategy to pad the returned sequences (according to the model's padding side and padding index)
  527. among:
  528. - `True` or `'longest'` (default): Pad to the longest sequence in the batch (or no padding if only a single
  529. sequence is provided).
  530. - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
  531. acceptable input length for the model if that argument is not provided.
  532. - `False` or `'do_not_pad'`: No padding (i.e., can output a batch with sequences of different lengths).
  533. max_length (`int`, *optional*):
  534. Maximum length of the returned list and optionally padding length (see above).
  535. pad_to_multiple_of (`int`, *optional*):
  536. If set will pad the sequence to a multiple of the provided value.
  537. This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >=
  538. 7.0 (Volta).
  539. label_pad_token_id (`int`, *optional*, defaults to -100):
  540. The id to use when padding the labels (-100 will be automatically ignored by PyTorch loss functions).
  541. return_tensors (`str`, *optional*, defaults to `"pt"`):
  542. The type of Tensor to return. Allowable values are "np", "pt" and "tf".
  543. """
  544. tokenizer: PreTrainedTokenizerBase
  545. model: Optional[Any] = None
  546. padding: Union[bool, str, PaddingStrategy] = True
  547. max_length: Optional[int] = None
  548. pad_to_multiple_of: Optional[int] = None
  549. label_pad_token_id: int = -100
  550. return_tensors: str = "pt"
  551. def __call__(self, features, return_tensors=None):
  552. if return_tensors is None:
  553. return_tensors = self.return_tensors
  554. label_name = "label" if "label" in features[0] else "labels"
  555. labels = [feature[label_name] for feature in features] if label_name in features[0] else None
  556. # reconvert list[None] to None if necessary
  557. # this might occur when we pass {..., "labels": None}
  558. if labels is not None and all(label is None for label in labels):
  559. labels = None
  560. non_labels_features = [{k: v for k, v in feature.items() if k != label_name} for feature in features]
  561. # run through tokenizer without labels to ensure no side effects
  562. batch = pad_without_fast_tokenizer_warning(
  563. self.tokenizer,
  564. non_labels_features,
  565. padding=self.padding,
  566. max_length=self.max_length,
  567. pad_to_multiple_of=self.pad_to_multiple_of,
  568. return_tensors=return_tensors,
  569. )
  570. # we have to pad the labels manually as we cannot rely on `tokenizer.pad` and we need them to be of the same length to return tensors
  571. no_padding = self.padding is False or self.padding == PaddingStrategy.DO_NOT_PAD
  572. if labels is not None:
  573. if no_padding:
  574. if isinstance(features[0][label_name], list):
  575. batch["labels"] = list(labels)
  576. else:
  577. batch["labels"] = [np.concatenate([label, []]) for label in labels]
  578. else:
  579. max_padding = self.padding == PaddingStrategy.MAX_LENGTH and self.max_length is not None
  580. max_label_length = max(len(l) for l in labels) if not max_padding else self.max_length
  581. if self.pad_to_multiple_of is not None:
  582. max_label_length = (
  583. (max_label_length + self.pad_to_multiple_of - 1)
  584. // self.pad_to_multiple_of
  585. * self.pad_to_multiple_of
  586. )
  587. padding_side = self.tokenizer.padding_side
  588. if isinstance(features[0][label_name], list):
  589. batch["labels"] = [
  590. label + [self.label_pad_token_id] * (max_label_length - len(label))
  591. if padding_side == "right"
  592. else [self.label_pad_token_id] * (max_label_length - len(label)) + label
  593. for label in labels
  594. ]
  595. else:
  596. batch["labels"] = [
  597. np.concatenate(
  598. [
  599. label,
  600. np.array([self.label_pad_token_id] * (max_label_length - len(label)), dtype=np.int64),
  601. ]
  602. )
  603. if padding_side == "right"
  604. else np.concatenate(
  605. [
  606. np.array([self.label_pad_token_id] * (max_label_length - len(label)), dtype=np.int64),
  607. label,
  608. ]
  609. )
  610. for label in labels
  611. ]
  612. # reintroduce side effects via tokenizer that return respective datatypes for the `return_tensors` argument
  613. if batch.get("labels", None) is not None:
  614. if return_tensors == "pt":
  615. import torch
  616. batch["labels"] = torch.tensor(batch["labels"], dtype=torch.int64)
  617. elif return_tensors == "tf":
  618. import tensorflow as tf
  619. batch["labels"] = tf.constant(batch["labels"], dtype=tf.int64)
  620. else:
  621. batch["labels"] = np.array(batch["labels"], dtype=np.int64)
  622. else:
  623. batch["labels"] = None
  624. # prepare decoder_input_ids
  625. if (
  626. labels is not None
  627. and self.model is not None
  628. and hasattr(self.model, "prepare_decoder_input_ids_from_labels")
  629. ):
  630. decoder_input_ids = self.model.prepare_decoder_input_ids_from_labels(labels=batch["labels"])
  631. batch["decoder_input_ids"] = decoder_input_ids
  632. return batch
  633. @dataclass
  634. class DataCollatorForLanguageModeling(DataCollatorMixin):
  635. """
  636. Data collator used for language modeling. Inputs are dynamically padded to the maximum length of a batch if they
  637. are not all of the same length.
  638. Args:
  639. tokenizer ([`PreTrainedTokenizer`] or [`PreTrainedTokenizerFast`]):
  640. The tokenizer used for encoding the data.
  641. mlm (`bool`, *optional*, defaults to `True`):
  642. Whether or not to use masked language modeling. If set to `False`, the labels are the same as the inputs
  643. with the padding tokens ignored (by setting them to -100). Otherwise, the labels are -100 for non-masked
  644. tokens and the value to predict for the masked token.
  645. whole_word_mask (`bool`, *optional*, defaults to `False`):
  646. Whether or not to mask whole words instead of individual tokens.
  647. mlm_probability (`float`, *optional*, defaults to 0.15):
  648. The probability with which to (randomly) mask tokens in the input, when `mlm` is set to `True`.
  649. mask_replace_prob (`float`, *optional*, defaults to 0.8):
  650. The probability with which masked tokens are replaced by the tokenizer's mask token (e.g., `[MASK]`).
  651. Defaults to 0.8, meaning 80% of the masked tokens will be replaced with `[MASK]`.
  652. Only works when `mlm` is set to `True`.
  653. random_replace_prob (`float`, *optional*, defaults to 0.1):
  654. The probability with which masked tokens are replaced by random tokens from the tokenizer's vocabulary.
  655. Defaults to 0.1, meaning 10% of the masked tokens will be replaced with random tokens. The remaining
  656. masked tokens (1 - mask_replace_prob - random_replace_prob) are left unchanged.
  657. Only works when `mlm` is set to `True`.
  658. pad_to_multiple_of (`int`, *optional*):
  659. If set, will pad the sequence to a multiple of the provided value.
  660. return_tensors (`str`):
  661. The type of Tensor to return. Allowable values are "np", "pt" and "tf".
  662. seed (`int`, *optional*):
  663. The seed to use for the random number generator for masking. If not provided, the global RNG will be used.
  664. <Tip>
  665. For best performance, this data collator should be used with a dataset having items that are dictionaries or
  666. BatchEncoding, with the `"special_tokens_mask"` key, as returned by a [`PreTrainedTokenizer`] or a
  667. [`PreTrainedTokenizerFast`] with the argument `return_special_tokens_mask=True`.
  668. <Example Options and Expectations>
  669. 1. Default Behavior:
  670. - `mask_replace_prob=0.8`, `random_replace_prob=0.1`.
  671. - Expect 80% of masked tokens replaced with `[MASK]`, 10% replaced with random tokens, and 10% left unchanged.
  672. 2. All masked tokens replaced by `[MASK]`:
  673. - `mask_replace_prob=1.0`, `random_replace_prob=0.0`.
  674. - Expect all masked tokens to be replaced with `[MASK]`. No tokens are left unchanged or replaced with random tokens.
  675. 3. No `[MASK]` replacement, only random tokens:
  676. - `mask_replace_prob=0.0`, `random_replace_prob=1.0`.
  677. - Expect all masked tokens to be replaced with random tokens. No `[MASK]` replacements or unchanged tokens.
  678. 4. Balanced replacement:
  679. - `mask_replace_prob=0.5`, `random_replace_prob=0.4`.
  680. - Expect 50% of masked tokens replaced with `[MASK]`, 40% replaced with random tokens, and 10% left unchanged.
  681. Note:
  682. The sum of `mask_replace_prob` and `random_replace_prob` must not exceed 1. If their sum is less than 1, the
  683. remaining proportion will consist of masked tokens left unchanged.
  684. </Tip>
  685. """
  686. tokenizer: PreTrainedTokenizerBase
  687. mlm: bool = True
  688. whole_word_mask: bool = False
  689. mlm_probability: Optional[float] = 0.15
  690. mask_replace_prob: float = 0.8
  691. random_replace_prob: float = 0.1
  692. pad_to_multiple_of: Optional[int] = None
  693. tf_experimental_compile: bool = False
  694. return_tensors: str = "pt"
  695. seed: Optional[int] = None
  696. def __post_init__(self):
  697. if self.mlm:
  698. if self.tokenizer.mask_token is None:
  699. raise ValueError(
  700. "This tokenizer does not have a mask token which is necessary for masked language modeling. "
  701. "You should pass `mlm=False` to train on causal language modeling instead."
  702. )
  703. if self.mlm_probability is None or self.mlm_probability < 0 or self.mlm_probability > 1:
  704. raise ValueError("mlm_probability should be between 0 and 1.")
  705. self.mlm_probability = float(self.mlm_probability)
  706. elif self.whole_word_mask:
  707. raise ValueError(
  708. "Whole word masking can only be used with mlm=True."
  709. "If you want to use whole word masking, please set mlm=True."
  710. )
  711. if self.mask_replace_prob + self.random_replace_prob > 1:
  712. raise ValueError("The sum of mask_replace_prob and random_replace_prob should not exceed 1")
  713. if self.mask_replace_prob < 0 or self.mask_replace_prob > 1:
  714. raise ValueError("mask_replace_prob should be between 0 and 1.")
  715. if self.random_replace_prob < 0 or self.random_replace_prob > 1:
  716. raise ValueError("random_replace_prob should be between 0 and 1.")
  717. self.mask_replace_prob = float(self.mask_replace_prob)
  718. self.random_replace_prob = float(self.random_replace_prob)
  719. if self.tf_experimental_compile:
  720. import tensorflow as tf
  721. self.tf_mask_tokens = tf.function(self.tf_mask_tokens, jit_compile=True)
  722. if self.whole_word_mask:
  723. if not self.tokenizer.is_fast:
  724. warnings.warn(
  725. "Whole word masking depends on offset mapping which is only natively available with fast tokenizers.",
  726. UserWarning,
  727. )
  728. if self.mask_replace_prob < 1:
  729. warnings.warn(
  730. "Random token replacement is not supported with whole word masking.",
  731. "Setting mask_replace_prob to 1.",
  732. )
  733. self.mask_replace_prob = 1
  734. self.random_replace_prob = 0
  735. self.generator = None
  736. def get_generator(self, seed):
  737. if self.return_tensors == "pt":
  738. import torch
  739. return torch.Generator().manual_seed(seed)
  740. elif self.return_tensors == "tf":
  741. import tensorflow as tf
  742. return tf.random.Generator.from_seed(seed)
  743. else:
  744. return np.random.default_rng(seed)
  745. def create_rng(self):
  746. if mp.current_process().name == "MainProcess":
  747. # If we are in the main process, we create a generator object with the seed
  748. self.generator = self.get_generator(self.seed)
  749. else:
  750. # If we are in a worker process (i.e using multiprocessing), we need to set a unique seed for each
  751. # worker's generator, generated as the main seed + the worker's ID.
  752. # (https://pytorch.org/docs/stable/data.html#randomness-in-multi-process-data-loading)
  753. # Only PyTorch DataLoader allows us to access the worker ID, and so we check for this.
  754. # For other frameworks, we will throw an error.
  755. import torch
  756. worker_info = torch.utils.data.get_worker_info()
  757. if worker_info is None:
  758. error_string = (
  759. "Worker process information is not available for seeding the generator. This may be because",
  760. "you are using multiprocessing without using a PyTorch DataLoader. The `seed` parameter can",
  761. "only be used when using multiprocessing with a PyTorch DataLoader. Please either use a",
  762. "single process or use a PyTorch DataLoader with multiple workers.",
  763. )
  764. raise ValueError(error_string)
  765. self.generator = self.get_generator(self.seed + worker_info.id)
  766. @staticmethod
  767. def tf_bernoulli(shape, probability, generator=None):
  768. import tensorflow as tf
  769. prob_matrix = tf.fill(shape, probability)
  770. # if generator exists, use it to generate the random numbers
  771. # otherwise, use the global RNG
  772. if generator:
  773. return tf.cast(prob_matrix - generator.uniform(shape, 0, 1) >= 0, tf.bool)
  774. else:
  775. return tf.cast(prob_matrix - tf.random.uniform(shape, 0, 1) >= 0, tf.bool)
  776. def tf_mask_tokens(
  777. self, inputs: Any, vocab_size, mask_token_id, special_tokens_mask: Optional[Any] = None
  778. ) -> tuple[Any, Any]:
  779. """
  780. Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original.
  781. """
  782. import tensorflow as tf
  783. mask_token_id = tf.cast(mask_token_id, inputs.dtype)
  784. input_shape = tf.shape(inputs)
  785. # 1 for a special token, 0 for a normal token in the special tokens mask
  786. # We sample a few tokens in each sequence for MLM training (with probability `self.mlm_probability`)
  787. masked_indices = self.tf_bernoulli(input_shape, self.mlm_probability, self.generator) & ~special_tokens_mask
  788. # Replace unmasked indices with -100 in the labels since we only compute loss on masked tokens
  789. labels = tf.where(masked_indices, inputs, -100)
  790. # mask_replace_prob% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK])
  791. indices_replaced = self.tf_bernoulli(input_shape, self.mask_replace_prob, self.generator) & masked_indices
  792. inputs = tf.where(indices_replaced, mask_token_id, inputs)
  793. if self.mask_replace_prob == 1 or self.random_replace_prob == 0:
  794. return inputs, labels
  795. remaining_prob = 1 - self.mask_replace_prob
  796. # scaling the random_replace_prob to the remaining probability for example if
  797. # mask_replace_prob = 0.8 and random_replace_prob = 0.1,
  798. # then random_replace_prob_scaled = 0.1 / 0.2 = 0.5
  799. random_replace_prob_scaled = self.random_replace_prob / remaining_prob
  800. # random_replace_prob% of the time, we replace masked input tokens with random word
  801. indices_random = (
  802. self.tf_bernoulli(input_shape, random_replace_prob_scaled, self.generator)
  803. & masked_indices
  804. & ~indices_replaced
  805. )
  806. if self.generator:
  807. random_words = self.generator.uniform(input_shape, maxval=vocab_size, dtype=inputs.dtype)
  808. else:
  809. random_words = tf.random.uniform(input_shape, maxval=vocab_size, dtype=inputs.dtype)
  810. inputs = tf.where(indices_random, random_words, inputs)
  811. # The rest of the time ((1-random_replace_prob-mask_replace_prob)% of the time) we keep the masked input tokens unchanged
  812. return inputs, labels
  813. def tf_call(self, examples: list[Union[list[int], Any, dict[str, Any]]]) -> dict[str, Any]:
  814. import tensorflow as tf
  815. if self.seed and self.generator is None:
  816. # If we have a seed, we need to create a generator object. Subsequent calls to this function will use the same generator.
  817. # If no seed supplied, we will use the global RNG
  818. self.create_rng()
  819. # Handle dict or lists with proper padding and conversion to tensor.
  820. if isinstance(examples[0], Mapping):
  821. batch = pad_without_fast_tokenizer_warning(
  822. self.tokenizer, examples, return_tensors="tf", pad_to_multiple_of=self.pad_to_multiple_of
  823. )
  824. else:
  825. batch = {
  826. "input_ids": _tf_collate_batch(examples, self.tokenizer, pad_to_multiple_of=self.pad_to_multiple_of)
  827. }
  828. # If special token mask has been preprocessed, pop it from the dict.
  829. special_tokens_mask = batch.pop("special_tokens_mask", None)
  830. if self.mlm:
  831. if special_tokens_mask is None:
  832. special_tokens_mask = [
  833. self.tokenizer.get_special_tokens_mask(val, already_has_special_tokens=True)
  834. for val in batch["input_ids"].numpy().tolist()
  835. ]
  836. # Cannot directly create as bool
  837. special_tokens_mask = tf.cast(tf.convert_to_tensor(special_tokens_mask, dtype=tf.int64), tf.bool)
  838. else:
  839. special_tokens_mask = tf.cast(special_tokens_mask, tf.bool)
  840. batch["input_ids"], batch["labels"] = self.tf_mask_tokens(
  841. tf.cast(batch["input_ids"], tf.int64),
  842. special_tokens_mask=special_tokens_mask,
  843. mask_token_id=self.tokenizer.mask_token_id,
  844. vocab_size=len(self.tokenizer),
  845. )
  846. else:
  847. labels = batch["input_ids"]
  848. if self.tokenizer.pad_token_id is not None:
  849. # Replace self.tokenizer.pad_token_id with -100
  850. labels = tf.where(labels == self.tokenizer.pad_token_id, -100, labels)
  851. else:
  852. labels = tf.identity(labels) # Makes a copy, just in case
  853. batch["labels"] = labels
  854. return batch
  855. def torch_call(self, examples: list[Union[list[int], Any, dict[str, Any]]]) -> dict[str, Any]:
  856. # Handle dict or lists with proper padding and conversion to tensor.
  857. if self.seed and self.generator is None:
  858. # If we have a seed, we need to create a generator object. Subsequent calls to this function will use the same generator.
  859. # If no seed supplied, we will use the global RNG
  860. self.create_rng()
  861. if isinstance(examples[0], Mapping):
  862. batch = pad_without_fast_tokenizer_warning(
  863. self.tokenizer, examples, return_tensors="pt", pad_to_multiple_of=self.pad_to_multiple_of
  864. )
  865. else:
  866. batch = {
  867. "input_ids": _torch_collate_batch(examples, self.tokenizer, pad_to_multiple_of=self.pad_to_multiple_of)
  868. }
  869. # If special token mask has been preprocessed, pop it from the dict.
  870. special_tokens_mask = batch.pop("special_tokens_mask", None)
  871. offset_mapping = batch.pop("offset_mapping", None)
  872. if self.mlm:
  873. batch["input_ids"], batch["labels"] = self.torch_mask_tokens(
  874. batch["input_ids"], special_tokens_mask=special_tokens_mask, offset_mapping=offset_mapping
  875. )
  876. else:
  877. labels = batch["input_ids"].clone()
  878. if self.tokenizer.pad_token_id is not None:
  879. labels[labels == self.tokenizer.pad_token_id] = -100
  880. batch["labels"] = labels
  881. return batch
  882. def torch_mask_tokens(
  883. self, inputs: Any, special_tokens_mask: Optional[Any] = None, offset_mapping: Optional[Any] = None
  884. ) -> tuple[Any, Any]:
  885. """
  886. Prepare masked tokens inputs/labels for masked language modeling.
  887. """
  888. import torch
  889. labels = inputs.clone()
  890. # We sample a few tokens in each sequence for MLM training (with probability `self.mlm_probability`)
  891. probability_matrix = torch.full(labels.shape, self.mlm_probability)
  892. if special_tokens_mask is None:
  893. special_tokens_mask = [
  894. self.tokenizer.get_special_tokens_mask(val, already_has_special_tokens=True) for val in labels.tolist()
  895. ]
  896. if self.whole_word_mask:
  897. word_ids, no_mask_mask = self._calc_word_ids_and_prob_mask(
  898. to_numpy(offset_mapping), to_numpy(special_tokens_mask)
  899. )
  900. no_mask_mask = torch.tensor(no_mask_mask, dtype=torch.bool)
  901. else:
  902. no_mask_mask = (
  903. special_tokens_mask.bool()
  904. if isinstance(special_tokens_mask, torch.Tensor)
  905. else torch.tensor(special_tokens_mask, dtype=torch.bool)
  906. )
  907. probability_matrix.masked_fill_(no_mask_mask, value=0.0)
  908. masked_indices = torch.bernoulli(probability_matrix, generator=self.generator).bool()
  909. if self.whole_word_mask:
  910. masked_indices = torch.BoolTensor(self._whole_word_mask(word_ids, masked_indices))
  911. labels[~masked_indices] = -100 # We only compute loss on masked tokens
  912. # mask_replace_prob% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK])
  913. indices_replaced = (
  914. torch.bernoulli(torch.full(labels.shape, self.mask_replace_prob), generator=self.generator).bool()
  915. & masked_indices
  916. )
  917. inputs[indices_replaced] = self.tokenizer.convert_tokens_to_ids(self.tokenizer.mask_token)
  918. if self.mask_replace_prob == 1 or self.random_replace_prob == 0:
  919. return inputs, labels
  920. remaining_prob = 1 - self.mask_replace_prob
  921. # scaling the random_replace_prob to the remaining probability for example if
  922. # mask_replace_prob = 0.8 and random_replace_prob = 0.1,
  923. # then random_replace_prob_scaled = 0.1 / 0.2 = 0.5
  924. random_replace_prob_scaled = self.random_replace_prob / remaining_prob
  925. # random_replace_prob% of the time, we replace masked input tokens with random word
  926. indices_random = (
  927. torch.bernoulli(torch.full(labels.shape, random_replace_prob_scaled), generator=self.generator).bool()
  928. & masked_indices
  929. & ~indices_replaced
  930. )
  931. random_words = torch.randint(len(self.tokenizer), labels.shape, dtype=torch.long, generator=self.generator)
  932. inputs[indices_random] = random_words[indices_random]
  933. # The rest of the time ((1-random_replace_prob-mask_replace_prob)% of the time) we keep the masked input tokens unchanged
  934. return inputs, labels
  935. def numpy_call(self, examples: list[Union[list[int], Any, dict[str, Any]]]) -> dict[str, Any]:
  936. # Handle dict or lists with proper padding and conversion to tensor.
  937. if self.seed and self.generator is None:
  938. # If we have a seed, we need to create a generator object. Subsequent calls to this function will use the same generator.
  939. # If no seed supplied, we will use the global RNG
  940. self.create_rng()
  941. if isinstance(examples[0], Mapping):
  942. batch = pad_without_fast_tokenizer_warning(
  943. self.tokenizer, examples, return_tensors="np", pad_to_multiple_of=self.pad_to_multiple_of
  944. )
  945. else:
  946. batch = {
  947. "input_ids": _numpy_collate_batch(examples, self.tokenizer, pad_to_multiple_of=self.pad_to_multiple_of)
  948. }
  949. # If special token mask has been preprocessed, pop it from the dict.
  950. special_tokens_mask = batch.pop("special_tokens_mask", None)
  951. offset_mapping = batch.pop("offset_mapping", None)
  952. if self.mlm:
  953. batch["input_ids"], batch["labels"] = self.numpy_mask_tokens(
  954. batch["input_ids"], special_tokens_mask=special_tokens_mask, offset_mapping=offset_mapping
  955. )
  956. else:
  957. labels = np.copy(batch["input_ids"])
  958. if self.tokenizer.pad_token_id is not None:
  959. labels[labels == self.tokenizer.pad_token_id] = -100
  960. batch["labels"] = labels
  961. return batch
  962. def numpy_mask_tokens(
  963. self,
  964. inputs: Any,
  965. special_tokens_mask: Optional[Any] = None,
  966. offset_mapping: Optional[Any] = None,
  967. ) -> tuple[Any, Any]:
  968. """
  969. Prepare masked tokens inputs/labels for masked language modeling.
  970. """
  971. labels = np.copy(inputs)
  972. # We sample a few tokens in each sequence for MLM training (with probability `self.mlm_probability`)
  973. probability_matrix = np.full(labels.shape, self.mlm_probability)
  974. if special_tokens_mask is None:
  975. special_tokens_mask = [
  976. self.tokenizer.get_special_tokens_mask(val, already_has_special_tokens=True) for val in labels.tolist()
  977. ]
  978. if self.whole_word_mask:
  979. word_ids, no_mask_mask = self._calc_word_ids_and_prob_mask(
  980. to_numpy(offset_mapping), to_numpy(special_tokens_mask)
  981. )
  982. else:
  983. no_mask_mask = (
  984. special_tokens_mask.astype(bool)
  985. if isinstance(special_tokens_mask, np.ndarray)
  986. else np.array(special_tokens_mask, dtype=bool)
  987. )
  988. probability_matrix[no_mask_mask] = 0
  989. # Numpy doesn't have bernoulli, so we use a binomial with 1 trial
  990. if self.generator:
  991. masked_indices = self.generator.binomial(1, probability_matrix, size=probability_matrix.shape).astype(bool)
  992. else:
  993. masked_indices = np.random.binomial(1, probability_matrix, size=probability_matrix.shape).astype(bool)
  994. if self.whole_word_mask:
  995. masked_indices = self._whole_word_mask(word_ids, masked_indices)
  996. labels[~masked_indices] = -100 # We only compute loss on masked tokens
  997. # mask_replace_prob% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK])
  998. if self.generator:
  999. indices_replaced = (
  1000. self.generator.binomial(1, self.mask_replace_prob, size=labels.shape).astype(bool) & masked_indices
  1001. )
  1002. else:
  1003. indices_replaced = (
  1004. np.random.binomial(1, self.mask_replace_prob, size=labels.shape).astype(bool) & masked_indices
  1005. )
  1006. inputs[indices_replaced] = self.tokenizer.mask_token_id
  1007. if self.mask_replace_prob == 1 or self.random_replace_prob == 0:
  1008. return inputs, labels
  1009. remaining_prob = 1 - self.mask_replace_prob
  1010. # scaling the random_replace_prob to the remaining probability for example if
  1011. # mask_replace_prob = 0.8 and random_replace_prob = 0.1,
  1012. # then random_replace_prob_scaled = 0.1 / 0.2 = 0.5
  1013. random_replace_prob_scaled = self.random_replace_prob / remaining_prob
  1014. if self.generator:
  1015. indices_random = (
  1016. self.generator.binomial(1, random_replace_prob_scaled, size=labels.shape).astype(bool)
  1017. & masked_indices
  1018. & ~indices_replaced
  1019. )
  1020. random_words = self.generator.integers(
  1021. low=0, high=len(self.tokenizer), size=np.count_nonzero(indices_random), dtype=np.int64
  1022. )
  1023. else:
  1024. indices_random = (
  1025. np.random.binomial(1, random_replace_prob_scaled, size=labels.shape).astype(bool)
  1026. & masked_indices
  1027. & ~indices_replaced
  1028. )
  1029. random_words = np.random.randint(
  1030. low=0, high=len(self.tokenizer), size=np.count_nonzero(indices_random), dtype=np.int64
  1031. )
  1032. inputs[indices_random] = random_words
  1033. # The rest of the time (10% of the time) we keep the masked input tokens unchanged
  1034. return inputs, labels
  1035. @staticmethod
  1036. def _calc_word_ids_and_prob_mask(
  1037. offsets: np.ndarray[np.ndarray[tuple[int, int]]], special_tokens_mask: np.ndarray[np.ndarray[int]]
  1038. ) -> tuple[np.ndarray[np.ndarray[int]], np.ndarray[np.ndarray[int]]]:
  1039. """
  1040. Map tokens to word ids and create mask of tokens to not mask.
  1041. Tokens that are part of the same word will have the same word id and we will only
  1042. set a mask probability for the first token of each word.
  1043. """
  1044. token_starts = offsets[:, :, 0]
  1045. token_ends = offsets[:, :, 1]
  1046. prev_token_ends = np.roll(token_ends, 1, axis=1)
  1047. prev_token_ends[:, 0] = -1 # First token has no previous token
  1048. prev_token_special = np.roll(special_tokens_mask, 1, axis=1)
  1049. prev_token_special[:, 0] = 0
  1050. # Not special token AND (gap from previous or previous token was special)
  1051. special_tokens_mask = special_tokens_mask.astype(bool)
  1052. is_new_word = (~special_tokens_mask) & ((token_starts != prev_token_ends) | (prev_token_special == 1))
  1053. word_ids = np.cumsum(is_new_word, axis=1)
  1054. word_ids[special_tokens_mask] = -1
  1055. prob_mask = ~is_new_word
  1056. return word_ids, prob_mask
  1057. @staticmethod
  1058. def _whole_word_mask(word_ids: np.ndarray[np.ndarray[int]], mask: Any) -> Any:
  1059. """
  1060. Mask whole words based on word ids and mask.
  1061. """
  1062. mask = to_numpy(mask)
  1063. valid_ids = word_ids != -1
  1064. # Create 3D mask where [batch, token_i, token_j] is True if token_i and token_j are the same word
  1065. same_word = (word_ids[:, :, None] == word_ids[:, None, :]) & valid_ids[:, :, None] & valid_ids[:, None, :]
  1066. # For each token, set True if any token in the same word is masked
  1067. return np.any(same_word & mask[:, None, :], axis=2)
  1068. @dataclass
  1069. class DataCollatorForWholeWordMask(DataCollatorForLanguageModeling):
  1070. """
  1071. Data collator used for language modeling that masks entire words.
  1072. - collates batches of tensors, honoring their tokenizer's pad_token
  1073. - preprocesses batches for masked language modeling
  1074. <Tip>
  1075. This collator relies on details of the implementation of subword tokenization by [`BertTokenizer`], specifically
  1076. that subword tokens are prefixed with *##*. For tokenizers that do not adhere to this scheme, this collator will
  1077. produce an output that is roughly equivalent to [`.DataCollatorForLanguageModeling`].
  1078. </Tip>"""
  1079. def torch_call(self, examples: list[Union[list[int], Any, dict[str, Any]]]) -> dict[str, Any]:
  1080. if self.seed and self.generator is None:
  1081. # If we have a seed, we need to create a generator object. Subsequent calls to this function will use the same generator.
  1082. # If no seed supplied, we will use the global RNG
  1083. self.create_rng()
  1084. if isinstance(examples[0], Mapping):
  1085. input_ids = [e["input_ids"] for e in examples]
  1086. else:
  1087. input_ids = examples
  1088. examples = [{"input_ids": e} for e in examples]
  1089. batch_input = _torch_collate_batch(input_ids, self.tokenizer, pad_to_multiple_of=self.pad_to_multiple_of)
  1090. mask_labels = []
  1091. for e in examples:
  1092. ref_tokens = []
  1093. for id in tolist(e["input_ids"]):
  1094. token = self.tokenizer._convert_id_to_token(id)
  1095. ref_tokens.append(token)
  1096. # For Chinese tokens, we need extra inf to mark sub-word, e.g [喜,欢]-> [喜,##欢]
  1097. if "chinese_ref" in e:
  1098. ref_pos = tolist(e["chinese_ref"])
  1099. len_seq = len(e["input_ids"])
  1100. for i in range(len_seq):
  1101. if i in ref_pos:
  1102. ref_tokens[i] = "##" + ref_tokens[i]
  1103. mask_labels.append(self._whole_word_mask(ref_tokens))
  1104. batch_mask = _torch_collate_batch(mask_labels, self.tokenizer, pad_to_multiple_of=self.pad_to_multiple_of)
  1105. inputs, labels = self.torch_mask_tokens(batch_input, batch_mask)
  1106. return {"input_ids": inputs, "labels": labels}
  1107. def tf_call(self, examples: list[Union[list[int], Any, dict[str, Any]]]) -> dict[str, Any]:
  1108. import tensorflow as tf
  1109. if self.seed and self.generator is None:
  1110. # If we have a seed, we need to create a generator object. Subsequent calls to this function will use the same generator.
  1111. # If no seed supplied, we will use the global RNG
  1112. self.create_rng()
  1113. if isinstance(examples[0], Mapping):
  1114. input_ids = [e["input_ids"] for e in examples]
  1115. else:
  1116. input_ids = examples
  1117. examples = [{"input_ids": e} for e in examples]
  1118. batch_input = _tf_collate_batch(input_ids, self.tokenizer, pad_to_multiple_of=self.pad_to_multiple_of)
  1119. mask_labels = []
  1120. for e in examples:
  1121. ref_tokens = []
  1122. for id in tolist(e["input_ids"]):
  1123. token = self.tokenizer._convert_id_to_token(id)
  1124. ref_tokens.append(token)
  1125. # For Chinese tokens, we need extra inf to mark sub-word, e.g [喜,欢]-> [喜,##欢]
  1126. if "chinese_ref" in e:
  1127. ref_pos = tolist(e["chinese_ref"])
  1128. len_seq = len(e["input_ids"])
  1129. for i in range(len_seq):
  1130. if i in ref_pos:
  1131. ref_tokens[i] = "##" + ref_tokens[i]
  1132. mask_labels.append(self._whole_word_mask(ref_tokens))
  1133. batch_mask = _tf_collate_batch(mask_labels, self.tokenizer, pad_to_multiple_of=self.pad_to_multiple_of)
  1134. inputs, labels = self.tf_mask_tokens(tf.cast(batch_input, tf.int64), batch_mask)
  1135. return {"input_ids": inputs, "labels": labels}
  1136. def numpy_call(self, examples: list[Union[list[int], Any, dict[str, Any]]]) -> dict[str, Any]:
  1137. if self.seed and self.generator is None:
  1138. # If we have a seed, we need to create a generator object. Subsequent calls to this function will use the same generator.
  1139. # If no seed supplied, we will use the global RNG
  1140. self.create_rng()
  1141. if isinstance(examples[0], Mapping):
  1142. input_ids = [e["input_ids"] for e in examples]
  1143. else:
  1144. input_ids = examples
  1145. examples = [{"input_ids": e} for e in examples]
  1146. batch_input = _numpy_collate_batch(input_ids, self.tokenizer, pad_to_multiple_of=self.pad_to_multiple_of)
  1147. mask_labels = []
  1148. for e in examples:
  1149. ref_tokens = []
  1150. for id in tolist(e["input_ids"]):
  1151. token = self.tokenizer._convert_id_to_token(id)
  1152. ref_tokens.append(token)
  1153. # For Chinese tokens, we need extra inf to mark sub-word, e.g [喜,欢]-> [喜,##欢]
  1154. if "chinese_ref" in e:
  1155. ref_pos = tolist(e["chinese_ref"])
  1156. len_seq = len(e["input_ids"])
  1157. for i in range(len_seq):
  1158. if i in ref_pos:
  1159. ref_tokens[i] = "##" + ref_tokens[i]
  1160. mask_labels.append(self._whole_word_mask(ref_tokens))
  1161. batch_mask = _numpy_collate_batch(mask_labels, self.tokenizer, pad_to_multiple_of=self.pad_to_multiple_of)
  1162. inputs, labels = self.numpy_mask_tokens(batch_input, batch_mask)
  1163. return {"input_ids": inputs, "labels": labels}
  1164. def _shuffle(self, cand_indexes):
  1165. # if no seed, just use random's shuffle
  1166. if self.seed is None:
  1167. random.shuffle(cand_indexes)
  1168. return cand_indexes
  1169. # if seed is provided, use the generator to shuffle
  1170. if self.return_tensors == "pt":
  1171. import torch
  1172. indices = torch.randperm(len(cand_indexes), generator=self.generator)
  1173. return [cand_indexes[i] for i in indices]
  1174. elif self.return_tensors == "tf":
  1175. import tensorflow as tf
  1176. seed = self.generator.make_seeds(2)[0]
  1177. indices = tf.random.experimental.stateless_shuffle(tf.range(len(cand_indexes)), seed=seed).numpy().tolist()
  1178. return [cand_indexes[i] for i in indices]
  1179. elif self.return_tensors == "np":
  1180. self.generator.shuffle(cand_indexes)
  1181. return cand_indexes
  1182. def _whole_word_mask(self, input_tokens: list[str], max_predictions=512):
  1183. """
  1184. Get 0/1 labels for masked tokens with whole word mask proxy
  1185. """
  1186. from transformers import BertTokenizer, BertTokenizerFast
  1187. if not isinstance(self.tokenizer, (BertTokenizer, BertTokenizerFast)):
  1188. warnings.warn(
  1189. "DataCollatorForWholeWordMask is only suitable for BertTokenizer-like tokenizers. "
  1190. "Please refer to the documentation for more information."
  1191. )
  1192. cand_indexes = []
  1193. for i, token in enumerate(input_tokens):
  1194. if token == "[CLS]" or token == "[SEP]":
  1195. continue
  1196. if len(cand_indexes) >= 1 and token.startswith("##"):
  1197. cand_indexes[-1].append(i)
  1198. else:
  1199. cand_indexes.append([i])
  1200. cand_indexes = self._shuffle(cand_indexes)
  1201. num_to_predict = min(max_predictions, max(1, int(round(len(input_tokens) * self.mlm_probability))))
  1202. masked_lms = []
  1203. covered_indexes = set()
  1204. for index_set in cand_indexes:
  1205. if len(masked_lms) >= num_to_predict:
  1206. break
  1207. # If adding a whole-word mask would exceed the maximum number of
  1208. # predictions, then just skip this candidate.
  1209. if len(masked_lms) + len(index_set) > num_to_predict:
  1210. continue
  1211. for index in index_set:
  1212. covered_indexes.add(index)
  1213. masked_lms.append(index)
  1214. if len(covered_indexes) != len(masked_lms):
  1215. raise ValueError("Length of covered_indexes is not equal to length of masked_lms.")
  1216. mask_labels = [1 if i in covered_indexes else 0 for i in range(len(input_tokens))]
  1217. return mask_labels
  1218. def torch_mask_tokens(self, inputs: Any, mask_labels: Any) -> tuple[Any, Any]:
  1219. """
  1220. Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original. Set
  1221. 'mask_labels' means we use whole word mask (wwm), we directly mask idxs according to it's ref.
  1222. """
  1223. import torch
  1224. if self.tokenizer.mask_token is None:
  1225. raise ValueError(
  1226. "This tokenizer does not have a mask token which is necessary for masked language modeling. Remove the"
  1227. " --mlm flag if you want to use this tokenizer."
  1228. )
  1229. labels = inputs.clone()
  1230. # We sample a few tokens in each sequence for masked-LM training (with probability args.mlm_probability defaults to 0.15 in Bert/RoBERTa)
  1231. probability_matrix = mask_labels
  1232. special_tokens_mask = [
  1233. self.tokenizer.get_special_tokens_mask(val, already_has_special_tokens=True) for val in labels.tolist()
  1234. ]
  1235. probability_matrix.masked_fill_(torch.tensor(special_tokens_mask, dtype=torch.bool), value=0.0)
  1236. if self.tokenizer.pad_token is not None:
  1237. padding_mask = labels.eq(self.tokenizer.pad_token_id)
  1238. probability_matrix.masked_fill_(padding_mask, value=0.0)
  1239. masked_indices = probability_matrix.bool()
  1240. labels[~masked_indices] = -100 # We only compute loss on masked tokens
  1241. # mask_replace_prob% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK])
  1242. indices_replaced = (
  1243. torch.bernoulli(torch.full(labels.shape, self.mask_replace_prob), generator=self.generator).bool()
  1244. & masked_indices
  1245. )
  1246. inputs[indices_replaced] = self.tokenizer.convert_tokens_to_ids(self.tokenizer.mask_token)
  1247. if self.mask_replace_prob == 1 or self.random_replace_prob == 0:
  1248. return inputs, labels
  1249. remaining_prob = 1 - self.mask_replace_prob
  1250. # scaling the random_replace_prob to the remaining probability for example if
  1251. # mask_replace_prob = 0.8 and random_replace_prob = 0.1,
  1252. # then random_replace_prob_scaled = 0.1 / 0.2 = 0.5
  1253. random_replace_prob_scaled = self.random_replace_prob / remaining_prob
  1254. # random_replacement_prob% of the time, we replace masked input tokens with random word
  1255. indices_random = (
  1256. torch.bernoulli(torch.full(labels.shape, random_replace_prob_scaled), generator=self.generator).bool()
  1257. & masked_indices
  1258. & ~indices_replaced
  1259. )
  1260. random_words = torch.randint(len(self.tokenizer), labels.shape, dtype=torch.long, generator=self.generator)
  1261. inputs[indices_random] = random_words[indices_random]
  1262. # The rest of the time ((1-random_replacement_prob-mask_replace_prob)% of the time) we keep the masked input tokens unchanged
  1263. return inputs, labels
  1264. def tf_mask_tokens(self, inputs: Any, mask_labels: Any) -> tuple[Any, Any]:
  1265. """
  1266. Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original. Set
  1267. 'mask_labels' means we use whole word mask (wwm), we directly mask idxs according to it's ref.
  1268. """
  1269. import tensorflow as tf
  1270. input_shape = tf.shape(inputs)
  1271. if self.tokenizer.mask_token is None:
  1272. raise ValueError(
  1273. "This tokenizer does not have a mask token which is necessary for masked language modeling. Remove the"
  1274. " --mlm flag if you want to use this tokenizer."
  1275. )
  1276. labels = tf.identity(inputs)
  1277. # We sample a few tokens in each sequence for masked-LM training (with probability args.mlm_probability defaults to 0.15 in Bert/RoBERTa)
  1278. masked_indices = tf.cast(mask_labels, tf.bool)
  1279. special_tokens_mask = [
  1280. self.tokenizer.get_special_tokens_mask(val, already_has_special_tokens=True) for val in labels
  1281. ]
  1282. masked_indices = masked_indices & ~tf.cast(special_tokens_mask, dtype=tf.bool)
  1283. if self.tokenizer.pad_token is not None:
  1284. padding_mask = inputs == self.tokenizer.pad_token_id
  1285. masked_indices = masked_indices & ~padding_mask
  1286. # Replace unmasked indices with -100 in the labels since we only compute loss on masked tokens
  1287. labels = tf.where(masked_indices, inputs, -100)
  1288. # mask_replace_prob% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK])
  1289. indices_replaced = self.tf_bernoulli(input_shape, self.mask_replace_prob, self.generator) & masked_indices
  1290. inputs = tf.where(indices_replaced, self.tokenizer.mask_token_id, inputs)
  1291. if self.mask_replace_prob == 1 or self.random_replace_prob == 0:
  1292. return inputs, labels
  1293. remaining_prob = 1 - self.mask_replace_prob
  1294. # scaling the random_replace_prob to the remaining probability for example if
  1295. # mask_replace_prob = 0.8 and random_replace_prob = 0.1,
  1296. # then random_replace_prob_scaled = 0.1 / 0.2 = 0.5
  1297. random_replace_prob_scaled = self.random_replace_prob / remaining_prob
  1298. # random_replace_prob% of the time, we replace masked input tokens with random word
  1299. indices_random = (
  1300. self.tf_bernoulli(input_shape, random_replace_prob_scaled, self.generator)
  1301. & masked_indices
  1302. & ~indices_replaced
  1303. )
  1304. if self.generator:
  1305. random_words = self.generator.uniform(input_shape, maxval=len(self.tokenizer), dtype=tf.int64)
  1306. else:
  1307. random_words = tf.random.uniform(input_shape, maxval=len(self.tokenizer), dtype=tf.int64)
  1308. inputs = tf.where(indices_random, random_words, inputs)
  1309. # The rest of the time ((1-mask_replace_prob-random_replace_prob)% of the time) we keep the masked input tokens unchanged
  1310. return inputs, labels
  1311. def numpy_mask_tokens(self, inputs: Any, mask_labels: Any) -> tuple[Any, Any]:
  1312. """
  1313. Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original. Set
  1314. 'mask_labels' means we use whole word mask (wwm), we directly mask idxs according to it's ref.
  1315. """
  1316. if self.tokenizer.mask_token is None:
  1317. raise ValueError(
  1318. "This tokenizer does not have a mask token which is necessary for masked language modeling. Remove the"
  1319. " --mlm flag if you want to use this tokenizer."
  1320. )
  1321. labels = np.copy(inputs)
  1322. # We sample a few tokens in each sequence for masked-LM training (with probability args.mlm_probability defaults to 0.15 in Bert/RoBERTa)
  1323. masked_indices = mask_labels.astype(bool)
  1324. special_tokens_mask = [
  1325. self.tokenizer.get_special_tokens_mask(val, already_has_special_tokens=True) for val in labels.tolist()
  1326. ]
  1327. masked_indices[np.array(special_tokens_mask, dtype=bool)] = 0
  1328. if self.tokenizer.pad_token is not None:
  1329. padding_mask = labels == self.tokenizer.pad_token_id
  1330. masked_indices[padding_mask] = 0
  1331. labels[~masked_indices] = -100 # We only compute loss on masked tokens
  1332. # mask_replacement_prob% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK])
  1333. if self.generator:
  1334. indices_replaced = (
  1335. self.generator.binomial(1, self.mask_replace_prob, size=labels.shape).astype(bool) & masked_indices
  1336. )
  1337. else:
  1338. indices_replaced = (
  1339. np.random.binomial(1, self.mask_replace_prob, size=labels.shape).astype(bool) & masked_indices
  1340. )
  1341. inputs[indices_replaced] = self.tokenizer.convert_tokens_to_ids(self.tokenizer.mask_token)
  1342. if self.mask_replace_prob == 1 or self.random_replace_prob == 0:
  1343. return inputs, labels
  1344. remaining_prob = 1 - self.mask_replace_prob
  1345. # scaling the random_replace_prob to the remaining probability for example if
  1346. # mask_replace_prob = 0.8 and random_replace_prob = 0.1,
  1347. # then random_replace_prob_scaled = 0.1 / 0.2 = 0.5
  1348. random_replace_prob_scaled = self.random_replace_prob / remaining_prob
  1349. if self.generator:
  1350. indices_random = (
  1351. self.generator.binomial(1, random_replace_prob_scaled, size=labels.shape).astype(bool)
  1352. & masked_indices
  1353. & ~indices_replaced
  1354. )
  1355. random_words = self.generator.integers(low=0, high=len(self.tokenizer), size=labels.shape, dtype=np.int64)
  1356. else:
  1357. indices_random = (
  1358. np.random.binomial(1, random_replace_prob_scaled, size=labels.shape).astype(bool)
  1359. & masked_indices
  1360. & ~indices_replaced
  1361. )
  1362. random_words = np.random.randint(low=0, high=len(self.tokenizer), size=labels.shape, dtype=np.int64)
  1363. inputs[indices_random] = random_words[indices_random]
  1364. # The rest of the time ((1-mask_replace_prob-random_replace_prob)% of the time) we keep the masked input tokens unchanged
  1365. return inputs, labels
  1366. def __init__(self, *args, **kwargs):
  1367. warnings.warn(
  1368. "DataCollatorForWholeWordMask is deprecated and will be removed in a future version, you can now use "
  1369. "DataCollatorForLanguageModeling with whole_word_mask=True instead.",
  1370. FutureWarning,
  1371. )
  1372. super().__init__(*args, **kwargs)
  1373. self.mlm = True # Force masked language modeling
  1374. self.whole_word_mask = True # Force whole word masking
  1375. def tolist(x) -> list[Any]:
  1376. if isinstance(x, list):
  1377. return x
  1378. elif hasattr(x, "numpy"): # Checks for TF tensors without needing the import
  1379. x = x.numpy()
  1380. return x.tolist()
  1381. def to_numpy(x) -> np.ndarray[Any]:
  1382. if isinstance(x, np.ndarray):
  1383. return x
  1384. elif hasattr(x, "detach"):
  1385. return x.detach().cpu().numpy()
  1386. else:
  1387. return np.array(x)
  1388. @dataclass
  1389. class DataCollatorForSOP(DataCollatorForLanguageModeling):
  1390. """
  1391. Data collator used for sentence order prediction task.
  1392. - collates batches of tensors, honoring their tokenizer's pad_token
  1393. - preprocesses batches for both masked language modeling and sentence order prediction
  1394. """
  1395. def __init__(self, *args, **kwargs):
  1396. warnings.warn(
  1397. "DataCollatorForSOP is deprecated and will be removed in a future version, you can now use "
  1398. "DataCollatorForLanguageModeling instead.",
  1399. FutureWarning,
  1400. )
  1401. def __call__(self, examples: list[dict[str, Any]]) -> dict[str, Any]:
  1402. import torch
  1403. from torch.nn.utils.rnn import pad_sequence
  1404. input_ids = [example["input_ids"] for example in examples]
  1405. input_ids = _torch_collate_batch(input_ids, self.tokenizer)
  1406. input_ids, labels, attention_mask = self.mask_tokens(input_ids)
  1407. token_type_ids = [example["token_type_ids"] for example in examples]
  1408. # size of segment_ids varied because randomness, padding zero to the end as the original implementation
  1409. token_type_ids = pad_sequence(token_type_ids, batch_first=True, padding_value=self.tokenizer.pad_token_id)
  1410. sop_label_list = [example["sentence_order_label"] for example in examples]
  1411. sentence_order_label = torch.stack(sop_label_list)
  1412. return {
  1413. "input_ids": input_ids,
  1414. "labels": labels,
  1415. "attention_mask": attention_mask,
  1416. "token_type_ids": token_type_ids,
  1417. "sentence_order_label": sentence_order_label,
  1418. }
  1419. def mask_tokens(self, inputs: Any) -> tuple[Any, Any, Any]:
  1420. """
  1421. Prepare masked tokens inputs/labels/attention_mask for masked language modeling: 80% MASK, 10% random, 10%
  1422. original. N-gram not applied yet.
  1423. """
  1424. import torch
  1425. if self.tokenizer.mask_token is None:
  1426. raise ValueError(
  1427. "This tokenizer does not have a mask token which is necessary for masked language modeling. Remove the"
  1428. " --mlm flag if you want to use this tokenizer."
  1429. )
  1430. labels = inputs.clone()
  1431. # We sample a few tokens in each sequence for masked-LM training (with probability args.mlm_probability defaults to 0.15 in Bert/RoBERTa)
  1432. probability_matrix = torch.full(labels.shape, self.mlm_probability)
  1433. special_tokens_mask = [
  1434. self.tokenizer.get_special_tokens_mask(val, already_has_special_tokens=True) for val in labels.tolist()
  1435. ]
  1436. probability_matrix.masked_fill_(torch.tensor(special_tokens_mask, dtype=torch.bool), value=0.0)
  1437. if self.tokenizer.pad_token is not None:
  1438. padding_mask = labels.eq(self.tokenizer.pad_token_id)
  1439. probability_matrix.masked_fill_(padding_mask, value=0.0)
  1440. masked_indices = torch.bernoulli(probability_matrix).bool()
  1441. # probability be `1` (masked), however in albert model attention mask `0` means masked, revert the value
  1442. attention_mask = (~masked_indices).float()
  1443. if self.tokenizer.pad_token is not None:
  1444. attention_padding_mask = labels.eq(self.tokenizer.pad_token_id)
  1445. attention_mask.masked_fill_(attention_padding_mask, value=1.0)
  1446. labels[~masked_indices] = -100 # We only compute loss on masked tokens, -100 is default for CE compute
  1447. # 80% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK])
  1448. indices_replaced = torch.bernoulli(torch.full(labels.shape, 0.8)).bool() & masked_indices
  1449. inputs[indices_replaced] = self.tokenizer.convert_tokens_to_ids(self.tokenizer.mask_token)
  1450. # 10% of the time, we replace masked input tokens with random word
  1451. indices_random = torch.bernoulli(torch.full(labels.shape, 0.5)).bool() & masked_indices & ~indices_replaced
  1452. random_words = torch.randint(len(self.tokenizer), labels.shape, dtype=torch.long)
  1453. inputs[indices_random] = random_words[indices_random]
  1454. # The rest of the time (10% of the time) we keep the masked input tokens unchanged
  1455. return inputs, labels, attention_mask
  1456. @dataclass
  1457. class DataCollatorForPermutationLanguageModeling(DataCollatorMixin):
  1458. """
  1459. Data collator used for permutation language modeling.
  1460. - collates batches of tensors, honoring their tokenizer's pad_token
  1461. - preprocesses batches for permutation language modeling with procedures specific to XLNet
  1462. """
  1463. tokenizer: PreTrainedTokenizerBase
  1464. plm_probability: float = 1 / 6
  1465. max_span_length: int = 5 # maximum length of a span of masked tokens
  1466. return_tensors: str = "pt"
  1467. def torch_call(self, examples: list[Union[list[int], Any, dict[str, Any]]]) -> dict[str, Any]:
  1468. if isinstance(examples[0], Mapping):
  1469. examples = [e["input_ids"] for e in examples]
  1470. batch = _torch_collate_batch(examples, self.tokenizer)
  1471. inputs, perm_mask, target_mapping, labels = self.torch_mask_tokens(batch)
  1472. return {"input_ids": inputs, "perm_mask": perm_mask, "target_mapping": target_mapping, "labels": labels}
  1473. def tf_call(self, examples: list[Union[list[int], Any, dict[str, Any]]]) -> dict[str, Any]:
  1474. if isinstance(examples[0], Mapping):
  1475. examples = [e["input_ids"] for e in examples]
  1476. batch = _tf_collate_batch(examples, self.tokenizer)
  1477. inputs, perm_mask, target_mapping, labels = self.tf_mask_tokens(batch)
  1478. return {"input_ids": inputs, "perm_mask": perm_mask, "target_mapping": target_mapping, "labels": labels}
  1479. def numpy_call(self, examples: list[Union[list[int], Any, dict[str, Any]]]) -> dict[str, Any]:
  1480. if isinstance(examples[0], Mapping):
  1481. examples = [e["input_ids"] for e in examples]
  1482. batch = _numpy_collate_batch(examples, self.tokenizer)
  1483. inputs, perm_mask, target_mapping, labels = self.numpy_mask_tokens(batch)
  1484. return {"input_ids": inputs, "perm_mask": perm_mask, "target_mapping": target_mapping, "labels": labels}
  1485. def torch_mask_tokens(self, inputs: Any) -> tuple[Any, Any, Any, Any]:
  1486. """
  1487. The masked tokens to be predicted for a particular sequence are determined by the following algorithm:
  1488. 0. Start from the beginning of the sequence by setting `cur_len = 0` (number of tokens processed so far).
  1489. 1. Sample a `span_length` from the interval `[1, max_span_length]` (length of span of tokens to be masked)
  1490. 2. Reserve a context of length `context_length = span_length / plm_probability` to surround span to be
  1491. masked
  1492. 3. Sample a starting point `start_index` from the interval `[cur_len, cur_len + context_length -
  1493. span_length]` and mask tokens `start_index:start_index + span_length`
  1494. 4. Set `cur_len = cur_len + context_length`. If `cur_len < max_len` (i.e. there are tokens remaining in the
  1495. sequence to be processed), repeat from Step 1.
  1496. """
  1497. import torch
  1498. if self.tokenizer.mask_token is None:
  1499. raise ValueError(
  1500. "This tokenizer does not have a mask token which is necessary for permutation language modeling."
  1501. " Please add a mask token if you want to use this tokenizer."
  1502. )
  1503. if inputs.size(1) % 2 != 0:
  1504. raise ValueError(
  1505. "This collator requires that sequence lengths be even to create a leakage-free perm_mask. Please see"
  1506. " relevant comments in source code for details."
  1507. )
  1508. labels = inputs.clone()
  1509. # Creating the mask and target_mapping tensors
  1510. masked_indices = torch.full(labels.shape, 0, dtype=torch.bool)
  1511. target_mapping = torch.zeros((labels.size(0), labels.size(1), labels.size(1)), dtype=torch.float32)
  1512. for i in range(labels.size(0)):
  1513. # Start from the beginning of the sequence by setting `cur_len = 0` (number of tokens processed so far).
  1514. cur_len = 0
  1515. max_len = labels.size(1)
  1516. while cur_len < max_len:
  1517. # Sample a `span_length` from the interval `[1, max_span_length]` (length of span of tokens to be masked)
  1518. span_length = torch.randint(1, self.max_span_length + 1, (1,)).item()
  1519. # Reserve a context of length `context_length = span_length / plm_probability` to surround the span to be masked
  1520. context_length = int(span_length / self.plm_probability)
  1521. # Sample a starting point `start_index` from the interval `[cur_len, cur_len + context_length - span_length]` and mask tokens `start_index:start_index + span_length`
  1522. start_index = cur_len + torch.randint(context_length - span_length + 1, (1,)).item()
  1523. masked_indices[i, start_index : start_index + span_length] = 1
  1524. # Set `cur_len = cur_len + context_length`
  1525. cur_len += context_length
  1526. # Since we're replacing non-masked tokens with -100 in the labels tensor instead of skipping them altogether,
  1527. # the i-th predict corresponds to the i-th token.
  1528. target_mapping[i] = torch.eye(labels.size(1))
  1529. special_tokens_mask = torch.tensor(
  1530. [self.tokenizer.get_special_tokens_mask(val, already_has_special_tokens=True) for val in labels.tolist()],
  1531. dtype=torch.bool,
  1532. )
  1533. masked_indices.masked_fill_(special_tokens_mask, value=0.0)
  1534. if self.tokenizer.pad_token is not None:
  1535. padding_mask = labels.eq(self.tokenizer.pad_token_id)
  1536. masked_indices.masked_fill_(padding_mask, value=0.0)
  1537. # Mask indicating non-functional tokens, where functional tokens are [SEP], [CLS], padding, etc.
  1538. non_func_mask = ~(padding_mask | special_tokens_mask)
  1539. inputs[masked_indices] = self.tokenizer.mask_token_id
  1540. labels[~masked_indices] = -100 # We only compute loss on masked tokens
  1541. perm_mask = torch.zeros((labels.size(0), labels.size(1), labels.size(1)), dtype=torch.float32)
  1542. for i in range(labels.size(0)):
  1543. # Generate permutation indices i.e. sample a random factorisation order for the sequence. This will
  1544. # determine which tokens a given token can attend to (encoded in `perm_mask`).
  1545. # Note: Length of token sequence being permuted has to be less than or equal to reused sequence length
  1546. # (see documentation for `mems`), otherwise information may leak through due to reuse. In this implementation,
  1547. # we assume that reused length is half of sequence length and permutation length is equal to reused length.
  1548. # This requires that the sequence length be even.
  1549. # Create a linear factorisation order
  1550. perm_index = torch.arange(labels.size(1))
  1551. # Split this into two halves, assuming that half the sequence is reused each time
  1552. perm_index = perm_index.reshape((-1, labels.size(1) // 2)).transpose(0, 1)
  1553. # Permute the two halves such that they do not cross over
  1554. perm_index = perm_index[torch.randperm(labels.size(1) // 2)]
  1555. # Flatten this out into the desired permuted factorisation order
  1556. perm_index = torch.flatten(perm_index.transpose(0, 1))
  1557. # Set the permutation indices of non-masked (non-functional) tokens to the
  1558. # smallest index (-1) so that:
  1559. # (1) They can be seen by all other positions
  1560. # (2) They cannot see masked positions, so there won't be information leak
  1561. perm_index.masked_fill_(~masked_indices[i] & non_func_mask[i], -1)
  1562. # The logic for whether the i-th token can attend on the j-th token based on the factorisation order:
  1563. # 0 (can attend): If perm_index[i] > perm_index[j] or j is neither masked nor a functional token
  1564. # 1 (cannot attend): If perm_index[i] <= perm_index[j] and j is either masked or a functional token
  1565. perm_mask[i] = (
  1566. perm_index.reshape((labels.size(1), 1)) <= perm_index.reshape((1, labels.size(1)))
  1567. ) & masked_indices[i]
  1568. return inputs.long(), perm_mask, target_mapping, labels.long()
  1569. def tf_mask_tokens(self, inputs: Any) -> tuple[Any, Any, Any, Any]:
  1570. """
  1571. The masked tokens to be predicted for a particular sequence are determined by the following algorithm:
  1572. 0. Start from the beginning of the sequence by setting `cur_len = 0` (number of tokens processed so far).
  1573. 1. Sample a `span_length` from the interval `[1, max_span_length]` (length of span of tokens to be masked)
  1574. 2. Reserve a context of length `context_length = span_length / plm_probability` to surround span to be
  1575. masked
  1576. 3. Sample a starting point `start_index` from the interval `[cur_len, cur_len + context_length -
  1577. span_length]` and mask tokens `start_index:start_index + span_length`
  1578. 4. Set `cur_len = cur_len + context_length`. If `cur_len < max_len` (i.e. there are tokens remaining in the
  1579. sequence to be processed), repeat from Step 1.
  1580. """
  1581. import tensorflow as tf
  1582. if self.tokenizer.mask_token is None:
  1583. raise ValueError(
  1584. "This tokenizer does not have a mask token which is necessary for permutation language modeling."
  1585. " Please add a mask token if you want to use this tokenizer."
  1586. )
  1587. if tf.shape(inputs)[1] % 2 != 0:
  1588. raise ValueError(
  1589. "This collator requires that sequence lengths be even to create a leakage-free perm_mask. Please see"
  1590. " relevant comments in source code for details."
  1591. )
  1592. labels = tf.identity(inputs)
  1593. # Creating the mask and target_mapping tensors
  1594. masked_indices = np.full(labels.shape.as_list(), 0, dtype=bool)
  1595. labels_shape = tf.shape(labels)
  1596. target_mapping = np.zeros((labels_shape[0], labels_shape[1], labels_shape[1]), dtype=np.float32)
  1597. for i in range(len(labels)):
  1598. # Start from the beginning of the sequence by setting `cur_len = 0` (number of tokens processed so far).
  1599. cur_len = 0
  1600. max_len = tf.shape(labels)[1]
  1601. while cur_len < max_len:
  1602. # Sample a `span_length` from the interval `[1, max_span_length]` (length of span of tokens to be masked)
  1603. span_length = randint(1, self.max_span_length + 1)
  1604. # Reserve a context of length `context_length = span_length / plm_probability` to surround the span to be masked
  1605. context_length = int(span_length / self.plm_probability)
  1606. # Sample a starting point `start_index` from the interval `[cur_len, cur_len + context_length - span_length]` and mask tokens `start_index:start_index + span_length`
  1607. start_index = cur_len + randint(0, context_length - span_length + 1)
  1608. masked_indices[i, start_index : start_index + span_length] = 1
  1609. # Set `cur_len = cur_len + context_length`
  1610. cur_len += context_length
  1611. # Since we're replacing non-masked tokens with -100 in the labels tensor instead of skipping them altogether,
  1612. # the i-th predict corresponds to the i-th token.
  1613. target_mapping[i] = np.eye(labels_shape[1])
  1614. masked_indices = tf.cast(tf.convert_to_tensor(masked_indices), dtype=tf.bool)
  1615. target_mapping = tf.convert_to_tensor(target_mapping)
  1616. special_tokens_mask = tf.convert_to_tensor(
  1617. [
  1618. self.tokenizer.get_special_tokens_mask(val, already_has_special_tokens=True)
  1619. for val in labels.numpy().tolist()
  1620. ],
  1621. )
  1622. special_tokens_mask = tf.cast(special_tokens_mask, dtype=tf.bool)
  1623. masked_indices = masked_indices & ~special_tokens_mask
  1624. if self.tokenizer.pad_token is not None:
  1625. padding_mask = labels == self.tokenizer.pad_token_id
  1626. masked_indices = masked_indices & ~padding_mask
  1627. # Mask indicating non-functional tokens, where functional tokens are [SEP], [CLS], padding, etc.
  1628. non_func_mask = ~(padding_mask | special_tokens_mask)
  1629. inputs = tf.where(masked_indices, self.tokenizer.mask_token_id, inputs)
  1630. labels = tf.where(masked_indices, labels, -100) # We only compute loss on masked tokens
  1631. perm_mask = []
  1632. for i in range(len(labels)):
  1633. # Generate permutation indices i.e. sample a random factorisation order for the sequence. This will
  1634. # determine which tokens a given token can attend to (encoded in `perm_mask`).
  1635. # Note: Length of token sequence being permuted has to be less than or equal to reused sequence length
  1636. # (see documentation for `mems`), otherwise information may leak through due to reuse. In this implementation,
  1637. # we assume that reused length is half of sequence length and permutation length is equal to reused length.
  1638. # This requires that the sequence length be even.
  1639. # Create a linear factorisation order
  1640. # tf.range is the equivalent of torch.arange
  1641. perm_index = tf.range(labels_shape[1])
  1642. # Split this into two halves, assuming that half the sequence is reused each time
  1643. perm_index = tf.transpose(tf.reshape(perm_index, (-1, labels_shape[1] // 2)))
  1644. # Permute the two halves such that they do not cross over
  1645. perm_index = tf.random.shuffle(perm_index) # Shuffles along the first dimension
  1646. # Flatten this out into the desired permuted factorisation order
  1647. perm_index = tf.reshape(tf.transpose(perm_index), (-1,))
  1648. # Set the permutation indices of non-masked (non-functional) tokens to the
  1649. # smallest index (-1) so that:
  1650. # (1) They can be seen by all other positions
  1651. # (2) They cannot see masked positions, so there won't be information leak
  1652. perm_index = tf.where(~masked_indices[i] & non_func_mask[i], -1, perm_index)
  1653. # The logic for whether the i-th token can attend on the j-th token based on the factorisation order:
  1654. # 0 (can attend): If perm_index[i] > perm_index[j] or j is neither masked nor a functional token
  1655. # 1 (cannot attend): If perm_index[i] <= perm_index[j] and j is either masked or a functional token
  1656. perm_mask.append(
  1657. (tf.reshape(perm_index, (labels_shape[1], 1)) <= tf.reshape(perm_index, (1, labels_shape[1])))
  1658. & masked_indices[i]
  1659. )
  1660. perm_mask = tf.stack(perm_mask, axis=0)
  1661. return tf.cast(inputs, tf.int64), tf.cast(perm_mask, tf.float32), target_mapping, tf.cast(labels, tf.int64)
  1662. def numpy_mask_tokens(self, inputs: Any) -> tuple[Any, Any, Any, Any]:
  1663. """
  1664. The masked tokens to be predicted for a particular sequence are determined by the following algorithm:
  1665. 0. Start from the beginning of the sequence by setting `cur_len = 0` (number of tokens processed so far).
  1666. 1. Sample a `span_length` from the interval `[1, max_span_length]` (length of span of tokens to be masked)
  1667. 2. Reserve a context of length `context_length = span_length / plm_probability` to surround span to be
  1668. masked
  1669. 3. Sample a starting point `start_index` from the interval `[cur_len, cur_len + context_length -
  1670. span_length]` and mask tokens `start_index:start_index + span_length`
  1671. 4. Set `cur_len = cur_len + context_length`. If `cur_len < max_len` (i.e. there are tokens remaining in the
  1672. sequence to be processed), repeat from Step 1.
  1673. """
  1674. if self.tokenizer.mask_token is None:
  1675. raise ValueError(
  1676. "This tokenizer does not have a mask token which is necessary for permutation language modeling."
  1677. " Please add a mask token if you want to use this tokenizer."
  1678. )
  1679. if inputs.shape[1] % 2 != 0:
  1680. raise ValueError(
  1681. "This collator requires that sequence lengths be even to create a leakage-free perm_mask. Please see"
  1682. " relevant comments in source code for details."
  1683. )
  1684. labels = np.copy(inputs)
  1685. # Creating the mask and target_mapping tensors
  1686. masked_indices = np.full(labels.shape, 0, dtype=bool)
  1687. target_mapping = np.zeros((labels.shape[0], labels.shape[1], labels.shape[1]), dtype=np.float32)
  1688. for i in range(labels.shape[0]):
  1689. # Start from the beginning of the sequence by setting `cur_len = 0` (number of tokens processed so far).
  1690. cur_len = 0
  1691. max_len = labels.shape[1]
  1692. while cur_len < max_len:
  1693. # Sample a `span_length` from the interval `[1, max_span_length]` (length of span of tokens to be masked)
  1694. span_length = randint(1, self.max_span_length + 1)
  1695. # Reserve a context of length `context_length = span_length / plm_probability` to surround the span to be masked
  1696. context_length = int(span_length / self.plm_probability)
  1697. # Sample a starting point `start_index` from the interval `[cur_len, cur_len + context_length - span_length]` and mask tokens `start_index:start_index + span_length`
  1698. start_index = cur_len + randint(0, context_length - span_length + 1)
  1699. masked_indices[i, start_index : start_index + span_length] = 1
  1700. # Set `cur_len = cur_len + context_length`
  1701. cur_len += context_length
  1702. # Since we're replacing non-masked tokens with -100 in the labels tensor instead of skipping them altogether,
  1703. # the i-th predict corresponds to the i-th token.
  1704. target_mapping[i] = np.eye(labels.shape[1])
  1705. special_tokens_mask = np.array(
  1706. [self.tokenizer.get_special_tokens_mask(val, already_has_special_tokens=True) for val in labels.tolist()],
  1707. dtype=bool,
  1708. )
  1709. masked_indices[special_tokens_mask] = 0
  1710. if self.tokenizer.pad_token is not None:
  1711. padding_mask = labels == self.tokenizer.pad_token_id
  1712. masked_indices[padding_mask] = 0.0
  1713. # Mask indicating non-functional tokens, where functional tokens are [SEP], [CLS], padding, etc.
  1714. non_func_mask = ~(padding_mask | special_tokens_mask)
  1715. inputs[masked_indices] = self.tokenizer.mask_token_id
  1716. labels[~masked_indices] = -100 # We only compute loss on masked tokens
  1717. perm_mask = np.zeros((labels.shape[0], labels.shape[1], labels.shape[1]), dtype=np.float32)
  1718. for i in range(labels.shape[0]):
  1719. # Generate permutation indices i.e. sample a random factorisation order for the sequence. This will
  1720. # determine which tokens a given token can attend to (encoded in `perm_mask`).
  1721. # Note: Length of token sequence being permuted has to be less than or equal to reused sequence length
  1722. # (see documentation for `mems`), otherwise information may leak through due to reuse. In this implementation,
  1723. # we assume that reused length is half of sequence length and permutation length is equal to reused length.
  1724. # This requires that the sequence length be even.
  1725. # Create a linear factorisation order
  1726. perm_index = np.arange(labels.shape[1])
  1727. # Split this into two halves, assuming that half the sequence is reused each time
  1728. perm_index = perm_index.reshape((-1, labels.shape[1] // 2)).T
  1729. # Permute the two halves such that they do not cross over
  1730. np.random.shuffle(perm_index)
  1731. # Flatten this out into the desired permuted factorisation order
  1732. perm_index = perm_index.T.flatten()
  1733. # Set the permutation indices of non-masked (non-functional) tokens to the
  1734. # smallest index (-1) so that:
  1735. # (1) They can be seen by all other positions
  1736. # (2) They cannot see masked positions, so there won't be information leak
  1737. perm_index[~masked_indices[i] & non_func_mask[i]] = -1
  1738. # The logic for whether the i-th token can attend on the j-th token based on the factorisation order:
  1739. # 0 (can attend): If perm_index[i] > perm_index[j] or j is neither masked nor a functional token
  1740. # 1 (cannot attend): If perm_index[i] <= perm_index[j] and j is either masked or a functional token
  1741. perm_mask[i] = (
  1742. perm_index.reshape((labels.shape[1], 1)) <= perm_index.reshape((1, labels.shape[1]))
  1743. ) & masked_indices[i]
  1744. return inputs.astype(np.int64), perm_mask, target_mapping, labels.astype(np.int64)
  1745. @dataclass
  1746. class DataCollatorWithFlattening(DefaultDataCollator):
  1747. """
  1748. Data collator used for padding free approach. Does the following:
  1749. - concatenates the entire mini batch into single long sequence of shape [1, total_tokens]
  1750. - uses `separator_id` to separate sequences within the concatenated `labels`, default value is -100
  1751. - no padding will be added, returns `input_ids`, `labels` and `position_ids` by default
  1752. - optionally returns the kwargs contained in FlashAttentionKwargs
  1753. - optionally returns seq_idx indicating which sequence each token belongs to
  1754. <Tip warning={true}>
  1755. Using `DataCollatorWithFlattening` will flatten the entire mini batch into single long sequence.
  1756. Make sure your attention computation is able to handle it!
  1757. </Tip>
  1758. """
  1759. def __init__(
  1760. self,
  1761. *args,
  1762. return_position_ids=True,
  1763. separator_id=-100,
  1764. return_flash_attn_kwargs=False,
  1765. return_seq_idx=False,
  1766. **kwargs,
  1767. ):
  1768. super().__init__(*args, **kwargs)
  1769. self.return_position_ids = return_position_ids
  1770. self.separator_id = separator_id
  1771. self.return_flash_attn_kwargs = return_flash_attn_kwargs
  1772. self.return_seq_idx = return_seq_idx
  1773. self._int_64_keys = {"labels", "position_ids", "input_ids"}
  1774. self._batch_dim_keys = {"labels", "position_ids", "input_ids", "seq_idx"}
  1775. self._py_int_keys = {"max_length_q", "max_length_k"}
  1776. def __call__(self, features, return_tensors=None, separator_id=None):
  1777. if return_tensors is None:
  1778. return_tensors = self.return_tensors
  1779. if separator_id is None:
  1780. separator_id = self.separator_id
  1781. is_labels_provided = "labels" in features[0]
  1782. batch = {"input_ids": [], "labels": []}
  1783. if self.return_position_ids:
  1784. batch.update({"position_ids": []})
  1785. if self.return_seq_idx:
  1786. batch.update({"seq_idx": []})
  1787. if self.return_flash_attn_kwargs:
  1788. cu_seq_lens = [0]
  1789. max_length = 0
  1790. for seq_idx, sample in enumerate(features):
  1791. input_ids = sample["input_ids"]
  1792. batch["input_ids"] += input_ids
  1793. if is_labels_provided:
  1794. batch["labels"] += [separator_id] + sample["labels"][1:]
  1795. else:
  1796. batch["labels"] += [separator_id] + input_ids[1:]
  1797. if self.return_position_ids:
  1798. batch["position_ids"] += list(range(len(input_ids)))
  1799. if self.return_seq_idx:
  1800. batch["seq_idx"] += [seq_idx for _ in range(len(input_ids))]
  1801. if self.return_flash_attn_kwargs:
  1802. cu_seq_lens.append(cu_seq_lens[-1] + len(input_ids))
  1803. max_length = max(max_length, len(input_ids))
  1804. if self.return_flash_attn_kwargs:
  1805. batch["cu_seq_lens_q"] = batch["cu_seq_lens_k"] = cu_seq_lens
  1806. batch["max_length_q"] = batch["max_length_k"] = max_length
  1807. # FlashAttentionKwargs and seq_idx are expected to be int32s.
  1808. if return_tensors == "pt":
  1809. import torch
  1810. data_cls = torch.tensor
  1811. dtype_64 = torch.int64
  1812. dtype_32 = torch.int32
  1813. elif return_tensors == "np":
  1814. data_cls = np.array
  1815. dtype_64 = np.int64
  1816. dtype_32 = np.int32
  1817. else:
  1818. raise ValueError(f'return_tensors must be one of ("pt", "np"), {return_tensors=} not supported')
  1819. for k, v in batch.items():
  1820. if k in self._batch_dim_keys:
  1821. v = [v]
  1822. # Flash attention max_len_{q,k} are python ints
  1823. if k not in self._py_int_keys:
  1824. batch[k] = data_cls(v, dtype=dtype_64 if k in self._int_64_keys else dtype_32)
  1825. return batch