Skip to content

Commit 857c8f1

Browse files
fix: token_dtype_code assigns uint16 to vocab sizes needing uint64
Signed-off-by: andrewwhitecdw <andrewwhitecdw@users.noreply.github.com>
1 parent 2eed215 commit 857c8f1

2 files changed

Lines changed: 33 additions & 3 deletions

File tree

‎src/megatron/bridge/training/setup.py‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -335,9 +335,7 @@ def setup(
335335
if hasattr(cfg.dataset, "token_dtype_code") and cfg.dataset.token_dtype_code is None:
336336
vocab_size = getattr(tokenizer, "vocab_size", None)
337337
if vocab_size is not None:
338-
import numpy
339-
340-
cfg.dataset.token_dtype_code = 4 if vocab_size > numpy.iinfo(numpy.uint16).max + 1 else 8
338+
cfg.dataset.token_dtype_code = _get_token_dtype_code(vocab_size)
341339

342340
if cfg.train.num_epochs is not None:
343341
if should_fire(callback_manager, "on_data_init_start"):
@@ -781,6 +779,17 @@ def _validate_and_set_vocab_size(
781779
return model_vocab_size, False
782780

783781

782+
def _get_token_dtype_code(vocab_size: int) -> int:
783+
"""Return the numpy dtype code for token IDs that can hold `vocab_size` tokens.
784+
785+
uint16 (code 4) is used when all token ids (0..vocab_size-1) fit in uint16,
786+
otherwise uint64 (code 8) is used.
787+
"""
788+
import numpy as np
789+
790+
return 4 if vocab_size <= np.iinfo(np.uint16).max + 1 else 8
791+
792+
784793
def maybe_log_and_save_config(cfg: ConfigContainer) -> None:
785794
"""Save configuration to disk and log non-default values on rank 0.
786795
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import numpy as np
2+
3+
from megatron.bridge.training.setup import _get_token_dtype_code
4+
5+
6+
def test_get_token_dtype_code_uint16():
7+
"""Vocab sizes up to 65536 fit in uint16 (numpy code 4)."""
8+
assert _get_token_dtype_code(1) == np.dtype(np.uint16).num
9+
assert _get_token_dtype_code(65535) == np.dtype(np.uint16).num
10+
assert _get_token_dtype_code(65536) == np.dtype(np.uint16).num
11+
12+
13+
def test_get_token_dtype_code_uint64():
14+
"""Vocab sizes larger than 65536 require uint64 (numpy code 8)."""
15+
assert _get_token_dtype_code(65537) == np.dtype(np.uint64).num
16+
assert _get_token_dtype_code(100000) == np.dtype(np.uint64).num
17+
18+
19+
def test_get_token_dtype_code_boundary():
20+
"""The boundary between uint16 and uint64 is exactly 65536."""
21+
assert _get_token_dtype_code(65536) == 4

0 commit comments

Comments
 (0)