infolm.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. # Copyright The Lightning team.
  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 os
  15. from collections.abc import Sequence
  16. from enum import unique
  17. from typing import TYPE_CHECKING, List, Optional, Union
  18. import torch
  19. from torch import Tensor
  20. from torch.nn import functional as F # noqa: N812
  21. from torch.utils.data import DataLoader
  22. from typing_extensions import Literal
  23. from torchmetrics.functional.text.helper_embedding_metric import (
  24. TokenizedDataset,
  25. _get_progress_bar,
  26. _input_data_collator,
  27. _load_tokenizer_and_model,
  28. )
  29. from torchmetrics.utilities.enums import EnumStr
  30. from torchmetrics.utilities.imports import _TRANSFORMERS_GREATER_EQUAL_4_4
  31. if TYPE_CHECKING and _TRANSFORMERS_GREATER_EQUAL_4_4:
  32. from transformers import PreTrainedModel, PreTrainedTokenizerBase
  33. if not _TRANSFORMERS_GREATER_EQUAL_4_4:
  34. __doctest_skip__ = ["infolm"]
  35. _ALLOWED_INFORMATION_MEASURE_LITERAL = Literal[
  36. "kl_divergence",
  37. "alpha_divergence",
  38. "beta_divergence",
  39. "ab_divergence",
  40. "renyi_divergence",
  41. "l1_distance",
  42. "l2_distance",
  43. "l_infinity_distance",
  44. "fisher_rao_distance",
  45. ]
  46. @unique
  47. class _IMEnum(EnumStr):
  48. """A helper Enum class for storing the information measure."""
  49. @staticmethod
  50. def _name() -> str:
  51. return "Information measure"
  52. KL_DIVERGENCE = "kl_divergence"
  53. ALPHA_DIVERGENCE = "alpha_divergence"
  54. BETA_DIVERGENCE = "beta_divergence"
  55. AB_DIVERGENCE = "ab_divergence"
  56. RENYI_DIVERGENCE = "renyi_divergence"
  57. L1_DISTANCE = "l1_distance"
  58. L2_DISTANCE = "l2_distance"
  59. L_INFINITY_DISTANCE = "l_infinity_distance"
  60. FISHER_RAO_DISTANCE = "fisher_rao_distance"
  61. class _InformationMeasure:
  62. """A wrapper class used for the calculation of different information measures.
  63. This metric can be used to measure the information between the discrete reference distributions of predicted and
  64. reference sentences. The class also handles input validation for `alpha` and `beta` parameters.
  65. Args:
  66. information_measure:
  67. A name of information measure to be used. Please use one of: ['kl_divergence', 'alpha_divergence',
  68. 'beta_divergence', 'ab_divergence', 'renyi_divergence', 'l1_distance', 'l2_distance', 'l_infinity_distance',
  69. 'fisher_rao_distance']
  70. alpha:
  71. Alpha parameter of the divergence used for alpha, AB and Rényi divergence measures.
  72. beta:
  73. Beta parameter of the divergence used for beta and AB divergence measures.
  74. Raises:
  75. ValueError:
  76. If information measure is one from alpha, AB or Rényi divergence and parameter `alpha` is `None`.
  77. ValueError:
  78. If information measure is one from beta or divergence and parameter `beta` is `None`.
  79. ValueError:
  80. If information measure is alpha divergence and parameter `alpha` equals 0 or 1.
  81. ValueError:
  82. If information measure is beta divergence and parameter `beta` equals 0 or -1.
  83. ValueError:
  84. If information measure is AB divergence and parameter `alpha`, `beta` or `alpha + beta` equal 0.
  85. ValueError:
  86. If information measure is Rényi divergence and parameter `alpha` equals 1.
  87. """
  88. def __init__(
  89. self,
  90. information_measure: _ALLOWED_INFORMATION_MEASURE_LITERAL,
  91. alpha: Optional[float] = None,
  92. beta: Optional[float] = None,
  93. ) -> None:
  94. self.information_measure = _IMEnum.from_str(information_measure)
  95. _bad_measures = (_IMEnum.ALPHA_DIVERGENCE, _IMEnum.AB_DIVERGENCE, _IMEnum.RENYI_DIVERGENCE)
  96. if self.information_measure in _bad_measures and not isinstance(alpha, float):
  97. raise ValueError(f"Parameter `alpha` is expected to be defined for {information_measure}.")
  98. if self.information_measure in [_IMEnum.BETA_DIVERGENCE, _IMEnum.AB_DIVERGENCE] and not isinstance(beta, float):
  99. raise ValueError(f"Parameter `beta` is expected to be defined for {information_measure}.")
  100. if self.information_measure == _IMEnum.ALPHA_DIVERGENCE and (not isinstance(alpha, float) or alpha in [0, 1]):
  101. raise ValueError(
  102. f"Parameter `alpha` is expected to be float differened from 0 and 1 for {information_measure}."
  103. )
  104. if self.information_measure == _IMEnum.BETA_DIVERGENCE and (not isinstance(beta, float) or beta in [0, -1]):
  105. raise ValueError(
  106. f"Parameter `beta` is expected to be float differened from 0 and -1 for {information_measure}."
  107. )
  108. if self.information_measure == _IMEnum.AB_DIVERGENCE and (
  109. alpha is None
  110. or beta is None
  111. or (any(not isinstance(p, float) for p in [alpha, beta]) or 0 in [alpha, beta, alpha + beta])
  112. ):
  113. raise ValueError(
  114. "Parameters `alpha`, `beta` and their sum are expected to be differened from 0 for "
  115. f"{information_measure}."
  116. )
  117. if self.information_measure == _IMEnum.RENYI_DIVERGENCE and (not isinstance(alpha, float) or alpha == 1):
  118. raise ValueError(f"Parameter `alpha` is expected to be float differened from 1 for {information_measure}.")
  119. # We ensure self.alpha and self.beta to be different from None to ensure mypy compliance
  120. self.alpha = alpha or 0
  121. self.beta = beta or 0
  122. def __call__(self, preds_distribution: Tensor, target_distribution: Tensor) -> Tensor:
  123. information_measure_function = getattr(self, f"_calculate_{self.information_measure.value}")
  124. return torch.nan_to_num(information_measure_function(preds_distribution, target_distribution))
  125. @staticmethod
  126. def _calculate_kl_divergence(preds_distribution: Tensor, target_distribution: Tensor) -> Tensor:
  127. """Calculate Kullback-Leibler divergence between discrete distributions of predicted and reference sentences.
  128. Args:
  129. preds_distribution:
  130. Discrete reference distribution of predicted sentences over the vocabulary.
  131. target_distribution:
  132. Discrete reference distribution of reference sentences over the vocabulary.
  133. Return:
  134. Kullback-Leibler divergence between discrete distributions of predicted and reference sentences.
  135. """
  136. return torch.sum(target_distribution * torch.log(preds_distribution / target_distribution), dim=-1)
  137. def _calculate_alpha_divergence(self, preds_distribution: Tensor, target_distribution: Tensor) -> Tensor:
  138. """Calculate alpha divergence between discrete distributions of predicted and reference sentences.
  139. Args:
  140. preds_distribution:
  141. Discrete reference distribution of predicted sentences over the vocabulary.
  142. target_distribution:
  143. Discrete reference distribution of reference sentences over the vocabulary.
  144. Return:
  145. Alpha divergence between discrete distributions of predicted and reference sentences.
  146. """
  147. _alpha_denom = self.alpha * (self.alpha - 1)
  148. return (
  149. 1 - torch.sum(target_distribution**self.alpha * preds_distribution ** (1 - self.alpha), dim=-1)
  150. ) / _alpha_denom
  151. def _calculate_ab_divergence(self, preds_distribution: Tensor, target_distribution: Tensor) -> Tensor:
  152. """Calculate AB divergence between discrete distributions of predicted and reference sentences.
  153. Args:
  154. preds_distribution:
  155. Discrete reference distribution of predicted sentences over the vocabulary.
  156. target_distribution:
  157. Discrete reference distribution of reference sentences over the vocabulary.
  158. Return:
  159. AB divergence between discrete distributions of predicted and reference sentences.
  160. """
  161. a = torch.log(torch.sum(target_distribution ** (self.beta + self.alpha), dim=-1))
  162. a /= self.beta * (self.beta + self.alpha)
  163. b = torch.log(torch.sum(preds_distribution ** (self.beta + self.alpha), dim=-1))
  164. b /= self.alpha * (self.beta + self.alpha)
  165. c = torch.log(torch.sum(target_distribution**self.alpha * preds_distribution**self.beta, dim=-1))
  166. c /= self.alpha * self.beta
  167. return a + b - c
  168. def _calculate_beta_divergence(self, preds_distribution: Tensor, target_distribution: Tensor) -> Tensor:
  169. """Calculate beta divergence between discrete distributions of predicted and reference sentences.
  170. Args:
  171. preds_distribution:
  172. Discrete reference distribution of predicted sentences over the vocabulary.
  173. target_distribution:
  174. Discrete reference distribution of reference sentences over the vocabulary.
  175. Return:
  176. Beta divergence between discrete distributions of predicted and reference sentences.
  177. """
  178. self.alpha = 1.0
  179. return self._calculate_ab_divergence(preds_distribution, target_distribution)
  180. def _calculate_renyi_divergence(self, preds_distribution: Tensor, target_distribution: Tensor) -> Tensor:
  181. """Calculate Rényi divergence between discrete distributions of predicted and reference sentences.
  182. Args:
  183. preds_distribution:
  184. Discrete reference distribution of predicted sentences over the vocabulary.
  185. target_distribution:
  186. Discrete reference distribution of reference sentences over the vocabulary.
  187. Return:
  188. Rényi divergence between discrete distributions of predicted and reference sentences.
  189. """
  190. return (
  191. torch.log(torch.sum(target_distribution**self.alpha * preds_distribution ** (1 - self.alpha), dim=-1))
  192. ) / (self.alpha - 1)
  193. @staticmethod
  194. def _calculate_l1_distance(preds_distribution: Tensor, target_distribution: Tensor) -> Tensor:
  195. """Calculate L1 distance between discrete distributions of predicted and reference sentences.
  196. Args:
  197. preds_distribution:
  198. Discrete reference distribution of predicted sentences over the vocabulary.
  199. target_distribution:
  200. Discrete reference distribution of reference sentences over the vocabulary.
  201. Return:
  202. L1 distance between discrete distributions of predicted and reference sentences.
  203. """
  204. return torch.norm(target_distribution - preds_distribution, p=1, dim=-1)
  205. @staticmethod
  206. def _calculate_l2_distance(preds_distribution: Tensor, target_distribution: Tensor) -> Tensor:
  207. """Calculate L2 distance between discrete distributions of predicted and reference sentences.
  208. Args:
  209. preds_distribution:
  210. Discrete reference distribution of predicted sentences over the vocabulary.
  211. target_distribution:
  212. Discrete reference distribution of reference sentences over the vocabulary.
  213. Return:
  214. L2 distance between discrete distributions of predicted and reference sentences.
  215. """
  216. return torch.norm(target_distribution - preds_distribution, p=2, dim=-1)
  217. @staticmethod
  218. def _calculate_l_infinity_distance(preds_distribution: Tensor, target_distribution: Tensor) -> Tensor:
  219. """Calculate L-infinity distance between discrete distributions of predicted and reference sentences.
  220. Args:
  221. preds_distribution:
  222. Discrete reference distribution of predicted sentences over the vocabulary.
  223. target_distribution:
  224. Discrete reference distribution of reference sentences over the vocabulary.
  225. Return:
  226. L-infinity distance between discrete distributions of predicted and reference sentences.
  227. """
  228. return torch.norm(target_distribution - preds_distribution, p=float("inf"), dim=-1)
  229. @staticmethod
  230. def _calculate_fisher_rao_distance(preds_distribution: Tensor, target_distribution: Tensor) -> Tensor:
  231. """Calculate Fisher-Rao distance between discrete distributions of predicted and reference sentences.
  232. Args:
  233. preds_distribution:
  234. Discrete reference distribution of predicted sentences over the vocabulary.
  235. target_distribution:
  236. Discrete reference distribution of reference sentences over the vocabulary.
  237. Return:
  238. Fisher-Rao distance between discrete distributions of predicted and reference sentences.
  239. """
  240. return 2 * torch.acos(torch.clamp(torch.sqrt(preds_distribution * target_distribution).sum(-1), 0, 1))
  241. def _get_dataloader(
  242. input_ids: Tensor, attention_mask: Tensor, idf: bool, batch_size: int, num_workers: int
  243. ) -> DataLoader:
  244. """Prepare dataloader.
  245. Args:
  246. input_ids:
  247. Indices of input sequence tokens in the vocabulary.
  248. attention_mask:
  249. Mask to avoid performing attention on padding token indices.
  250. idf:
  251. A bool indicating whether normalization using inverse document frequencies should be used.
  252. batch_size:
  253. A batch size used for model processing.
  254. num_workers:
  255. A number of workers to use for a dataloader.
  256. Return:
  257. An instance of ``torch.utils.data.DataLoader`` used for iterating over examples.
  258. """
  259. dataset = TokenizedDataset(input_ids, attention_mask, idf)
  260. return DataLoader(dataset, batch_size=batch_size, num_workers=num_workers)
  261. def _get_special_tokens_map(tokenizer: "PreTrainedTokenizerBase") -> dict[str, int]:
  262. """Build a dictionary of model/tokenizer special tokens.
  263. Args:
  264. tokenizer:
  265. Initialized tokenizer from HuggingFace's `transformers package.
  266. Return:
  267. A dictionary containing: mask_token_id, pad_token_id, sep_token_id and cls_token_id.
  268. """
  269. return {
  270. "mask_token_id": tokenizer.mask_token_id,
  271. "pad_token_id": tokenizer.pad_token_id,
  272. "sep_token_id": tokenizer.sep_token_id,
  273. "cls_token_id": tokenizer.cls_token_id,
  274. }
  275. def _get_token_mask(input_ids: Tensor, pad_token_id: int, sep_token_id: int, cls_token_id: int) -> Tensor:
  276. """Generate a token mask for differentiating all special tokens in the input batch.
  277. There are 0s for special tokens and 1s otherwise.
  278. Args:
  279. input_ids:
  280. Indices of input sequence tokens in the vocabulary.
  281. pad_token_id:
  282. An id of ``<PAD>`` tokens that are used to make arrays of tokens the same size for batching purpose
  283. cls_token_id:
  284. An id of ``<CLS>`` token that represents the class of the input. (It might be ``<BOS>`` token for some
  285. models.)
  286. sep_token_id:
  287. An id of ``<SEP>`` token that separates two different sentences in the same input. (It might be ``<EOS>``
  288. token for some models.)
  289. Return:
  290. Tensor mask of 0s and 1s that masks all special tokens in the ``input_ids`` tensor.
  291. """
  292. token_mask = input_ids.eq(pad_token_id) | input_ids.eq(sep_token_id) | input_ids.eq(cls_token_id)
  293. return ~token_mask
  294. def _get_batch_distribution(
  295. model: "PreTrainedModel",
  296. batch: dict[str, Tensor],
  297. temperature: float,
  298. idf: bool,
  299. special_tokens_map: dict[str, int],
  300. ) -> Tensor:
  301. """Calculate a discrete probability distribution for a batch of examples. See `InfoLM`_ for details.
  302. Args:
  303. model:
  304. Initialized model from HuggingFace's `transformers package.
  305. batch:
  306. An input batch dictionary containing ``input_ids`` and ``attention_mask``.
  307. temperature:
  308. A temperature for calibrating language modelling. For more information, please reference `InfoLM`_ paper.
  309. max_length:
  310. A maximum length of input sequences. Sequences longer than `max_length` are to be trimmed.
  311. idf:
  312. An indication of whether normalization using inverse document frequencies should be used.
  313. special_tokens_map:
  314. A dictionary mapping tokenizer special tokens into the corresponding integer values.
  315. Return:
  316. A discrete probability distribution.
  317. """
  318. seq_len = batch["input_ids"].shape[1]
  319. prob_distribution_batch_list: List[Tensor] = []
  320. token_mask = _get_token_mask(
  321. batch["input_ids"],
  322. special_tokens_map["pad_token_id"],
  323. special_tokens_map["sep_token_id"],
  324. special_tokens_map["cls_token_id"],
  325. )
  326. for mask_idx in range(seq_len):
  327. input_ids = batch["input_ids"].clone()
  328. input_ids[:, mask_idx] = special_tokens_map["mask_token_id"]
  329. logits_distribution = model(input_ids, batch["attention_mask"]).logits
  330. # [batch_size, seq_len, vocab_size] -> [batch_size, vocab_size]
  331. logits_distribution = logits_distribution[:, mask_idx, :]
  332. prob_distribution = F.softmax(logits_distribution / temperature, dim=-1)
  333. if idf:
  334. prob_distribution *= batch["input_ids_idf"][:, mask_idx].unsqueeze(1).to(prob_distribution.device)
  335. prob_distribution_batch_list.append(prob_distribution.unsqueeze(1).cpu()) # [batch_size, 1, vocab_size]
  336. # Clean from memory
  337. del input_ids, logits_distribution, prob_distribution
  338. prob_distribution_batch = torch.cat(prob_distribution_batch_list, dim=1) # [batch_size, seq_len, vocab_size]
  339. prob_distribution_batch = torch.einsum("bsv, bs -> bsv", prob_distribution_batch.to(token_mask.device), token_mask)
  340. if idf:
  341. masked_input_ids_idf = token_mask * batch["input_ids_idf"].to(token_mask.device)
  342. return prob_distribution_batch.sum(dim=1) / masked_input_ids_idf.sum(dim=1).unsqueeze(1)
  343. return prob_distribution_batch.sum(dim=1) / token_mask.sum(dim=1).unsqueeze(1)
  344. @torch.no_grad()
  345. def _get_data_distribution(
  346. model: "PreTrainedModel",
  347. dataloader: DataLoader,
  348. temperature: float,
  349. idf: bool,
  350. special_tokens_map: dict[str, int],
  351. verbose: bool,
  352. ) -> Tensor:
  353. """Calculate a discrete probability distribution according to the methodology described in `InfoLM`_.
  354. Args:
  355. model:
  356. Initialized model from HuggingFace's `transformers package.
  357. dataloader:
  358. An instance of `torch.utils.data.DataLoader` used for iterating over examples.
  359. temperature:
  360. A temperature for calibrating language modelling. For more information, please reference `InfoLM`_ paper.
  361. max_length:
  362. A maximum length of input sequences. Sequences longer than `max_length` are to be trimmed.
  363. idf:
  364. An indication of whether normalization using inverse document frequencies should be used.
  365. special_tokens_map:
  366. A dictionary mapping tokenizer special tokens into the corresponding integer values.
  367. verbose:
  368. An indication of whether a progress bar to be displayed during the embeddings calculation.
  369. Return:
  370. A discrete probability distribution.
  371. """
  372. device = model.device
  373. prob_distribution: List[Tensor] = []
  374. for batch in _get_progress_bar(dataloader, verbose):
  375. batch = _input_data_collator(batch, device)
  376. prob_distribution.append(_get_batch_distribution(model, batch, temperature, idf, special_tokens_map))
  377. return torch.cat(prob_distribution, dim=0)
  378. def _infolm_update(
  379. preds: Union[str, Sequence[str]],
  380. target: Union[str, Sequence[str]],
  381. tokenizer: "PreTrainedTokenizerBase",
  382. max_length: int,
  383. ) -> tuple[Tensor, Tensor, Tensor, Tensor]:
  384. """Update the metric state by a tokenization of ``preds`` and ``target`` sentencens.
  385. Args:
  386. preds:
  387. An iterable of hypothesis corpus.
  388. target:
  389. An iterable of reference corpus.
  390. tokenizer:
  391. Initialized tokenizer from HuggingFace's `transformers package.
  392. max_length:
  393. A maximum length of input sequences. Sequences longer than `max_length` are to be trimmed.
  394. Return:
  395. Tokenizerd ``preds`` and ``target`` sentences represented with ``input_ids`` and ``attention_mask`` tensors.
  396. """
  397. # HuggingFace tokenizer expects an input to be of a type str or List[str]
  398. if not isinstance(preds, (str, list)):
  399. preds = list(preds)
  400. if not isinstance(target, (str, list)):
  401. target = list(target)
  402. preds_input = tokenizer(preds, padding="max_length", max_length=max_length, truncation=True, return_tensors="pt")
  403. target_input = tokenizer(target, padding="max_length", max_length=max_length, truncation=True, return_tensors="pt")
  404. return preds_input.input_ids, preds_input.attention_mask, target_input.input_ids, target_input.attention_mask
  405. def _infolm_compute(
  406. model: "PreTrainedModel",
  407. preds_dataloader: DataLoader,
  408. target_dataloader: DataLoader,
  409. temperature: float,
  410. idf: bool,
  411. information_measure_cls: _InformationMeasure,
  412. special_tokens_map: dict[str, int],
  413. verbose: bool = True,
  414. ) -> Tensor:
  415. """Calculate selected information measure using the pre-trained language model.
  416. Args:
  417. model:
  418. Initialized model from HuggingFace's `transformers package.
  419. preds_dataloader:
  420. Loader iterating over tokenizer predicted sentences.
  421. target_dataloader:
  422. Loader iterating over tokenizer reference sentences.
  423. temperature:
  424. A temperature for calibrating language modelling. For more information, please reference `InfoLM`_ paper.
  425. idf:
  426. An indication of whether normalization using inverse document frequencies should be used.
  427. information_measure_cls:
  428. Information measure class containing all parameters necessary for calculating information measure values
  429. using ``preds_distribution`` and ``target_distribution``.
  430. special_tokens_map:
  431. A dictionary mapping tokenizer special tokens into the corresponding integer values.
  432. verbose:
  433. An indication of whether a progress bar to be displayed during the embeddings calculation.
  434. Return:
  435. A corpus-level InfoLM score.
  436. """
  437. preds_distribution = _get_data_distribution(model, preds_dataloader, temperature, idf, special_tokens_map, verbose)
  438. target_distribution = _get_data_distribution(
  439. model, target_dataloader, temperature, idf, special_tokens_map, verbose
  440. )
  441. # Sort preds and target sentences
  442. preds_distribution = preds_distribution[preds_dataloader.dataset.sorting_indices]
  443. target_distribution = target_distribution[target_dataloader.dataset.sorting_indices]
  444. # Calculate information measure
  445. return information_measure_cls(preds_distribution, target_distribution)
  446. def infolm(
  447. preds: Union[str, Sequence[str]],
  448. target: Union[str, Sequence[str]],
  449. model_name_or_path: Union[str, os.PathLike] = "bert-base-uncased",
  450. temperature: float = 0.25,
  451. information_measure: _ALLOWED_INFORMATION_MEASURE_LITERAL = "kl_divergence",
  452. idf: bool = True,
  453. alpha: Optional[float] = None,
  454. beta: Optional[float] = None,
  455. device: Optional[Union[str, torch.device]] = None,
  456. max_length: Optional[int] = None,
  457. batch_size: int = 64,
  458. num_threads: int = 0,
  459. verbose: bool = True,
  460. return_sentence_level_score: bool = False,
  461. ) -> Union[Tensor, tuple[Tensor, Tensor]]:
  462. """Calculate `InfoLM`_ [1].
  463. InfoML corresponds to distance/divergence between predicted and reference sentence discrete distribution using
  464. one of the following information measures:
  465. - `KL divergence`_
  466. - `alpha divergence`_
  467. - `beta divergence`_
  468. - `AB divergence`_
  469. - `Rényi divergence`_
  470. - L1 distance
  471. - L2 distance
  472. - L-infinity distance
  473. - `Fisher-Rao distance`_
  474. `InfoLM`_ is a family of untrained embedding-based metrics which addresses some famous flaws of standard
  475. string-based metrics thanks to the usage of pre-trained masked language models. This family of metrics is mainly
  476. designed for summarization and data-to-text tasks.
  477. If you want to use IDF scaling over the whole dataset, please use the class metric.
  478. The implementation of this metric is fully based HuggingFace `transformers`' package.
  479. Args:
  480. preds:
  481. An iterable of hypothesis corpus.
  482. target:
  483. An iterable of reference corpus.
  484. model_name_or_path:
  485. A name or a model path used to load `transformers` pretrained model.
  486. temperature:
  487. A temperature for calibrating language modelling. For more information, please reference `InfoLM`_ paper.
  488. information_measure:
  489. A name of information measure to be used. Please use one of: ['kl_divergence', 'alpha_divergence',
  490. 'beta_divergence', 'ab_divergence', 'renyi_divergence', 'l1_distance', 'l2_distance', 'l_infinity_distance',
  491. 'fisher_rao_distance']
  492. idf:
  493. An indication of whether normalization using inverse document frequencies should be used.
  494. alpha:
  495. Alpha parameter of the divergence used for alpha, AB and Rényi divergence measures.
  496. beta:
  497. Beta parameter of the divergence used for beta and AB divergence measures.
  498. device:
  499. A device to be used for calculation.
  500. max_length:
  501. A maximum length of input sequences. Sequences longer than `max_length` are to be trimmed.
  502. batch_size:
  503. A batch size used for model processing.
  504. num_threads:
  505. A number of threads to use for a dataloader.
  506. verbose:
  507. An indication of whether a progress bar to be displayed during the embeddings calculation.
  508. return_sentence_level_score:
  509. An indication whether a sentence-level InfoLM score to be returned.
  510. Returns:
  511. A corpus-level InfoLM score.
  512. (Optionally) A list of sentence-level InfoLM scores if `return_sentence_level_score=True`.
  513. Example:
  514. >>> from torchmetrics.functional.text.infolm import infolm
  515. >>> preds = ['he read the book because he was interested in world history']
  516. >>> target = ['he was interested in world history because he read the book']
  517. >>> infolm(preds, target, model_name_or_path='google/bert_uncased_L-2_H-128_A-2', idf=False)
  518. tensor(-0.1784)
  519. References:
  520. [1] InfoLM: A New Metric to Evaluate Summarization & Data2Text Generation by Pierre Colombo, Chloé Clavel and
  521. Pablo Piantanida `InfoLM`_
  522. """
  523. tokenizer, model = _load_tokenizer_and_model(model_name_or_path, device)
  524. information_measure_cls = _InformationMeasure(information_measure, alpha, beta)
  525. max_length = max_length or model.config.max_length
  526. special_tokens_map = _get_special_tokens_map(tokenizer)
  527. preds_input_ids, preds_attention_mask, target_input_ids, target_attention_mask = _infolm_update(
  528. preds, target, tokenizer, max_length
  529. )
  530. preds_dataloader = _get_dataloader(preds_input_ids, preds_attention_mask, idf, batch_size, num_threads)
  531. target_dataloader = _get_dataloader(target_input_ids, target_attention_mask, idf, batch_size, num_threads)
  532. info_lm_score = _infolm_compute(
  533. model,
  534. preds_dataloader,
  535. target_dataloader,
  536. temperature,
  537. idf,
  538. information_measure_cls,
  539. special_tokens_map,
  540. verbose,
  541. )
  542. if return_sentence_level_score:
  543. return info_lm_score.mean(), info_lm_score
  544. return info_lm_score.mean()