Skip to content

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 32 commits into from
Dec 14, 2023
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 Oct 15, 2023
b0e00cb
Update convert.py
strutive07 Oct 15, 2023
f888d2e
Update convert.py
strutive07 Oct 15, 2023
ea9f35f
add bytes_to_unicode function
strutive07 Oct 15, 2023
c7b636e
change add_meta_vocab fucntion
strutive07 Oct 15, 2023
6ec856b
remove debug code
strutive07 Oct 15, 2023
1f16e5f
remove byte_encoder
strutive07 Oct 15, 2023
e876aec
Add newline between classes
strutive07 Oct 15, 2023
1778450
Check tokenizer.json when tokenizer.model is not exist.
strutive07 Oct 15, 2023
a5b26b6
Move transformers dependency to local code
strutive07 Oct 18, 2023
5a1f178
Add error context with 'raise from'
strutive07 Oct 18, 2023
89611cb
Add fast tokenizer option to BpeVocab
strutive07 Oct 23, 2023
97f690a
Merge branch 'master' into convert_hf_vocab
strutive07 Oct 29, 2023
e715442
Update convert.py
strutive07 Oct 29, 2023
d54764d
Add VocabLoader and remove *Vocab class
strutive07 Oct 30, 2023
e19b780
Add transformers dependency
strutive07 Oct 30, 2023
28f09be
remove added tokens and check newline token to decide spm or bpe
strutive07 Nov 5, 2023
4adb8b9
Update convert.py
strutive07 Nov 5, 2023
13f0701
Add special token type
strutive07 Nov 5, 2023
f37a7d7
Update convert.py
strutive07 Nov 11, 2023
9f4dc23
Update convert.py
strutive07 Nov 11, 2023
dcf372e
Update convert.py
strutive07 Nov 11, 2023
cc1f3fc
Fix typo in convert.py
strutive07 Nov 15, 2023
026eb7c
Fix when params.n_vocab < tokenizer vocab size
strutive07 Nov 18, 2023
2e263ca
update vocab class
strutive07 Nov 19, 2023
5ac1949
change funtion name
strutive07 Nov 22, 2023
74d80a8
Merge branch 'master' into convert_hf_vocab
strutive07 Nov 22, 2023
61edd1b
Remove unused variable/functions, add types to class variable and met…
strutive07 Nov 28, 2023
1f5357c
fix flake8 warnings
strutive07 Nov 28, 2023
8fabb01
code style cleanup
cebtenzzre Dec 13, 2023
c3b1c12
make mypy happy
cebtenzzre Dec 13, 2023
35e95b6
change exception
strutive07 Dec 13, 2023
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
Next Next commit
Add HFVocab into convert.py
  • Loading branch information
strutive07 authored Oct 15, 2023
commit f7e377d62f20d92a05b4c95647efeff4c2976c18
57 changes: 53 additions & 4 deletions convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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}")

Expand Down Expand Up @@ -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)")

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!

Copy link
Contributor

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.

parser.add_argument("--vocabtype", choices=["spm", "bpe"], help="vocab format (default: spm)", default="spm")

Choose a reason for hiding this comment

The 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)
Expand Down Expand Up @@ -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}")
Expand All @@ -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)
Expand Down