outlines_logits_processors.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. # Copyright 2024- the Outlines developers
  2. # This file is adapted from
  3. # https://github.com/outlines-dev/outlines/blob/main/outlines/serve/vllm.py
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. # http://www.apache.org/licenses/LICENSE-2.0
  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 copy
  15. import json
  16. import math
  17. from collections import defaultdict
  18. from functools import lru_cache
  19. from typing import Callable, DefaultDict, Dict, List, Union
  20. import torch
  21. from outlines.caching import cache
  22. from outlines.fsm.guide import CFGGuide, Generate, Guide, RegexGuide, Write
  23. from outlines.fsm.json_schema import build_regex_from_schema
  24. from pydantic import BaseModel
  25. from transformers import PreTrainedTokenizerBase
  26. class BaseLogitsProcessor:
  27. def __init__(self, guide: Guide):
  28. self._guide: Guide = guide
  29. self._fsm_state: DefaultDict[int, int] = defaultdict(int)
  30. def __call__(self, input_ids: List[int],
  31. scores: torch.Tensor) -> torch.Tensor:
  32. """Use the FSM to bias the logits before sampling the next token."""
  33. seq_id = hash(tuple(input_ids))
  34. if len(input_ids) > 0:
  35. last_token = input_ids[-1]
  36. last_seq_id = hash(tuple(input_ids[:-1]))
  37. self._fsm_state[seq_id] = self._guide.get_next_state(
  38. state=self._fsm_state[last_seq_id], token_id=last_token)
  39. instruction = self._guide.get_next_instruction(
  40. state=self._fsm_state[seq_id])
  41. if type(instruction) == Generate:
  42. allowed_tokens = instruction.tokens
  43. elif type(instruction) == Write:
  44. # TODO: support fast forward tokens
  45. allowed_tokens = [instruction.tokens[0]]
  46. else:
  47. raise TypeError(
  48. f"Unsupported instruction type {type(instruction)}")
  49. mask = torch.full((scores.shape[-1], ),
  50. -math.inf,
  51. device=scores.device)
  52. mask[allowed_tokens] = 0
  53. scores.add_(mask)
  54. return scores
  55. class RegexLogitsProcessor(BaseLogitsProcessor):
  56. @classmethod
  57. @cache()
  58. def _get_guide(cls, regex_string: str,
  59. tokenizer: PreTrainedTokenizerBase) -> Guide:
  60. tokenizer = _adapt_tokenizer(tokenizer)
  61. return RegexGuide(regex_string, tokenizer)
  62. def __init__(self, regex_string: str, tokenizer: PreTrainedTokenizerBase):
  63. """Compile the FSM that drives the regex-structured generation.
  64. Parameters
  65. ----------
  66. regex_string
  67. A string that represents a regular expression
  68. tokenizer
  69. The model's tokenizer
  70. """
  71. super().__init__(
  72. RegexLogitsProcessor._get_guide(regex_string, tokenizer))
  73. class JSONLogitsProcessor(RegexLogitsProcessor):
  74. def __init__(self, schema: Union[str, Dict, BaseModel],
  75. tokenizer: PreTrainedTokenizerBase,
  76. whitespace_pattern: Union[str, None]):
  77. """Compile the FSM that drives the JSON-guided generation.
  78. Parameters
  79. ----------
  80. schema
  81. A JSON schema that encodes the structure we want the model to
  82. generate
  83. tokenizer
  84. The model's tokenizer
  85. whitespace_pattern
  86. Pattern to use for JSON syntactic whitespace (doesn't impact
  87. string literals)
  88. Example: allow only a single space or newline with
  89. `whitespace_pattern=r"[\n ]?"`
  90. """
  91. if isinstance(schema, type(BaseModel)):
  92. schema_str = json.dumps(schema.model_json_schema())
  93. elif isinstance(schema, Dict):
  94. schema_str = json.dumps(schema)
  95. elif isinstance(schema, str):
  96. schema_str = schema
  97. else:
  98. raise ValueError(
  99. f"Cannot parse schema {schema}. The schema must be either "
  100. f"a Pydantic object, a dictionary or a string that contains "
  101. f"the JSON Schema specification")
  102. regex_string = build_regex_from_schema(schema_str, whitespace_pattern)
  103. super().__init__(regex_string, tokenizer)
  104. class CFGLogitsProcessor(BaseLogitsProcessor):
  105. @classmethod
  106. @cache()
  107. def _get_guide(cls, cfg: str, tokenizer: PreTrainedTokenizerBase) -> Guide:
  108. tokenizer = _adapt_tokenizer(tokenizer)
  109. return CFGGuide(cfg, tokenizer)
  110. def __init__(self, cfg: str, tokenizer: PreTrainedTokenizerBase):
  111. """Compile the FSM that drives the context free grammar generation.
  112. Parameters
  113. ----------
  114. cfg
  115. A string that represents a context-free grammar
  116. tokenizer
  117. The model's tokenizer
  118. """
  119. super().__init__(CFGLogitsProcessor._get_guide(cfg, tokenizer))
  120. self._guide = self._guide.copy()
  121. @lru_cache(maxsize=32)
  122. def _adapt_tokenizer(tokenizer: PreTrainedTokenizerBase):
  123. """Adapt Aphrodite's tokenizer to use to compile the FSM.
  124. The API of Outlines tokenizers is slightly different to that of
  125. `transformers`. The decoder of outlines, returns a list whereas
  126. the decode of Aphrodite returns an str. To sync the Aphrodite decoder with
  127. outlines internal api, the decoder should be adapted. In addition
  128. we need to handle the missing spaces to Llama's tokenizer to be
  129. able to compile FSMs for this model.
  130. """
  131. if getattr(tokenizer, "_outlines_adapted", False):
  132. return tokenizer
  133. tokenizer = copy.deepcopy(tokenizer)
  134. tokenizer.vocabulary = tokenizer.get_vocab()
  135. tokenizer.special_tokens = set(tokenizer.all_special_tokens)
  136. def convert_token_to_string(token: str) -> str:
  137. from transformers.file_utils import SPIECE_UNDERLINE
  138. string = tokenizer.convert_tokens_to_string([token])
  139. # A hack to handle missing spaces to HF's Llama tokenizers
  140. if token.startswith(SPIECE_UNDERLINE) or token == "<0x20>":
  141. return " " + string
  142. return string
  143. def change_decoder(
  144. decoder: Callable[[List[int]],
  145. str]) -> Callable[[List[int]], List[str]]:
  146. """Sync Aphrodite's decoder with the outlines by returning list."""
  147. def new_decoder(inp_tokens: List[int]) -> List[str]:
  148. return [decoder(inp_tokens)]
  149. return new_decoder
  150. tokenizer.convert_token_to_string = convert_token_to_string
  151. tokenizer.decode = change_decoder(tokenizer.decode)
  152. setattr(tokenizer, "_outlines_adapted", True) # noqa: B010
  153. return tokenizer