-
Notifications
You must be signed in to change notification settings - Fork 569
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Integrate with llama.cpp using logit processors
- Loading branch information
Showing
10 changed files
with
307 additions
and
224 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,3 +4,4 @@ __pycache__ | |
docs/build | ||
.coverage | ||
.idea/ | ||
*.gguf |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
from enum import Enum | ||
|
||
from llama_cpp import Llama, LogitsProcessorList | ||
from pydantic import BaseModel, constr | ||
|
||
from outlines.models.llamacpp import LlamaCppTokenizer, LlamaJSONLogitsProcessor | ||
|
||
|
||
class Weapon(str, Enum): | ||
sword = "sword" | ||
axe = "axe" | ||
mace = "mace" | ||
spear = "spear" | ||
bow = "bow" | ||
crossbow = "crossbow" | ||
|
||
|
||
class Armor(str, Enum): | ||
leather = "leather" | ||
chainmail = "chainmail" | ||
plate = "plate" | ||
|
||
|
||
class Character(BaseModel): | ||
name: constr(max_length=10) | ||
age: int | ||
armor: Armor | ||
weapon: Weapon | ||
strength: int | ||
|
||
|
||
if __name__ == "__main__": | ||
llama = Llama("./phi-2.Q4_K_M.gguf") | ||
tokenizer = LlamaCppTokenizer(llama) | ||
|
||
prompt = "Instruct: You are a leading role play gamer. You have seen thousands of different characters and their attributes.\nPlease return a JSON object with common attributes of an RPG character. Give me a character description\nOutput:" | ||
|
||
logits_processor = LlamaJSONLogitsProcessor(Character, tokenizer) | ||
|
||
json_str = llama.create_completion( | ||
prompt, | ||
top_k=40, | ||
top_p=0.95, | ||
temperature=0.7, | ||
max_tokens=100, | ||
logits_processor=LogitsProcessorList([logits_processor]), | ||
)["choices"][0]["text"] | ||
|
||
print(json_str) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,100 @@ | ||
import json | ||
import math | ||
from typing import Union | ||
|
||
import numpy as np | ||
import torch | ||
from numpy.typing import NDArray | ||
|
||
from outlines.fsm.fsm import CFGFSM, FSM, FSMState, RegexFSM | ||
from outlines.fsm.json_schema import build_regex_from_object | ||
from outlines.models.tokenizer import Tokenizer | ||
|
||
|
||
class LogitsProcessor: | ||
def __init__(self, tokenizer: Tokenizer, fsm: FSM): | ||
"""Super class for logit processors. | ||
Parameters | ||
---------- | ||
tokenizer | ||
An instance of `Tokenizer` | ||
""" | ||
self.tokenizer = tokenizer | ||
self.fsm_state: FSMState = None # type: ignore | ||
self.fsm: FSM = fsm | ||
|
||
def __call__( | ||
self, input_ids: NDArray[np.int64], scores: NDArray[np.float32] | ||
) -> NDArray[np.float32]: | ||
"""Use the FSM to bias the logits before sampling the next token.""" | ||
if self.fsm is None: | ||
raise NotImplementedError() | ||
|
||
if self.fsm_state is None: | ||
self.fsm_state = FSMState(0) | ||
else: | ||
last_token = input_ids[-1] | ||
self.fsm_state = self.fsm.next_state(self.fsm_state, last_token) | ||
|
||
allowed_tokens = self.fsm.allowed_token_ids(self.fsm_state) | ||
|
||
mask = torch.full((scores.shape[-1],), -math.inf, device="cpu").numpy() | ||
mask[allowed_tokens] = 0 | ||
biased_scores = scores + mask | ||
|
||
biased_scores[self.tokenizer.eos_token_id] = 0 | ||
|
||
return biased_scores | ||
|
||
|
||
class RegexLogitsProcessor(LogitsProcessor): | ||
def __init__(self, regex_string: str, tokenizer: Tokenizer): | ||
"""Compile the FSM that drives the regex-guided generation. | ||
Parameters | ||
---------- | ||
regex_string | ||
A string that represents a regular expression | ||
tokenizer | ||
An instance of `Tokenizer` | ||
""" | ||
fsm = RegexFSM(regex_string, tokenizer) | ||
super().__init__(tokenizer, fsm) | ||
|
||
|
||
class JSONLogitsProcessor(RegexLogitsProcessor): | ||
def __init__(self, schema: Union[str, dict], tokenizer: Tokenizer): | ||
"""Compile the FSM that drives the JSON-guided generation. | ||
Parameters | ||
---------- | ||
schema | ||
A JSON schema that encodes the structure we want the model to generate | ||
tokenizer | ||
An instance of `Tokenizer` | ||
""" | ||
# TODO: Why is this needed? We are using regexes | ||
if isinstance(schema, dict): | ||
schema = json.dumps(schema) | ||
regex_string = build_regex_from_object(schema) | ||
super().__init__(regex_string, tokenizer) | ||
|
||
|
||
class CFGLogitsProcessor(LogitsProcessor): | ||
def __init__(self, cfg_str: str, tokenizer: Tokenizer): | ||
"""Compile the FSM that drives the CFG-guided generation. | ||
Parameters | ||
---------- | ||
cfg_str | ||
A string that represents a grammar | ||
tokenizer | ||
An instance of `Tokenizer` | ||
""" | ||
fsm = CFGFSM(cfg_str, tokenizer) | ||
super().__init__(tokenizer, fsm) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.