-
Notifications
You must be signed in to change notification settings - Fork 250
Tokenizers tokenizer #1261
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
Tokenizers tokenizer #1261
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
d8443a7
feat(tokenizer): Add an abstract base class for additional tokenizer …
gabe-l-hart 2483486
feat(tokenizers): Add a python impl of the Tokenizer interface using …
gabe-l-hart 5c41015
feat(builder): Add support for using the TokenizersTokenizer in builder
gabe-l-hart 27d2708
feat(tokenizers): Add and plumb the option to use the "tokenizers" to…
gabe-l-hart 9d9a4a7
fix(tokenizers): Fix how bos/eos tokens are parsed from tokenizers (lib)
gabe-l-hart 4a20f69
fix(hf_tokenizer): Rename to HFTokenizer and corresponding flags
gabe-l-hart File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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,32 @@ | ||
# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
# All rights reserved. | ||
# | ||
# This source code is licensed under the BSD-style license found in the | ||
# LICENSE file in the root directory of this source tree. | ||
""" | ||
Abstract base class for all tokenizer classes in python matching c++ interface. | ||
""" | ||
|
||
# Standard | ||
from abc import ABC, abstractmethod | ||
from typing import List | ||
|
||
|
||
class TokenizerBase(ABC): | ||
__doc__ = __doc__ | ||
|
||
@abstractmethod | ||
def encode(self, s: str, *, bos: bool = False, eos: bool = False) -> List[int]: | ||
"""Encode the given string and optionally include bos/eos tokens""" | ||
|
||
@abstractmethod | ||
def decode(self, ids: List[int]) -> str: | ||
"""Decode the given token ids into a string""" | ||
|
||
@abstractmethod | ||
def bos_id(self) -> int: | ||
"""The id of the begin-of-string token""" | ||
|
||
@abstractmethod | ||
def eos_id(self) -> int: | ||
"""The id of the end-of-string token""" |
This file contains hidden or 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,92 @@ | ||
# Copyright (c) Meta Platforms, Inc. and affiliates. | ||
# All rights reserved. | ||
# | ||
# This source code is licensed under the BSD-style license found in the | ||
# LICENSE file in the root directory of this source tree. | ||
|
||
# Standard | ||
from typing import List, Optional | ||
import json | ||
import os | ||
|
||
# Third Party | ||
from tokenizers import Tokenizer | ||
|
||
# Local | ||
from .base import TokenizerBase | ||
|
||
|
||
class HFTokenizer(TokenizerBase): | ||
""" | ||
Wrapper around the Huggingface `tokenizers` library for API compatibility | ||
""" | ||
|
||
def __init__(self, file_path: str): | ||
# If the path is a directory, look for "tokenizer.json" which is | ||
# standard for transformers checkpoints and also look for the | ||
# "tokenizer_config.json" file to parse eos/bos tokens | ||
if os.path.isdir(file_path): | ||
tokenizer_path = os.path.join(file_path, "tokenizer.json") | ||
tokenizer_config_path = os.path.join(file_path, "tokenizer_config.json") | ||
else: | ||
tokenizer_path = file_path | ||
tokenizer_config_path = os.path.join(os.path.dirname(file_path), "tokenizer_config.json") | ||
if not os.path.isfile(tokenizer_path): | ||
tokenizer_config_path = None | ||
|
||
# Load the tokenizer itself | ||
self._tokenizer = Tokenizer.from_file(tokenizer_path) | ||
|
||
# If available, parse bos/eos tokens from the tokenizer config | ||
self._bos_id, self._eos_id = None, None | ||
if tokenizer_config_path is not None: | ||
with open(tokenizer_config_path, "r") as handle: | ||
tok_config = json.load(handle) | ||
bos_token = tok_config.get("bos_token") | ||
eos_token = tok_config.get("eos_token") | ||
if bos_token is not None: | ||
self._bos_id = self._tokenizer.token_to_id(bos_token) | ||
if eos_token is not None: | ||
self._eos_id = self._tokenizer.token_to_id(eos_token) | ||
|
||
# If no eos/bos tokens found, go looking for them! | ||
if None in [self._bos_id, self._eos_id]: | ||
tok_content = json.loads(self._tokenizer.to_str()) | ||
if self._bos_id is None: | ||
self._bos_id = self._look_for_special_token(tok_content, ["begin", "text"]) | ||
if self._eos_id is None: | ||
self._eos_id = self._look_for_special_token(tok_content, ["end", "text"]) | ||
|
||
assert None not in [self._bos_id, self._eos_id], "Unable to find an BOS/EOS tokens" | ||
|
||
@staticmethod | ||
def _look_for_special_token(added_tokens: dict, search_strs: List[str]) -> Optional[int]: | ||
candidate_toks = added_tokens | ||
for search_str in search_strs: | ||
candidate_toks = [ | ||
tok for tok in candidate_toks | ||
if tok["special"] and search_str in tok["content"] | ||
] | ||
if len(candidate_toks) == 1: | ||
return candidate_toks[0]["id"] | ||
|
||
def encode( | ||
self, | ||
s: str, | ||
*, | ||
bos: bool = False, | ||
eos: bool = False, | ||
) -> List[int]: | ||
res = self._tokenizer.encode(s, add_special_tokens=bos).ids | ||
if eos and (not res or res[-1] != self._eos_token): | ||
res.append(self._eos_token) | ||
return res | ||
|
||
def decode(self, ids: List[int]) -> str: | ||
return self._tokenizer.decode(ids) | ||
|
||
def bos_id(self) -> int: | ||
return self._bos_id | ||
|
||
def eos_id(self) -> int: | ||
return self._eos_id |
This file contains hidden or 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 hidden or 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 hidden or 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.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Any reason not to use the full path?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Heh, no, I have tended towards relative imports for local (the mental equivalent of
#inlclude "foo.h"
vs#include <string>
for local files vs standard/third party). Definitely no strong preference though! I'd much rather stay consistent with the rest of the project.