watermarking.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. # coding=utf-8
  2. # Copyright 2024 The HuggingFace Inc. team and Google DeepMind.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import collections
  16. from dataclasses import dataclass
  17. from functools import lru_cache
  18. from typing import Any, Optional, Union
  19. import numpy as np
  20. import torch
  21. from torch import nn
  22. from torch.nn import BCELoss
  23. from ..modeling_utils import PreTrainedModel
  24. from ..utils import ModelOutput, logging
  25. from .configuration_utils import PretrainedConfig, WatermarkingConfig
  26. from .logits_process import SynthIDTextWatermarkLogitsProcessor, WatermarkLogitsProcessor
  27. logger = logging.get_logger(__name__)
  28. @dataclass
  29. class WatermarkDetectorOutput:
  30. """
  31. Outputs of a watermark detector.
  32. Args:
  33. num_tokens_scored (np.ndarray of shape (batch_size)):
  34. Array containing the number of tokens scored for each element in the batch.
  35. num_green_tokens (np.ndarray of shape (batch_size)):
  36. Array containing the number of green tokens for each element in the batch.
  37. green_fraction (np.ndarray of shape (batch_size)):
  38. Array containing the fraction of green tokens for each element in the batch.
  39. z_score (np.ndarray of shape (batch_size)):
  40. Array containing the z-score for each element in the batch. Z-score here shows
  41. how many standard deviations away is the green token count in the input text
  42. from the expected green token count for machine-generated text.
  43. p_value (np.ndarray of shape (batch_size)):
  44. Array containing the p-value for each batch obtained from z-scores.
  45. prediction (np.ndarray of shape (batch_size)), *optional*:
  46. Array containing boolean predictions whether a text is machine-generated for each element in the batch.
  47. confidence (np.ndarray of shape (batch_size)), *optional*:
  48. Array containing confidence scores of a text being machine-generated for each element in the batch.
  49. """
  50. num_tokens_scored: Optional[np.ndarray] = None
  51. num_green_tokens: Optional[np.ndarray] = None
  52. green_fraction: Optional[np.ndarray] = None
  53. z_score: Optional[np.ndarray] = None
  54. p_value: Optional[np.ndarray] = None
  55. prediction: Optional[np.ndarray] = None
  56. confidence: Optional[np.ndarray] = None
  57. class WatermarkDetector:
  58. r"""
  59. Detector for detection of watermark generated text. The detector needs to be given the exact same settings that were
  60. given during text generation to replicate the watermark greenlist generation and so detect the watermark. This includes
  61. the correct device that was used during text generation, the correct watermarking arguments and the correct tokenizer vocab size.
  62. The code was based on the [original repo](https://github.com/jwkirchenbauer/lm-watermarking/tree/main).
  63. See [the paper](https://huggingface.co/papers/2306.04634) for more information.
  64. Args:
  65. model_config (`PretrainedConfig`):
  66. The model config that will be used to get model specific arguments used when generating.
  67. device (`str`):
  68. The device which was used during watermarked text generation.
  69. watermarking_config (Union[`WatermarkingConfig`, `Dict`]):
  70. The exact same watermarking config and arguments used when generating text.
  71. ignore_repeated_ngrams (`bool`, *optional*, defaults to `False`):
  72. Whether to count every unique ngram only once or not.
  73. max_cache_size (`int`, *optional*, defaults to 128):
  74. The max size to be used for LRU caching of seeding/sampling algorithms called for every token.
  75. Examples:
  76. ```python
  77. >>> from transformers import AutoTokenizer, AutoModelForCausalLM, WatermarkDetector, WatermarkingConfig
  78. >>> model_id = "openai-community/gpt2"
  79. >>> model = AutoModelForCausalLM.from_pretrained(model_id)
  80. >>> tok = AutoTokenizer.from_pretrained(model_id)
  81. >>> tok.pad_token_id = tok.eos_token_id
  82. >>> tok.padding_side = "left"
  83. >>> inputs = tok(["This is the beginning of a long story", "Alice and Bob are"], padding=True, return_tensors="pt")
  84. >>> input_len = inputs["input_ids"].shape[-1]
  85. >>> # first generate text with watermark and without
  86. >>> watermarking_config = WatermarkingConfig(bias=2.5, seeding_scheme="selfhash")
  87. >>> out_watermarked = model.generate(**inputs, watermarking_config=watermarking_config, do_sample=False, max_length=20)
  88. >>> out = model.generate(**inputs, do_sample=False, max_length=20)
  89. >>> # now we can instantiate the detector and check the generated text
  90. >>> detector = WatermarkDetector(model_config=model.config, device="cpu", watermarking_config=watermarking_config)
  91. >>> detection_out_watermarked = detector(out_watermarked, return_dict=True)
  92. >>> detection_out = detector(out, return_dict=True)
  93. >>> detection_out_watermarked.prediction
  94. array([ True, True])
  95. >>> detection_out.prediction
  96. array([False, False])
  97. ```
  98. """
  99. def __init__(
  100. self,
  101. model_config: PretrainedConfig,
  102. device: str,
  103. watermarking_config: Union[WatermarkingConfig, dict],
  104. ignore_repeated_ngrams: bool = False,
  105. max_cache_size: int = 128,
  106. ):
  107. if isinstance(watermarking_config, WatermarkingConfig):
  108. watermarking_config = watermarking_config.to_dict()
  109. self.bos_token_id = (
  110. model_config.bos_token_id if not model_config.is_encoder_decoder else model_config.decoder_start_token_id
  111. )
  112. self.greenlist_ratio = watermarking_config["greenlist_ratio"]
  113. self.ignore_repeated_ngrams = ignore_repeated_ngrams
  114. self.processor = WatermarkLogitsProcessor(
  115. vocab_size=model_config.vocab_size, device=device, **watermarking_config
  116. )
  117. # Expensive re-seeding and sampling is cached.
  118. self._get_ngram_score_cached = lru_cache(maxsize=max_cache_size)(self._get_ngram_score)
  119. def _get_ngram_score(self, prefix: torch.LongTensor, target: int):
  120. greenlist_ids = self.processor._get_greenlist_ids(prefix)
  121. return target in greenlist_ids
  122. def _score_ngrams_in_passage(self, input_ids: torch.LongTensor):
  123. batch_size, seq_length = input_ids.shape
  124. selfhash = int(self.processor.seeding_scheme == "selfhash")
  125. n = self.processor.context_width + 1 - selfhash
  126. indices = torch.arange(n).unsqueeze(0) + torch.arange(seq_length - n + 1).unsqueeze(1)
  127. ngram_tensors = input_ids[:, indices]
  128. num_tokens_scored_batch = np.zeros(batch_size)
  129. green_token_count_batch = np.zeros(batch_size)
  130. for batch_idx in range(ngram_tensors.shape[0]):
  131. frequencies_table = collections.Counter(ngram_tensors[batch_idx])
  132. ngram_to_watermark_lookup = {}
  133. for ngram_example in frequencies_table:
  134. prefix = ngram_example if selfhash else ngram_example[:-1]
  135. target = ngram_example[-1]
  136. ngram_to_watermark_lookup[ngram_example] = self._get_ngram_score_cached(prefix, target)
  137. if self.ignore_repeated_ngrams:
  138. # counts a green/red hit once per unique ngram.
  139. # num total tokens scored becomes the number unique ngrams.
  140. num_tokens_scored_batch[batch_idx] = len(frequencies_table.keys())
  141. green_token_count_batch[batch_idx] = sum(ngram_to_watermark_lookup.values())
  142. else:
  143. num_tokens_scored_batch[batch_idx] = sum(frequencies_table.values())
  144. green_token_count_batch[batch_idx] = sum(
  145. freq * outcome
  146. for freq, outcome in zip(frequencies_table.values(), ngram_to_watermark_lookup.values())
  147. )
  148. return num_tokens_scored_batch, green_token_count_batch
  149. def _compute_z_score(self, green_token_count: np.ndarray, total_num_tokens: np.ndarray) -> np.ndarray:
  150. expected_count = self.greenlist_ratio
  151. numer = green_token_count - expected_count * total_num_tokens
  152. denom = np.sqrt(total_num_tokens * expected_count * (1 - expected_count))
  153. z = numer / denom
  154. return z
  155. def _compute_pval(self, x, loc=0, scale=1):
  156. z = (x - loc) / scale
  157. return 1 - (0.5 * (1 + np.sign(z) * (1 - np.exp(-2 * z**2 / np.pi))))
  158. def __call__(
  159. self,
  160. input_ids: torch.LongTensor,
  161. z_threshold: float = 3.0,
  162. return_dict: bool = False,
  163. ) -> Union[WatermarkDetectorOutput, np.ndarray]:
  164. """
  165. Args:
  166. input_ids (`torch.LongTensor`):
  167. The watermark generated text. It is advised to remove the prompt, which can affect the detection.
  168. z_threshold (`Dict`, *optional*, defaults to `3.0`):
  169. Changing this threshold will change the sensitivity of the detector. Higher z threshold gives less
  170. sensitivity and vice versa for lower z threshold.
  171. return_dict (`bool`, *optional*, defaults to `False`):
  172. Whether to return `~generation.WatermarkDetectorOutput` or not. If not it will return boolean predictions,
  173. ma
  174. Return:
  175. [`~generation.WatermarkDetectorOutput`] or `np.ndarray`: A [`~generation.WatermarkDetectorOutput`]
  176. if `return_dict=True` otherwise a `np.ndarray`.
  177. """
  178. # Let's assume that if one batch start with `bos`, all batched also do
  179. if input_ids[0, 0] == self.bos_token_id:
  180. input_ids = input_ids[:, 1:]
  181. if input_ids.shape[-1] - self.processor.context_width < 1:
  182. raise ValueError(
  183. f"Must have at least `1` token to score after the first "
  184. f"min_prefix_len={self.processor.context_width} tokens required by the seeding scheme."
  185. )
  186. num_tokens_scored, green_token_count = self._score_ngrams_in_passage(input_ids)
  187. z_score = self._compute_z_score(green_token_count, num_tokens_scored)
  188. prediction = z_score > z_threshold
  189. if return_dict:
  190. p_value = self._compute_pval(z_score)
  191. confidence = 1 - p_value
  192. return WatermarkDetectorOutput(
  193. num_tokens_scored=num_tokens_scored,
  194. num_green_tokens=green_token_count,
  195. green_fraction=green_token_count / num_tokens_scored,
  196. z_score=z_score,
  197. p_value=p_value,
  198. prediction=prediction,
  199. confidence=confidence,
  200. )
  201. return prediction
  202. class BayesianDetectorConfig(PretrainedConfig):
  203. """
  204. This is the configuration class to store the configuration of a [`BayesianDetectorModel`]. It is used to
  205. instantiate a Bayesian Detector model according to the specified arguments.
  206. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
  207. documentation from [`PretrainedConfig`] for more information.
  208. Args:
  209. watermarking_depth (`int`, *optional*):
  210. The number of tournament layers.
  211. base_rate (`float1`, *optional*, defaults to 0.5):
  212. Prior probability P(w) that a text is watermarked.
  213. """
  214. def __init__(self, watermarking_depth: Optional[int] = None, base_rate: float = 0.5, **kwargs):
  215. self.watermarking_depth = watermarking_depth
  216. self.base_rate = base_rate
  217. # These can be set later to store information about this detector.
  218. self.model_name = None
  219. self.watermarking_config = None
  220. super().__init__(**kwargs)
  221. def set_detector_information(self, model_name, watermarking_config):
  222. self.model_name = model_name
  223. self.watermarking_config = watermarking_config
  224. @dataclass
  225. class BayesianWatermarkDetectorModelOutput(ModelOutput):
  226. """
  227. Base class for outputs of models predicting if the text is watermarked.
  228. Args:
  229. loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
  230. Language modeling loss.
  231. posterior_probabilities (`torch.FloatTensor` of shape `(1,)`):
  232. Multiple choice classification loss.
  233. """
  234. loss: Optional[torch.FloatTensor] = None
  235. posterior_probabilities: Optional[torch.FloatTensor] = None
  236. class BayesianDetectorWatermarkedLikelihood(nn.Module):
  237. """Watermarked likelihood model for binary-valued g-values.
  238. This takes in g-values and returns p(g_values|watermarked).
  239. """
  240. def __init__(self, watermarking_depth: int):
  241. """Initializes the model parameters."""
  242. super().__init__()
  243. self.watermarking_depth = watermarking_depth
  244. self.beta = torch.nn.Parameter(-2.5 + 0.001 * torch.randn(1, 1, watermarking_depth))
  245. self.delta = torch.nn.Parameter(0.001 * torch.randn(1, 1, self.watermarking_depth, watermarking_depth))
  246. def _compute_latents(self, g_values: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
  247. """Computes the unique token probability distribution given g-values.
  248. Args:
  249. g_values (`torch.Tensor` of shape `(batch_size, seq_len, watermarking_depth)`):
  250. PRF values.
  251. Returns:
  252. p_one_unique_token and p_two_unique_tokens, both of shape
  253. [batch_size, seq_len, watermarking_depth]. p_one_unique_token[i,t,l]
  254. gives the probability of there being one unique token in a tournament
  255. match on layer l, on timestep t, for batch item i.
  256. p_one_unique_token[i,t,l] + p_two_unique_token[i,t,l] = 1.
  257. """
  258. # Tile g-values to produce feature vectors for predicting the latents
  259. # for each layer in the tournament; our model for the latents psi is a
  260. # logistic regression model psi = sigmoid(delta * x + beta).
  261. # [batch_size, seq_len, watermarking_depth, watermarking_depth]
  262. x = torch.repeat_interleave(torch.unsqueeze(g_values, dim=-2), self.watermarking_depth, axis=-2)
  263. # mask all elements above -1 diagonal for autoregressive factorization
  264. x = torch.tril(x, diagonal=-1)
  265. # [batch_size, seq_len, watermarking_depth]
  266. # (i, j, k, l) x (i, j, k, l) -> (i, j, k) einsum equivalent
  267. logits = (self.delta[..., None, :] @ x.type(self.delta.dtype)[..., None]).squeeze() + self.beta
  268. p_two_unique_tokens = torch.sigmoid(logits)
  269. p_one_unique_token = 1 - p_two_unique_tokens
  270. return p_one_unique_token, p_two_unique_tokens
  271. def forward(self, g_values: torch.Tensor) -> torch.Tensor:
  272. """Computes the likelihoods P(g_values|watermarked).
  273. Args:
  274. g_values (`torch.Tensor` of shape `(batch_size, seq_len, watermarking_depth)`):
  275. g-values (values 0 or 1)
  276. Returns:
  277. p(g_values|watermarked) of shape [batch_size, seq_len, watermarking_depth].
  278. """
  279. p_one_unique_token, p_two_unique_tokens = self._compute_latents(g_values)
  280. # P(g_tl | watermarked) is equal to
  281. # 0.5 * [ (g_tl+0.5) * p_two_unique_tokens + p_one_unique_token].
  282. return 0.5 * ((g_values + 0.5) * p_two_unique_tokens + p_one_unique_token)
  283. class BayesianDetectorModel(PreTrainedModel):
  284. r"""
  285. Bayesian classifier for watermark detection.
  286. This detector uses Bayes' rule to compute a watermarking score, which is the sigmoid of the log of ratio of the
  287. posterior probabilities P(watermarked|g_values) and P(unwatermarked|g_values). Please see the section on
  288. BayesianScore in the paper for further details.
  289. Paper URL: https://www.nature.com/articles/s41586-024-08025-4
  290. Note that this detector only works with non-distortionary Tournament-based watermarking using the Bernoulli(0.5)
  291. g-value distribution.
  292. This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
  293. library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
  294. etc.)
  295. This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
  296. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
  297. and behavior.
  298. Parameters:
  299. config ([`BayesianDetectorConfig`]): Model configuration class with all the parameters of the model.
  300. Initializing with a config file does not load the weights associated with the model, only the
  301. configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
  302. """
  303. config: BayesianDetectorConfig
  304. base_model_prefix = "model"
  305. def __init__(self, config):
  306. super().__init__(config)
  307. self.watermarking_depth = config.watermarking_depth
  308. self.base_rate = config.base_rate
  309. self.likelihood_model_watermarked = BayesianDetectorWatermarkedLikelihood(
  310. watermarking_depth=self.watermarking_depth
  311. )
  312. self.prior = torch.nn.Parameter(torch.tensor([self.base_rate]))
  313. def _init_weights(self, module):
  314. """Initialize the weights."""
  315. if isinstance(module, nn.Parameter):
  316. module.weight.data.normal_(mean=0.0, std=0.02)
  317. def _compute_posterior(
  318. self,
  319. likelihoods_watermarked: torch.Tensor,
  320. likelihoods_unwatermarked: torch.Tensor,
  321. mask: torch.Tensor,
  322. prior: float,
  323. ) -> torch.Tensor:
  324. """
  325. Compute posterior P(w|g) given likelihoods, mask and prior.
  326. Args:
  327. likelihoods_watermarked (`torch.Tensor` of shape `(batch, length, depth)`):
  328. Likelihoods P(g_values|watermarked) of g-values under watermarked model.
  329. likelihoods_unwatermarked (`torch.Tensor` of shape `(batch, length, depth)`):
  330. Likelihoods P(g_values|unwatermarked) of g-values under unwatermarked model.
  331. mask (`torch.Tensor` of shape `(batch, length)`):
  332. A binary array indicating which g-values should be used. g-values with mask value 0 are discarded.
  333. prior (`float`):
  334. the prior probability P(w) that the text is watermarked.
  335. Returns:
  336. Posterior probability P(watermarked|g_values), shape [batch].
  337. """
  338. mask = torch.unsqueeze(mask, dim=-1)
  339. prior = torch.clamp(prior, min=1e-5, max=1 - 1e-5)
  340. log_likelihoods_watermarked = torch.log(torch.clamp(likelihoods_watermarked, min=1e-30, max=float("inf")))
  341. log_likelihoods_unwatermarked = torch.log(torch.clamp(likelihoods_unwatermarked, min=1e-30, max=float("inf")))
  342. log_odds = log_likelihoods_watermarked - log_likelihoods_unwatermarked
  343. # Sum relative surprisals (log odds) across all token positions and layers.
  344. relative_surprisal_likelihood = torch.einsum("i...->i", log_odds * mask)
  345. # Compute the relative surprisal prior
  346. relative_surprisal_prior = torch.log(prior) - torch.log(1 - prior)
  347. # Combine prior and likelihood.
  348. # [batch_size]
  349. relative_surprisal = relative_surprisal_prior + relative_surprisal_likelihood
  350. # Compute the posterior probability P(w|g) = sigmoid(relative_surprisal).
  351. return torch.sigmoid(relative_surprisal)
  352. def forward(
  353. self,
  354. g_values: torch.Tensor,
  355. mask: torch.Tensor,
  356. labels: Optional[torch.Tensor] = None,
  357. loss_batch_weight=1,
  358. return_dict=False,
  359. ) -> BayesianWatermarkDetectorModelOutput:
  360. """
  361. Computes the watermarked posterior P(watermarked|g_values).
  362. Args:
  363. g_values (`torch.Tensor` of shape `(batch_size, seq_len, watermarking_depth, ...)`):
  364. g-values (with values 0 or 1)
  365. mask:
  366. A binary array shape [batch_size, seq_len] indicating which g-values should be used. g-values with mask
  367. value 0 are discarded.
  368. Returns:
  369. p(watermarked | g_values), of shape [batch_size].
  370. """
  371. likelihoods_watermarked = self.likelihood_model_watermarked(g_values)
  372. likelihoods_unwatermarked = 0.5 * torch.ones_like(g_values)
  373. out = self._compute_posterior(
  374. likelihoods_watermarked=likelihoods_watermarked,
  375. likelihoods_unwatermarked=likelihoods_unwatermarked,
  376. mask=mask,
  377. prior=self.prior,
  378. )
  379. loss = None
  380. if labels is not None:
  381. loss_fct = BCELoss()
  382. loss_unwweight = torch.sum(self.likelihood_model_watermarked.delta**2)
  383. loss_weight = loss_unwweight * loss_batch_weight
  384. loss = loss_fct(torch.clamp(out, 1e-5, 1 - 1e-5), labels) + loss_weight
  385. if not return_dict:
  386. return (out,) if loss is None else (out, loss)
  387. return BayesianWatermarkDetectorModelOutput(loss=loss, posterior_probabilities=out)
  388. class SynthIDTextWatermarkDetector:
  389. r"""
  390. SynthID text watermark detector class.
  391. This class has to be initialized with the trained bayesian detector module check script
  392. in examples/synthid_text/detector_training.py for example in training/saving/loading this
  393. detector module. The folder also showcases example use case of this detector.
  394. Parameters:
  395. detector_module ([`BayesianDetectorModel`]):
  396. Bayesian detector module object initialized with parameters.
  397. Check https://github.com/huggingface/transformers-research-projects/tree/main/synthid_text for usage.
  398. logits_processor (`SynthIDTextWatermarkLogitsProcessor`):
  399. The logits processor used for watermarking.
  400. tokenizer (`Any`):
  401. The tokenizer used for the model.
  402. Examples:
  403. ```python
  404. >>> from transformers import (
  405. ... AutoTokenizer, BayesianDetectorModel, SynthIDTextWatermarkLogitsProcessor, SynthIDTextWatermarkDetector
  406. ... )
  407. >>> # Load the detector. See https://github.com/huggingface/transformers-research-projects/tree/main/synthid_text for training a detector.
  408. >>> detector_model = BayesianDetectorModel.from_pretrained("joaogante/dummy_synthid_detector")
  409. >>> logits_processor = SynthIDTextWatermarkLogitsProcessor(
  410. ... **detector_model.config.watermarking_config, device="cpu"
  411. ... )
  412. >>> tokenizer = AutoTokenizer.from_pretrained(detector_model.config.model_name)
  413. >>> detector = SynthIDTextWatermarkDetector(detector_model, logits_processor, tokenizer)
  414. >>> # Test whether a certain string is watermarked
  415. >>> test_input = tokenizer(["This is a test input"], return_tensors="pt")
  416. >>> is_watermarked = detector(test_input.input_ids)
  417. ```
  418. """
  419. def __init__(
  420. self,
  421. detector_module: BayesianDetectorModel,
  422. logits_processor: SynthIDTextWatermarkLogitsProcessor,
  423. tokenizer: Any,
  424. ):
  425. self.detector_module = detector_module
  426. self.logits_processor = logits_processor
  427. self.tokenizer = tokenizer
  428. def __call__(self, tokenized_outputs: torch.Tensor):
  429. # eos mask is computed, skip first ngram_len - 1 tokens
  430. # eos_mask will be of shape [batch_size, output_len]
  431. eos_token_mask = self.logits_processor.compute_eos_token_mask(
  432. input_ids=tokenized_outputs,
  433. eos_token_id=self.tokenizer.eos_token_id,
  434. )[:, self.logits_processor.ngram_len - 1 :]
  435. # context repetition mask is computed
  436. context_repetition_mask = self.logits_processor.compute_context_repetition_mask(
  437. input_ids=tokenized_outputs,
  438. )
  439. # context repetition mask shape [batch_size, output_len - (ngram_len - 1)]
  440. combined_mask = context_repetition_mask * eos_token_mask
  441. g_values = self.logits_processor.compute_g_values(
  442. input_ids=tokenized_outputs,
  443. )
  444. # g values shape [batch_size, output_len - (ngram_len - 1), depth]
  445. return self.detector_module(g_values, combined_mask)