outlines_logits_processors.py 4.6 KB

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