-
Notifications
You must be signed in to change notification settings - Fork 12.2k
support loading vocab from fast tokenizer config in convert.py #3633
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
Changes from 1 commit
Commits
Show all changes
32 commits
Select commit
Hold shift + click to select a range
f7e377d
Add HFVocab into convert.py
strutive07 b0e00cb
Update convert.py
strutive07 f888d2e
Update convert.py
strutive07 ea9f35f
add bytes_to_unicode function
strutive07 c7b636e
change add_meta_vocab fucntion
strutive07 6ec856b
remove debug code
strutive07 1f16e5f
remove byte_encoder
strutive07 e876aec
Add newline between classes
strutive07 1778450
Check tokenizer.json when tokenizer.model is not exist.
strutive07 a5b26b6
Move transformers dependency to local code
strutive07 5a1f178
Add error context with 'raise from'
strutive07 89611cb
Add fast tokenizer option to BpeVocab
strutive07 97f690a
Merge branch 'master' into convert_hf_vocab
strutive07 e715442
Update convert.py
strutive07 d54764d
Add VocabLoader and remove *Vocab class
strutive07 e19b780
Add transformers dependency
strutive07 28f09be
remove added tokens and check newline token to decide spm or bpe
strutive07 4adb8b9
Update convert.py
strutive07 13f0701
Add special token type
strutive07 f37a7d7
Update convert.py
strutive07 9f4dc23
Update convert.py
strutive07 dcf372e
Update convert.py
strutive07 cc1f3fc
Fix typo in convert.py
strutive07 026eb7c
Fix when params.n_vocab < tokenizer vocab size
strutive07 2e263ca
update vocab class
strutive07 5ac1949
change funtion name
strutive07 74d80a8
Merge branch 'master' into convert_hf_vocab
strutive07 61edd1b
Remove unused variable/functions, add types to class variable and met…
strutive07 1f5357c
fix flake8 warnings
strutive07 8fabb01
code style cleanup
cebtenzzre c3b1c12
make mypy happy
cebtenzzre 35e95b6
change exception
strutive07 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
Next
Next commit
Add HFVocab into convert.py
- Loading branch information
commit f7e377d62f20d92a05b4c95647efeff4c2976c18
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 |
---|---|---|
|
@@ -414,7 +414,54 @@ def all_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]: | |
def __repr__(self) -> str: | ||
return f"<SentencePieceVocab with {self.vocab_size_base} base tokens and {len(self.added_tokens_list)} added tokens>" | ||
|
||
Vocab: TypeAlias = 'BpeVocab | SentencePieceVocab' | ||
class HFVocab: | ||
def __init__(self, fname_tokenizer: Path, fname_added_tokens: Path | None) -> None: | ||
self.tokenizer = AutoTokenizer.from_pretrained(str(fname_tokenizer)) | ||
|
||
added_tokens: dict[str, int] | ||
if fname_added_tokens is not None: | ||
added_tokens = json.load(open(fname_added_tokens, encoding="utf-8")) | ||
else: | ||
added_tokens = {} | ||
|
||
vocab_size: int = self.tokenizer.vocab_size | ||
|
||
expected_ids = list(range(vocab_size, vocab_size + len(added_tokens))) | ||
actual_ids = sorted(added_tokens.values()) | ||
if expected_ids != actual_ids: | ||
raise Exception(f"Expected added token IDs to be sequential and start at {len(added_tokens)}; got {actual_ids}") | ||
|
||
items = sorted(added_tokens.items(), key=lambda text_idx: text_idx[1]) | ||
self.added_tokens_list = [text for (text, idx) in items] | ||
self.vocab_size_base: int = vocab_size | ||
self.vocab_size: int = self.vocab_size_base + len(self.added_tokens_list) | ||
self.fname_tokenizer = fname_tokenizer | ||
self.fname_added_tokens = fname_added_tokens | ||
|
||
def hf_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]: | ||
tokenizer = self.tokenizer | ||
reverse_vocab = {id: encoded_tok for encoded_tok, id in tokenizer.vocab.items()} | ||
byte_encoder = bytes_to_unicode() | ||
byte_decoder = {v: k for k, v in byte_encoder.items()} | ||
print(len(byte_decoder), byte_decoder) | ||
|
||
for i in range(tokenizer.vocab_size): | ||
text = reverse_vocab[i].encode("utf-8") | ||
yield text, 0.0, gguf.TokenType.NORMAL | ||
|
||
def added_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]: | ||
for text in self.added_tokens_list: | ||
score = -1000.0 | ||
yield text.encode("utf-8"), score, gguf.TokenType.USER_DEFINED | ||
|
||
def all_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]: | ||
yield from self.hf_tokens() | ||
yield from self.added_tokens() | ||
|
||
def __repr__(self) -> str: | ||
return f"<HFVocab with {self.vocab_size_base} base tokens and {len(self.added_tokens_list)} added tokens>" | ||
|
||
Vocab: TypeAlias = 'BpeVocab | SentencePieceVocab | HFVocab' | ||
|
||
# | ||
# data loading | ||
|
@@ -1084,6 +1131,8 @@ def load_vocab(path: Path, vocabtype: str | None) -> Vocab: | |
return BpeVocab(path, added_tokens_path if added_tokens_path.exists() else None) | ||
elif vocabtype == "spm": | ||
return SentencePieceVocab(path, added_tokens_path if added_tokens_path.exists() else None) | ||
elif vocabtype == "hf": | ||
return HFVocab(path, added_tokens_path if added_tokens_path.exists() else None) | ||
else: | ||
raise ValueError(f"Unsupported vocabulary type {vocabtype}") | ||
|
||
|
@@ -1120,7 +1169,7 @@ def main(args_in: list[str] | None = None) -> None: | |
parser.add_argument("--vocab-dir", type=Path, help="directory containing tokenizer.model, if separate from model file") | ||
parser.add_argument("--outfile", type=Path, help="path to write to; default: based on input") | ||
parser.add_argument("model", type=Path, help="directory containing model file, or model file itself (*.pth, *.pt, *.bin)") | ||
parser.add_argument("--vocabtype", choices=["spm", "bpe"], help="vocab format (default: spm)", default="spm") | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Since you removed this argument in this PR, I think you better update the README.md file as well. |
||
parser.add_argument("--vocabtype", choices=["spm", "bpe", "hf"], help="vocab format (default: spm)", default="spm") | ||
parser.add_argument("--ctx", type=int, help="model training context (default: based on input)") | ||
parser.add_argument("--concurrency", type=int, help=f"concurrency used for conversion (default: {DEFAULT_CONCURRENCY})", default = DEFAULT_CONCURRENCY) | ||
args = parser.parse_args(args_in) | ||
|
@@ -1162,7 +1211,7 @@ def main(args_in: list[str] | None = None) -> None: | |
assert args.outfile, "need --outfile if using --vocab-only" | ||
# FIXME: Try to respect vocab_dir somehow? | ||
vocab = load_vocab(args.vocab_dir or args.model, args.vocabtype) | ||
special_vocab = gguf.SpecialVocab(model_plus.paths[0].parent, load_merges = args.vocabtype == 'bpe') | ||
special_vocab = gguf.SpecialVocab(model_plus.paths[0].parent, load_merges = args.vocabtype in ('bpe', 'hf')) | ||
outfile = args.outfile | ||
OutputFile.write_vocab_only(outfile, params, vocab, special_vocab) | ||
print(f"Wrote {outfile}") | ||
|
@@ -1174,7 +1223,7 @@ def main(args_in: list[str] | None = None) -> None: | |
vocab_dir = args.vocab_dir if args.vocab_dir else model_plus.paths[0].parent | ||
vocab = load_vocab(vocab_dir, args.vocabtype) | ||
# FIXME: Try to respect vocab_dir somehow? | ||
special_vocab = gguf.SpecialVocab(model_plus.paths[0].parent, load_merges = args.vocabtype == 'bpe') | ||
special_vocab = gguf.SpecialVocab(model_plus.paths[0].parent, load_merges = args.vocabtype in ('bpe', 'hf')) | ||
|
||
model = model_plus.model | ||
model = convert_model_names(model, params) | ||
|
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.
Can you help me understand why you removed *.safetensors?
Thanks!
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.
The model files are automatically discovered. The model file names are arbitrary, some are split and others are not. The model files are dynamically "lazy" loaded to save memory as a result.
https://github.com/ggerganov/llama.cpp/blob/master/convert.py#L1348
The vocab can be set manually though.
https://github.com/ggerganov/llama.cpp/blob/master/convert.py#L1461
Not sure if that answers your question.