beam_constraints.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. from abc import ABC, abstractmethod
  2. from typing import Optional
  3. from ..utils import logging
  4. logger = logging.get_logger(__name__)
  5. # TODO joao, manuel: remove in v4.58.0
  6. class Constraint(ABC):
  7. r"""Abstract base class for all constraints that can be applied during generation.
  8. It must define how the constraint can be satisfied.
  9. All classes that inherit Constraint must follow the requirement that
  10. ```py
  11. completed = False
  12. while not completed:
  13. _, completed = constraint.update(constraint.advance())
  14. ```
  15. will always terminate (halt).
  16. """
  17. def __init__(self):
  18. logger.warning_once(
  19. "Importing `Constraint` classes is deprecated and will be removed in v4.58.0. Constrained beam search has been moved to the Hub: https://hf.co/transformers-community/constrained-beam-search. Please import using `from transformers.generation import Constraint` instead."
  20. )
  21. # test for the above condition
  22. self.test()
  23. def test(self):
  24. """
  25. Tests whether this constraint has been properly defined.
  26. """
  27. counter = 0
  28. completed = False
  29. while not completed:
  30. if counter == 1:
  31. self.reset()
  32. advance = self.advance()
  33. if not self.does_advance(advance):
  34. raise Exception(
  35. "Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true."
  36. )
  37. stepped, completed, reset = self.update(advance)
  38. counter += 1
  39. if counter > 10000:
  40. raise Exception("update() does not fulfill the constraint.")
  41. if self.remaining() != 0:
  42. raise Exception("Custom Constraint is not defined correctly.")
  43. @abstractmethod
  44. def advance(self):
  45. """
  46. When called, returns the token(s) that would take this constraint one step closer to being fulfilled.
  47. Return:
  48. token_ids (Union[int, list[int], None]):
  49. - A single token ID (int) that advances the constraint, or
  50. - A list of token IDs that could advance the constraint
  51. - None if the constraint is completed or cannot be advanced
  52. """
  53. raise NotImplementedError(
  54. f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
  55. )
  56. @abstractmethod
  57. def does_advance(self, token_id: int):
  58. """
  59. Reads in a token and returns whether it creates progress.
  60. """
  61. raise NotImplementedError(
  62. f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
  63. )
  64. @abstractmethod
  65. def update(self, token_id: int):
  66. """
  67. Reads in a token and returns booleans that indicate the progress made by it. This function will update the
  68. state of this object unlikes `does_advance(self, token_id: int)`.
  69. This isn't to test whether a certain token will advance the progress; it's to update its state as if it has
  70. been generated. This becomes important if token_id != desired token (refer to else statement in
  71. PhrasalConstraint)
  72. Args:
  73. token_id(`int`):
  74. The id of a newly generated token in the beam search.
  75. Return:
  76. stepped(`bool`):
  77. Whether this constraint has become one step closer to being fulfuilled.
  78. completed(`bool`):
  79. Whether this constraint has been completely fulfilled by this token being generated.
  80. reset (`bool`):
  81. Whether this constraint has reset its progress by this token being generated.
  82. """
  83. raise NotImplementedError(
  84. f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
  85. )
  86. @abstractmethod
  87. def reset(self):
  88. """
  89. Resets the state of this constraint to its initialization. We would call this in cases where the fulfillment of
  90. a constraint is abrupted by an unwanted token.
  91. """
  92. raise NotImplementedError(
  93. f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
  94. )
  95. @abstractmethod
  96. def remaining(self):
  97. """
  98. Returns the number of remaining steps of `advance()` in order to complete this constraint.
  99. """
  100. raise NotImplementedError(
  101. f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
  102. )
  103. @abstractmethod
  104. def copy(self, stateful=False):
  105. """
  106. Creates a new instance of this constraint.
  107. Args:
  108. stateful(`bool`): Whether to not only copy the constraint for new instance, but also its state.
  109. Return:
  110. constraint(`Constraint`): The same constraint as the one being called from.
  111. """
  112. raise NotImplementedError(
  113. f"{self.__class__} is an abstract class. Only classes inheriting this class can be called."
  114. )
  115. class PhrasalConstraint(Constraint):
  116. r"""
  117. [`Constraint`] enforcing that an ordered sequence of tokens is included in the output.
  118. Args:
  119. token_ids (`list[int]`):
  120. The id of the token that must be generated by the output.
  121. """
  122. def __init__(self, token_ids: list[int]):
  123. super(Constraint, self).__init__()
  124. if not isinstance(token_ids, list) or len(token_ids) == 0:
  125. raise ValueError(f"`token_ids` has to be a non-empty list, but is {token_ids}.")
  126. if any((not isinstance(token_id, int) or token_id < 0) for token_id in token_ids):
  127. raise ValueError(f"Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.")
  128. self.token_ids = token_ids
  129. self.seqlen = len(self.token_ids)
  130. self.fulfilled_idx = -1 # the index of the currently fulfilled step
  131. self.completed = False
  132. def advance(self):
  133. if self.completed:
  134. return None
  135. return self.token_ids[self.fulfilled_idx + 1]
  136. def does_advance(self, token_id: int):
  137. if not isinstance(token_id, int):
  138. raise TypeError(f"`token_id` has to be an `int`, but is {token_id} of type {type(token_id)}")
  139. if self.completed:
  140. return False
  141. return token_id == self.token_ids[self.fulfilled_idx + 1]
  142. def update(self, token_id: int):
  143. if not isinstance(token_id, int):
  144. raise TypeError(f"`token_id` has to be an `int`, but is {token_id} of type {type(token_id)}")
  145. stepped = False
  146. completed = False
  147. reset = False
  148. if self.does_advance(token_id):
  149. self.fulfilled_idx += 1
  150. stepped = True
  151. if self.fulfilled_idx == (self.seqlen - 1):
  152. completed = True
  153. self.completed = completed
  154. else:
  155. # failed to make progress.
  156. reset = True
  157. self.reset()
  158. return stepped, completed, reset
  159. def reset(self):
  160. self.completed = False
  161. self.fulfilled_idx = 0
  162. def remaining(self):
  163. return self.seqlen - (self.fulfilled_idx + 1)
  164. def copy(self, stateful=False):
  165. new_constraint = PhrasalConstraint(self.token_ids)
  166. if stateful:
  167. new_constraint.seq_len = self.seqlen
  168. new_constraint.fulfilled_idx = self.fulfilled_idx
  169. new_constraint.completed = self.completed
  170. return new_constraint
  171. class DisjunctiveTrie:
  172. def __init__(self, nested_token_ids: list[list[int]], no_subsets=True):
  173. r"""
  174. A helper class that builds a trie with the words represented in `nested_token_ids`.
  175. """
  176. self.max_height = max([len(one) for one in nested_token_ids])
  177. root = {}
  178. for token_ids in nested_token_ids:
  179. level = root
  180. for tidx, token_id in enumerate(token_ids):
  181. if token_id not in level:
  182. level[token_id] = {}
  183. level = level[token_id]
  184. if no_subsets and self.has_subsets(root, nested_token_ids):
  185. raise ValueError(
  186. "Each list in `nested_token_ids` can't be a complete subset of another list, but is"
  187. f" {nested_token_ids}."
  188. )
  189. self.trie = root
  190. def next_tokens(self, current_seq):
  191. """
  192. The next possible tokens that will progress the trie, given the current sequence of tokens in `current_seq`.
  193. """
  194. start = self.trie
  195. for current_token in current_seq:
  196. start = start[current_token]
  197. next_tokens = list(start.keys())
  198. return next_tokens
  199. def reached_leaf(self, current_seq):
  200. next_tokens = self.next_tokens(current_seq)
  201. return len(next_tokens) == 0
  202. def count_leaves(self, root):
  203. next_nodes = list(root.values())
  204. if len(next_nodes) == 0:
  205. return 1
  206. else:
  207. return sum([self.count_leaves(nn) for nn in next_nodes])
  208. def has_subsets(self, trie, nested_token_ids):
  209. """
  210. Returns whether # of leaves == # of words. Otherwise some word is a subset of another.
  211. """
  212. leaf_count = self.count_leaves(trie)
  213. return len(nested_token_ids) != leaf_count
  214. class DisjunctiveConstraint(Constraint):
  215. r"""
  216. A special [`Constraint`] that is fulfilled by fulfilling just one of several constraints.
  217. Args:
  218. nested_token_ids (`list[list[int]]`):
  219. A list of words, where each word is a list of ids. This constraint is fulfilled by generating just one from
  220. the list of words.
  221. """
  222. def __init__(self, nested_token_ids: list[list[int]]):
  223. super(Constraint, self).__init__()
  224. if not isinstance(nested_token_ids, list) or len(nested_token_ids) == 0:
  225. raise ValueError(f"`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.")
  226. if any(not isinstance(token_ids, list) for token_ids in nested_token_ids):
  227. raise ValueError(f"`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.")
  228. if any(
  229. any((not isinstance(token_id, int) or token_id < 0) for token_id in token_ids)
  230. for token_ids in nested_token_ids
  231. ):
  232. raise ValueError(
  233. f"Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}."
  234. )
  235. self.trie = DisjunctiveTrie(nested_token_ids)
  236. self.token_ids = nested_token_ids
  237. self.seqlen = self.trie.max_height
  238. self.current_seq = []
  239. self.completed = False
  240. def advance(self):
  241. token_list = self.trie.next_tokens(self.current_seq)
  242. if len(token_list) == 0:
  243. return None
  244. else:
  245. return token_list
  246. def does_advance(self, token_id: int):
  247. if not isinstance(token_id, int):
  248. raise TypeError(f"`token_id` is supposed to be type `int`, but is {token_id} of type {type(token_id)}")
  249. next_tokens = self.trie.next_tokens(self.current_seq)
  250. return token_id in next_tokens
  251. def update(self, token_id: int):
  252. if not isinstance(token_id, int):
  253. raise TypeError(f"`token_id` is supposed to be type `int`, but is {token_id} of type {type(token_id)}")
  254. stepped = False
  255. completed = False
  256. reset = False
  257. if self.does_advance(token_id):
  258. self.current_seq.append(token_id)
  259. stepped = True
  260. else:
  261. reset = True
  262. self.reset()
  263. completed = self.trie.reached_leaf(self.current_seq)
  264. self.completed = completed
  265. return stepped, completed, reset
  266. def reset(self):
  267. self.completed = False
  268. self.current_seq = []
  269. def remaining(self):
  270. if self.completed:
  271. # since this can be completed without reaching max height
  272. return 0
  273. else:
  274. return self.seqlen - len(self.current_seq)
  275. def copy(self, stateful=False):
  276. new_constraint = DisjunctiveConstraint(self.token_ids)
  277. if stateful:
  278. new_constraint.seq_len = self.seqlen
  279. new_constraint.current_seq = self.current_seq
  280. new_constraint.completed = self.completed
  281. return new_constraint
  282. class ConstraintListState:
  283. r"""
  284. A class for beam scorers to track its progress through a list of constraints.
  285. Args:
  286. constraints (`list[Constraint]`):
  287. A list of [`Constraint`] objects that must be fulfilled by the beam scorer.
  288. """
  289. def __init__(self, constraints: list[Constraint]):
  290. self.constraints = constraints
  291. # max # of steps required to fulfill a given constraint
  292. self.max_seqlen = max([c.seqlen for c in constraints])
  293. self.n_constraints = len(constraints)
  294. self.completed = False
  295. self.init_state()
  296. def init_state(self):
  297. self.complete_constraints = []
  298. self.inprogress_constraint = None
  299. self.pending_constraints = [constraint.copy(stateful=False) for constraint in self.constraints]
  300. def get_bank(self):
  301. add = 0
  302. if self.inprogress_constraint:
  303. # extra points for having a constraint mid-fulfilled
  304. add += self.max_seqlen - self.inprogress_constraint.remaining()
  305. return (len(self.complete_constraints) * self.max_seqlen) + add
  306. def advance(self):
  307. """The list of tokens to generate such that we can make progress.
  308. By "list" we don't mean the list of token that will fully fulfill a constraint.
  309. Given constraints `c_i = {t_ij | j == # of tokens}`, If we're not in the middle of progressing through a
  310. specific constraint `c_i`, we return:
  311. `[t_k1 for k in indices of unfulfilled constraints]`
  312. If we are in the middle of a constraint, then we return:
  313. `[t_ij]`, where `i` is the index of the inprogress constraint, `j` is the next step for the constraint.
  314. Though we don't care which constraint is fulfilled first, if we are in the progress of fulfilling a constraint,
  315. that's the only one we'll return.
  316. """
  317. token_list = []
  318. if self.inprogress_constraint is None:
  319. for constraint in self.pending_constraints: # "pending" == "unfulfilled yet"
  320. advance = constraint.advance()
  321. if isinstance(advance, int):
  322. token_list.append(advance)
  323. elif isinstance(advance, list):
  324. token_list.extend(advance)
  325. else:
  326. advance = self.inprogress_constraint.advance()
  327. if isinstance(advance, int):
  328. token_list.append(advance)
  329. elif isinstance(advance, list):
  330. token_list.extend(advance)
  331. if len(token_list) == 0:
  332. return None
  333. else:
  334. return token_list
  335. def reset(self, token_ids: Optional[list[int]]):
  336. """
  337. token_ids: the tokens generated thus far to reset the state of the progress through constraints.
  338. """
  339. self.init_state()
  340. if token_ids is not None:
  341. for token in token_ids:
  342. # completes or steps **one** constraint
  343. complete, stepped = self.add(token)
  344. # the entire list of constraints are fulfilled
  345. if self.completed:
  346. break
  347. def add(self, token_id: int):
  348. if not isinstance(token_id, int):
  349. raise TypeError(f"`token_id` should be an `int`, but is `{token_id}`.")
  350. complete, stepped = False, False
  351. if self.completed:
  352. complete = True
  353. stepped = False
  354. return complete, stepped
  355. if self.inprogress_constraint is not None:
  356. # In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current
  357. # job, simply update the state
  358. stepped, complete, reset = self.inprogress_constraint.update(token_id)
  359. if reset:
  360. # 1. If the next token breaks the progress, then we must restart.
  361. # e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books".
  362. # But that doesn't mean we self.init_state(), since we only reset the state for this particular
  363. # constraint, not the full list of constraints.
  364. self.pending_constraints.append(self.inprogress_constraint.copy(stateful=False))
  365. self.inprogress_constraint = None
  366. if complete:
  367. # 2. If the next token completes the constraint, move it to completed list, set
  368. # inprogress to None. If there are no pending constraints either, then this full list of constraints
  369. # is complete.
  370. self.complete_constraints.append(self.inprogress_constraint)
  371. self.inprogress_constraint = None
  372. if len(self.pending_constraints) == 0:
  373. # we're done!
  374. self.completed = True
  375. else:
  376. # Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list
  377. # of constraints?
  378. for cidx, pending_constraint in enumerate(self.pending_constraints):
  379. if pending_constraint.does_advance(token_id):
  380. stepped, complete, reset = pending_constraint.update(token_id)
  381. if not stepped:
  382. raise Exception(
  383. "`constraint.update(token_id)` is not yielding incremental progress, "
  384. "even though `constraint.does_advance(token_id)` is true."
  385. )
  386. if complete:
  387. self.complete_constraints.append(pending_constraint)
  388. self.inprogress_constraint = None
  389. if not complete and stepped:
  390. self.inprogress_constraint = pending_constraint
  391. if complete or stepped:
  392. # If we made any progress at all, then it's at least not a "pending constraint".
  393. self.pending_constraints = (
  394. self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :]
  395. )
  396. if len(self.pending_constraints) == 0 and self.inprogress_constraint is None:
  397. # If there's no longer any pending after this and no inprogress either, then we must be
  398. # complete.
  399. self.completed = True
  400. break # prevent accidentally stepping through multiple constraints with just one token.
  401. return complete, stepped
  402. def copy(self, stateful=True):
  403. new_state = ConstraintListState(self.constraints) # we actually never though self.constraints objects
  404. # throughout this process. So it's at initialization state.
  405. if stateful:
  406. new_state.complete_constraints = [
  407. constraint.copy(stateful=True) for constraint in self.complete_constraints
  408. ]
  409. if self.inprogress_constraint is not None:
  410. new_state.inprogress_constraint = self.inprogress_constraint.copy(stateful=True)
  411. new_state.pending_constraints = [constraint.copy() for constraint in self.pending_constraints]
  412. return new_state