Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / data / text / build_tokenizer.py: 60%
92 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
1# Copyright (c) 2025-2026, NVIDIA CORPORATION. All rights reserved.
2# Copyright 2026 Huawei Technologies Co., Ltd
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15# ============================================================================
17"""Build the tokenizer used by the private LLM data stages."""
19from __future__ import annotations
21import json
22from collections import OrderedDict
23from typing import Any
25from hyper_parallel.data.dataset_logging import get_dataset_logger
27logger = get_dataset_logger(__name__)
30class _DatasetTokenizer:
31 """Provide the stable tokenizer identity required by Dataset caches."""
33 def __init__(
34 self,
35 *tokenizer_paths: str,
36 vocab_size: int | None = None,
37 eod_token_id: int | None = None,
38 pad_token_id: int | None = None,
39 **tokenizer_options: Any,
40 ) -> None:
41 """Record the tokenizer identity and validate the special token configuration.
43 Args:
44 *tokenizer_paths: Tokenizer source paths recorded in the cache identity.
45 vocab_size: Pretokenized-corpus vocabulary size.
46 eod_token_id: Pretokenized-corpus end-of-document token ID, when one exists.
47 pad_token_id: Pretokenized-corpus padding token ID, when one exists.
48 **tokenizer_options: Extra options recorded in the cache identity.
50 Raises:
51 ValueError: If the vocabulary size is invalid or a special token ID is out of range.
52 """
54 if vocab_size is not None:
55 if vocab_size <= 0:
56 raise ValueError("vocab_size must be positive")
58 if eod_token_id is not None and not 0 <= eod_token_id < vocab_size:
59 raise ValueError("eod_token_id must be within the tokenizer vocabulary")
61 if pad_token_id is not None and not 0 <= pad_token_id < vocab_size:
62 raise ValueError("pad_token_id must be within the tokenizer vocabulary")
64 tokenizer_options["vocab_size"] = vocab_size
66 if eod_token_id is not None:
67 tokenizer_options["eod_token_id"] = eod_token_id
69 if pad_token_id is not None:
70 tokenizer_options["pad_token_id"] = pad_token_id
72 self.unique_identifiers = OrderedDict()
73 self.unique_identifiers["class"] = type(self).__name__
74 self.unique_identifiers["tokenizer_path"] = list(tokenizer_paths)
75 for option, value in tokenizer_options.items():
76 self.unique_identifiers[option] = str(value)
77 self.unique_description = json.dumps(self.unique_identifiers, indent=4)
79 if vocab_size is not None:
80 self.vocab_size = vocab_size
81 self.eod = eod_token_id
82 self.eos_token_id = eod_token_id
83 self.pad_token_id = pad_token_id
85 def __len__(self) -> int:
86 """Return the configured tokenizer vocabulary size."""
87 return self.vocab_size
89 @property
90 def eos(self) -> int | None:
91 """Return the end-of-sequence token ID when one exists."""
92 return self.eos_token_id
94 @property
95 def pad(self) -> int:
96 """Return the padding token ID."""
97 if self.pad_token_id is None:
98 raise AttributeError("The tokenizer does not define a padding token ID")
100 return self.pad_token_id
103class _HFAutoTokenizer(_DatasetTokenizer):
104 """Wrap a Hugging Face tokenizer with the Dataset tokenizer contract."""
106 def __init__(
107 self,
108 pretrained_model_name_or_path: str,
109 *args: Any,
110 trust_remote_code: bool,
111 **kwargs: Any,
112 ) -> None:
113 """Load a Hugging Face tokenizer and expose the Dataset identity contract.
115 Args:
116 pretrained_model_name_or_path: Model identifier or local tokenizer path.
117 *args: Extra positional arguments forwarded to ``HFAutoTokenizer.from_pretrained``.
118 trust_remote_code: Whether to trust remote code when loading the tokenizer.
119 **kwargs: Extra keyword arguments forwarded to ``HFAutoTokenizer.from_pretrained``.
121 Raises:
122 ValueError: If the tokenizer defines neither ``eod`` nor ``eos_token_id``.
123 """
124 tokenizer_options = dict(kwargs)
125 tokenizer_options["trust_remote_code"] = trust_remote_code
126 if args:
127 tokenizer_options["inputs"] = args
128 super().__init__(pretrained_model_name_or_path, **tokenizer_options)
130 # Transformers is optional and only required when constructing an HF tokenizer.
131 from transformers import AutoTokenizer as HFAutoTokenizer # pylint: disable=C0415
133 self.tokenizer = HFAutoTokenizer.from_pretrained(
134 pretrained_model_name_or_path, *args, trust_remote_code=trust_remote_code, **kwargs
135 )
136 if not hasattr(self.tokenizer, "eod"):
137 eos_token_id = getattr(self.tokenizer, "eos_token_id", None)
138 if eos_token_id is None:
139 raise ValueError("The tokenizer must define either 'eod' or 'eos_token_id'")
140 self.tokenizer.eod = eos_token_id
142 def __getattr__(self, name: str) -> Any:
143 """Delegate tokenizer attributes to the wrapped Hugging Face tokenizer."""
144 return getattr(self.tokenizer, name)
146 def __setattr__(self, name: str, value: Any) -> None:
147 """Delegate runtime tokenizer options after the wrapped tokenizer exists."""
148 tokenizer = self.__dict__.get("tokenizer")
149 if tokenizer is None or name in {"tokenizer", "unique_identifiers", "unique_description"}:
150 object.__setattr__(self, name, value)
151 return
152 setattr(tokenizer, name, value)
154 def __len__(self) -> int:
155 """Return the wrapped tokenizer vocabulary size."""
156 return len(self.tokenizer)
158 def __call__(self, *args: Any, **kwargs: Any) -> Any:
159 """Forward tokenization calls to the wrapped tokenizer."""
160 return self.tokenizer(*args, **kwargs)
163class AutoTokenizer:
164 """
165 Auto tokenizer class that dispatches to appropriate tokenizer implementations.
167 Similar to HuggingFace's AutoTokenizer, but with a custom registry for specialized
168 tokenizer implementations.
170 The dispatch logic is:
171 1. If a custom tokenizer is registered for the model type, use it
172 2. Otherwise, fall back to NeMoAutoTokenizerWithBosEosEnforced
174 Example:
175 >>> # Will use MistralCommonBackend if available for Mistral models
176 >>> tokenizer = NeMoAutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1")
178 >>> # Force using HF AutoTokenizer with BOS/EOS enforcement
179 >>> tokenizer = NeMoAutoTokenizer.from_pretrained("gpt2", force_default=True)
180 """
182 # Make registry accessible at class level
183 _registry = None
185 @classmethod
186 def from_pretrained(
187 cls,
188 pretrained_model_name_or_path: str | None,
189 *args: Any,
190 force_default: bool = False,
191 force_hf: bool = True,
192 trust_remote_code: bool = False,
193 tokenizer_type: str | None = None,
194 vocab_size: int | None = None,
195 eod_token_id: int | None = None,
196 pad_token_id: int | None = None,
197 **kwargs: Any,
198 ) -> Any:
199 """
200 Load a tokenizer from a pretrained model.
202 Args:
203 pretrained_model_name_or_path: Tokenizer path used for loading or stable Dataset cache identity.
204 *args: Additional positional arguments passed to the tokenizer's from_pretrained.
205 force_default: If True, always use NeMoAutoTokenizerWithBosEosEnforced
206 force_hf: If True, build a wrapped Hugging Face tokenizer.
207 trust_remote_code: Whether to trust remote code when loading config
208 tokenizer_type: Use ``hf`` to load a Hugging Face tokenizer or ``pretokenized`` for metadata only.
209 vocab_size: Pretokenized-corpus vocabulary size; required when tokenizer_type is pretokenized.
210 eod_token_id: Pretokenized-corpus end-of-document token ID, when one exists.
211 pad_token_id: Pretokenized-corpus padding token ID, when one exists.
212 **kwargs: Additional arguments passed to the tokenizer's from_pretrained
214 Returns:
215 A tokenizer instance appropriate for the model type
216 """
217 # ``force_default`` is retained for NeMo API compatibility; only the HF backend is supported.
218 del force_default
220 if tokenizer_type == "pretokenized":
221 if pretrained_model_name_or_path is None:
222 raise ValueError("pretrained_model_name_or_path is required for a pretokenized Dataset")
224 if vocab_size is None:
225 raise ValueError("tokenizer_type='pretokenized' requires vocab_size")
227 tokenizer = _DatasetTokenizer(
228 pretrained_model_name_or_path,
229 vocab_size=vocab_size,
230 eod_token_id=eod_token_id,
231 pad_token_id=pad_token_id,
232 )
233 elif tokenizer_type not in (None, "hf"):
234 raise ValueError(f"Unsupported tokenizer_type: {tokenizer_type!r}")
235 else:
236 if vocab_size is not None or eod_token_id is not None or pad_token_id is not None:
237 raise ValueError("vocab_size, eod_token_id, and pad_token_id require tokenizer_type='pretokenized'")
239 if pretrained_model_name_or_path is None:
240 raise ValueError("pretrained_model_name_or_path is required for a Hugging Face tokenizer")
242 if tokenizer_type != "hf" and not force_hf:
243 raise ValueError("Only the Hugging Face tokenizer backend is currently supported")
245 # Explicit ``hf`` and the legacy ``force_hf`` switch select the same backend.
246 tokenizer = _HFAutoTokenizer(
247 pretrained_model_name_or_path,
248 *args,
249 trust_remote_code=trust_remote_code,
250 **kwargs,
251 )
253 backend = getattr(tokenizer, "tokenizer", tokenizer)
254 logger.debug(
255 "Built Dataset tokenizer: type=%s, backend=%s, path=%s, vocab_size=%d, "
256 "eod_token_id=%s, eos_token_id=%s, pad_token_id=%s",
257 type(tokenizer).__name__, type(backend).__name__, pretrained_model_name_or_path, len(tokenizer),
258 getattr(tokenizer, "eod", None), getattr(tokenizer, "eos_token_id", None),
259 getattr(tokenizer, "pad_token_id", None),
260 )
261 return tokenizer
264def build_tokenizer(pretrained_model_name_or_path: str, **kwargs: Any) -> Any:
265 """Build the configured LLM tokenizer.
267 Args:
268 pretrained_model_name_or_path: Model identifier or local tokenizer path.
269 **kwargs: Options forwarded to ``AutoTokenizer.from_pretrained``.
271 Returns:
272 The constructed tokenizer.
273 """
274 return AutoTokenizer.from_pretrained(pretrained_model_name_or_path, **kwargs)