outlines_logits_processors.py 6.7 KB

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