outlines_logits_processors.py 6.0 KB

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