Skip to content

fix: tokenization of special characters: #850

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions llama_cpp/llama.py
Original file line number Diff line number Diff line change
Expand Up @@ -856,7 +856,7 @@ def create_embedding(
data: List[EmbeddingData] = []
total_tokens = 0
for index, input in enumerate(inputs):
tokens = self.tokenize(input.encode("utf-8"))
tokens = self.tokenize(input.encode("utf-8"), special=True)
self.reset()
self.eval(tokens)
n_tokens = len(tokens)
Expand Down Expand Up @@ -927,7 +927,7 @@ def _create_completion(
completion_tokens: List[int] = []
# Add blank space to start of prompt to match OG llama tokenizer
prompt_tokens: List[int] = (
self.tokenize(prompt.encode("utf-8"))
self.tokenize(prompt.encode("utf-8"), special=True)
if prompt != ""
else [self.token_bos()]
)
Expand Down Expand Up @@ -1823,7 +1823,7 @@ def __init__(self, llama: Llama):

def encode(self, text: str, add_bos: bool = True) -> List[int]:
return self.llama.tokenize(
text.encode("utf-8", errors="ignore"), add_bos=add_bos
text.encode("utf-8", errors="ignore"), add_bos=add_bos, special=True
)

def decode(self, tokens: List[int]) -> str:
Expand Down
2 changes: 1 addition & 1 deletion llama_cpp/server/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -589,7 +589,7 @@ def make_logit_bias_processor(
elif logit_bias_type == "tokens":
for token, score in logit_bias.items():
token = token.encode("utf-8")
for input_id in llama.tokenize(token, add_bos=False):
for input_id in llama.tokenize(token, add_bos=False, special=True):
to_bias[input_id] = score

def logit_bias_processor(
Expand Down
Empty file added test.py
Empty file.
9 changes: 9 additions & 0 deletions tests/test_llama.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,15 @@ def test_llama_cpp_tokenization():
detokenized = llama.detokenize(tokens)
assert detokenized != text

text = b"Hello World</s>"
tokens = llama.tokenize(text)
assert tokens[-1] != llama.token_eos()
assert tokens == [1, 15043, 2787, 829, 29879, 29958]

tokens = llama.tokenize(text, special=True)
assert tokens[-1] == llama.token_eos()
assert tokens == [1, 10994, 2787, 2]


def test_llama_patch(monkeypatch):
llama = llama_cpp.Llama(model_path=MODEL, vocab_only=True)
Expand Down