chrf.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. # referenced from
  15. # Library Name: torchtext
  16. # Authors: torchtext authors and @sluks
  17. # Date: 2021-11-25
  18. # Link:
  19. import itertools
  20. from collections.abc import Iterator, Sequence
  21. from typing import Any, List, Optional, Union
  22. import torch
  23. from torch import Tensor, tensor
  24. from torchmetrics import Metric
  25. from torchmetrics.functional.text.chrf import _chrf_score_compute, _chrf_score_update, _prepare_n_grams_dicts
  26. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
  27. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  28. if not _MATPLOTLIB_AVAILABLE:
  29. __doctest_skip__ = ["CHRFScore.plot"]
  30. _N_GRAM_LEVELS = ("char", "word")
  31. _TEXT_LEVELS = ("preds", "target", "matching")
  32. _DICT_STATES_NAMES = (
  33. "total_preds_char_n_grams",
  34. "total_preds_word_n_grams",
  35. "total_target_char_n_grams",
  36. "total_target_word_n_grams",
  37. "total_matching_char_n_grams",
  38. "total_matching_word_n_grams",
  39. )
  40. _DICT_STATES_TYPES = tuple[
  41. dict[int, Tensor], dict[int, Tensor], dict[int, Tensor], dict[int, Tensor], dict[int, Tensor], dict[int, Tensor]
  42. ]
  43. class CHRFScore(Metric):
  44. """Calculate `chrf score`_ of machine translated text with one or more references.
  45. This implementation supports both ChrF score computation introduced in `chrF score`_ and `chrF++ score`_ introduced
  46. in `chrF++ score`_. This implementation follows the implementations from https://github.com/m-popovic/chrF and
  47. https://github.com/mjpost/sacrebleu/blob/master/sacrebleu/metrics/chrf.py.
  48. As input to ``forward`` and ``update`` the metric accepts the following input:
  49. - ``preds`` (:class:`~Sequence`): An iterable of hypothesis corpus
  50. - ``target`` (:class:`~Sequence`): An iterable of iterables of reference corpus
  51. As output of ``forward`` and ``compute`` the metric returns the following output:
  52. - ``chrf`` (:class:`~torch.Tensor`): If `return_sentence_level_score=True` return a list of sentence-level
  53. chrF/chrF++ scores, else return a corpus-level chrF/chrF++ score
  54. Args:
  55. n_char_order: A character n-gram order. If ``n_char_order=6``, the metrics refers to the official chrF/chrF++.
  56. n_word_order: A word n-gram order. If ``n_word_order=2``, the metric refers to the official chrF++.
  57. If ``n_word_order=0``, the metric is equivalent to the original ChrF.
  58. beta: parameter determining an importance of recall w.r.t. precision. If ``beta=1``, their importance is equal.
  59. lowercase: An indication whether to enable case-insensitivity.
  60. whitespace: An indication whether keep whitespaces during n-gram extraction.
  61. return_sentence_level_score: An indication whether a sentence-level chrF/chrF++ score to be returned.
  62. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  63. Raises:
  64. ValueError:
  65. If ``n_char_order`` is not an integer greater than or equal to 1.
  66. ValueError:
  67. If ``n_word_order`` is not an integer greater than or equal to 0.
  68. ValueError:
  69. If ``beta`` is smaller than 0.
  70. Example:
  71. >>> from torchmetrics.text import CHRFScore
  72. >>> preds = ['the cat is on the mat']
  73. >>> target = [['there is a cat on the mat', 'a cat is on the mat']]
  74. >>> chrf = CHRFScore()
  75. >>> chrf(preds, target)
  76. tensor(0.8640)
  77. """
  78. is_differentiable: bool = False
  79. higher_is_better: bool = True
  80. full_state_update: bool = True
  81. plot_lower_bound: float = 0.0
  82. plot_upper_bound: float = 1.0
  83. sentence_chrf_score: Optional[List[Tensor]] = None
  84. def __init__(
  85. self,
  86. n_char_order: int = 6,
  87. n_word_order: int = 2,
  88. beta: float = 2.0,
  89. lowercase: bool = False,
  90. whitespace: bool = False,
  91. return_sentence_level_score: bool = False,
  92. **kwargs: Any,
  93. ) -> None:
  94. super().__init__(**kwargs)
  95. if not isinstance(n_char_order, int) or n_char_order < 1:
  96. raise ValueError("Expected argument `n_char_order` to be an integer greater than or equal to 1.")
  97. self.n_char_order = n_char_order
  98. if not isinstance(n_word_order, int) or n_word_order < 0:
  99. raise ValueError("Expected argument `n_word_order` to be an integer greater than or equal to 0.")
  100. self.n_word_order = n_word_order
  101. if beta < 0:
  102. raise ValueError("Expected argument `beta` to be greater than 0.")
  103. self.beta = beta
  104. self.lowercase = lowercase
  105. self.whitespace = whitespace
  106. self.return_sentence_level_score = return_sentence_level_score
  107. self.n_order = float(n_char_order + n_word_order)
  108. # Adding state dynamically
  109. for (n_gram_level, n_gram_order), text in self._get_text_n_gram_iterator():
  110. for n in range(1, n_gram_order + 1):
  111. state_name = self._get_state_name(text, n_gram_level, n)
  112. self.add_state(state_name, tensor(0.0), dist_reduce_fx="sum")
  113. if self.return_sentence_level_score:
  114. self.add_state("sentence_chrf_score", [], dist_reduce_fx="cat")
  115. def update(self, preds: Sequence[str], target: Sequence[Sequence[str]]) -> None:
  116. """Update state with predictions and targets."""
  117. n_grams_dicts_tuple = _chrf_score_update(
  118. preds,
  119. target,
  120. *self._convert_states_to_dicts(),
  121. self.n_char_order,
  122. self.n_word_order,
  123. self.n_order,
  124. self.beta,
  125. self.lowercase,
  126. self.whitespace,
  127. self.sentence_chrf_score if self.return_sentence_level_score else None,
  128. )
  129. self._update_states_from_dicts(n_grams_dicts_tuple[:-1])
  130. if self.sentence_chrf_score is not None:
  131. self.sentence_chrf_score = n_grams_dicts_tuple[-1]
  132. def compute(self) -> Union[Tensor, tuple[Tensor, Tensor]]:
  133. """Calculate chrF/chrF++ score."""
  134. if self.sentence_chrf_score is not None:
  135. return (
  136. _chrf_score_compute(*self._convert_states_to_dicts(), self.n_order, self.beta),
  137. torch.cat(self.sentence_chrf_score),
  138. )
  139. return _chrf_score_compute(*self._convert_states_to_dicts(), self.n_order, self.beta)
  140. def _convert_states_to_dicts(self) -> _DICT_STATES_TYPES:
  141. """Convert global metric states to the n-gram dictionaries to be passed in ``_chrf_score_update``."""
  142. n_grams_dicts: dict[str, dict[int, Tensor]] = dict(
  143. zip(_DICT_STATES_NAMES, _prepare_n_grams_dicts(self.n_char_order, self.n_word_order))
  144. )
  145. for (n_gram_level, n_gram_order), text in self._get_text_n_gram_iterator():
  146. for n in range(1, n_gram_order + 1):
  147. dict_name = self._get_dict_name(text, n_gram_level)
  148. state_name = self._get_state_name(text, n_gram_level, n)
  149. n_grams_dicts[dict_name][n] = getattr(self, state_name)
  150. return tuple(n_grams_dicts.values()) # type: ignore
  151. def _update_states_from_dicts(self, n_grams_dicts_tuple: _DICT_STATES_TYPES) -> None:
  152. """Update global metric states based on the n-gram dictionaries calculated on the current batch."""
  153. n_grams_dicts = dict(zip(_DICT_STATES_NAMES, n_grams_dicts_tuple))
  154. for (n_gram_level, n_gram_order), text in self._get_text_n_gram_iterator():
  155. for n in range(1, n_gram_order + 1):
  156. dict_name = self._get_dict_name(text, n_gram_level)
  157. state_name = self._get_state_name(text, n_gram_level, n)
  158. setattr(self, state_name, n_grams_dicts[dict_name][n])
  159. @staticmethod
  160. def _get_dict_name(text: str, n_gram_level: str) -> str:
  161. """Return a dictionary name w.r.t input args."""
  162. return f"total_{text}_{n_gram_level}_n_grams"
  163. @staticmethod
  164. def _get_state_name(text: str, n_gram_level: str, n: int) -> str:
  165. """Return a metric state name w.r.t input args."""
  166. return f"total_{text}_{n_gram_level}_{n}_grams"
  167. def _get_text_n_gram_iterator(self) -> Iterator[tuple[tuple[str, int], str]]:
  168. """Get iterator over char/word and reference/hypothesis/matching n-gram level."""
  169. return itertools.product(zip(_N_GRAM_LEVELS, [self.n_char_order, self.n_word_order]), _TEXT_LEVELS)
  170. def plot(
  171. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  172. ) -> _PLOT_OUT_TYPE:
  173. """Plot a single or multiple values from the metric.
  174. Args:
  175. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  176. If no value is provided, will automatically call `metric.compute` and plot that result.
  177. ax: An matplotlib axis object. If provided will add plot to that axis
  178. Returns:
  179. Figure and Axes object
  180. Raises:
  181. ModuleNotFoundError:
  182. If `matplotlib` is not installed
  183. .. plot::
  184. :scale: 75
  185. >>> # Example plotting a single value
  186. >>> from torchmetrics.text import CHRFScore
  187. >>> metric = CHRFScore()
  188. >>> preds = ['the cat is on the mat']
  189. >>> target = [['there is a cat on the mat', 'a cat is on the mat']]
  190. >>> metric.update(preds, target)
  191. >>> fig_, ax_ = metric.plot()
  192. .. plot::
  193. :scale: 75
  194. >>> # Example plotting multiple values
  195. >>> from torchmetrics.text import CHRFScore
  196. >>> metric = CHRFScore()
  197. >>> preds = ['the cat is on the mat']
  198. >>> target = [['there is a cat on the mat', 'a cat is on the mat']]
  199. >>> values = [ ]
  200. >>> for _ in range(10):
  201. ... values.append(metric(preds, target))
  202. >>> fig_, ax_ = metric.plot(values)
  203. """
  204. return self._plot(val, ax)