Coverage for transformer_lens/utilities/tokenize_utils.py: 95%

140 statements  

« prev     ^ index     » next       coverage.py v7.10.1, created at 2026-11-25 00:28 +0000

1"""tokenize_utils. 

2 

3This module contains utility functions related to tokenization 

4""" 

5 

6from __future__ import annotations 

7 

8import os 

9from copy import deepcopy 

10from typing import Any, Optional, cast 

11 

12import einops 

13import numpy as np 

14import torch 

15from datasets.arrow_dataset import Dataset 

16from datasets.iterable_dataset import IterableDataset 

17from transformers import AutoTokenizer, PreTrainedTokenizerBase, PreTrainedTokenizerFast 

18 

19from transformer_lens.utilities.hf_utils import keep_single_column 

20from transformer_lens.utilities.tensors import get_cumsum_along_dim 

21 

22 

23def tokenize_and_concatenate( 

24 dataset: Dataset | IterableDataset, 

25 tokenizer: PreTrainedTokenizerBase, 

26 streaming: bool = False, 

27 max_length: int = 1024, 

28 column_name: str = "text", 

29 add_bos_token: bool = True, 

30 num_proc: Optional[int] = 10, 

31 set_format: bool = True, 

32) -> Dataset | IterableDataset: 

33 """Tokenize each document, join with token-level EOS between docs, and reshape into ``(batch, sequence_length)`` rows. 

34 

35 Useful for training language models on a large text corpus without per-doc 

36 truncation or padding. Absolute-position-embedding models also benefit by 

37 avoiding early-token bias (e.g. news articles starting with "CNN"). 

38 

39 Args: 

40 dataset: The dataset to tokenize. Accepts both arrow ``Dataset`` and 

41 ``IterableDataset`` (e.g. when loaded with ``streaming=True``). 

42 tokenizer (PreTrainedTokenizerBase): The tokenizer. Must have ``bos_token_id`` and ``eos_token_id``. 

43 streaming (bool, optional): If True, avoids parallelism. Defaults to False. 

44 max_length (int, optional): The length of the context window of the sequence. Defaults to 1024. 

45 column_name (str, optional): The name of the text column in the dataset. Defaults to 'text'. 

46 add_bos_token (bool, optional): Whether to prepend ``bos_token_id`` to each output row. Defaults to True. 

47 num_proc (int, optional): Number of processes for parallel tokenization. ``None`` 

48 runs in-process -- datasets forks a dill-pickling pool for any int, 1 included. 

49 Ignored when ``streaming=True``. Defaults to 10. 

50 set_format (bool, optional): If True, calls ``set_format(type="torch")`` on the result. Set False 

51 for ``IterableDataset`` (which doesn't support format setting); wrap the output in 

52 ``(torch.LongTensor(ex["tokens"]) for ex in tokenized_dataset)`` instead. Defaults to True. 

53 

54 Returns: 

55 Tokenized dataset of token sequences in a single column ``"tokens"``. Returns the same dataset 

56 type as the input (``Dataset`` or ``IterableDataset``). 

57 """ 

58 dataset = keep_single_column(dataset, column_name) 

59 has_pad_token = tokenizer.pad_token is not None 

60 if not has_pad_token: 

61 tokenizer.add_special_tokens({"pad_token": "<PAD>"}) 

62 seq_len = max_length - 1 if add_bos_token else max_length 

63 

64 # Long docs legitimately exceed model_max_length; we slice into rows after. 

65 _deprecation_warnings_saved = None 

66 if hasattr(tokenizer, "deprecation_warnings"): 66 ↛ 72line 66 didn't jump to line 72 because the condition on line 66 was always true

67 _deprecation_warnings_saved = tokenizer.deprecation_warnings.copy() 

68 tokenizer.deprecation_warnings[ 

69 "sequence-length-is-longer-than-the-specified-maximum" 

70 ] = False 

71 

72 def tokenize_function(examples: Any) -> dict[str, np.ndarray]: 

73 text = examples[column_name] 

74 assert tokenizer.eos_token is not None, "Tokenizer must have an EOS token." 

75 if not text: 75 ↛ 76line 75 didn't jump to line 76 because the condition on line 75 was never true

76 return {"tokens": np.array([], dtype=np.int64)} 

77 

78 # Per-doc tokenization with explicit token-level EOS — string chunking 

79 # could cut tokens mid-doc (#1133); add_special_tokens=False prevents 

80 # SentencePiece tokenizers from scattering auto-BOS/EOS per call. 

81 encoded = tokenizer(text, add_special_tokens=False)["input_ids"] 

82 eos_id = tokenizer.eos_token_id 

83 pieces: list[np.ndarray] = [] 

84 for i, row in enumerate(encoded): 

85 pieces.append(np.asarray(row, dtype=np.int64)) 

86 if i < len(encoded) - 1: 

87 pieces.append(np.array([eos_id], dtype=np.int64)) 

88 if not pieces: 88 ↛ 89line 88 didn't jump to line 89 because the condition on line 88 was never true

89 return {"tokens": np.array([], dtype=np.int64)} 

90 tokens = np.concatenate(pieces) 

91 num_tokens = len(tokens) 

92 

93 if num_tokens < seq_len: 

94 num_batches = 1 

95 tokens = tokens[:seq_len] 

96 if len(tokens) < seq_len: 96 ↛ 106line 96 didn't jump to line 106 because the condition on line 96 was always true

97 # Pad with EOS when no native pad token to avoid OOV IDs. 

98 padding_id = tokenizer.eos_token_id if not has_pad_token else tokenizer.pad_token_id 

99 tokens = np.concatenate( 

100 [tokens, np.full(seq_len - len(tokens), padding_id)], axis=0 

101 ) 

102 else: 

103 num_batches = num_tokens // seq_len 

104 tokens = tokens[: seq_len * num_batches] 

105 

106 tokens = einops.rearrange( 

107 tokens, "(batch seq) -> batch seq", batch=num_batches, seq=seq_len 

108 ) 

109 if add_bos_token: 

110 prefix = np.full((num_batches, 1), tokenizer.bos_token_id) 

111 tokens = np.concatenate([prefix, tokens], axis=1) 

112 return {"tokens": tokens} 

113 

114 try: 

115 # IterableDataset.map() rejects `num_proc` outright (even None), so we 

116 # spread the kwarg conditionally rather than always passing it. 

117 tokenized_dataset = dataset.map( 

118 tokenize_function, 

119 batched=True, 

120 remove_columns=[column_name], 

121 **({"num_proc": num_proc} if not streaming else {}), 

122 ) 

123 finally: 

124 if _deprecation_warnings_saved is not None: 124 ↛ 127line 124 didn't jump to line 127 because the condition on line 124 was always true

125 tokenizer.deprecation_warnings.clear() 

126 tokenizer.deprecation_warnings.update(_deprecation_warnings_saved) 

127 if set_format: 

128 tokenized_dataset.set_format(type="torch", columns=["tokens"]) 

129 return tokenized_dataset 

130 

131 

132def _enable_bos_in_memory(tokenizer: PreTrainedTokenizerBase) -> PreTrainedTokenizerBase: 

133 """BOS-enabled copy of an in-memory fast tokenizer; unchanged if slow or a token has ':'.""" 

134 if not isinstance(tokenizer, PreTrainedTokenizerFast): 

135 return tokenizer 

136 tokenizer_with_bos = deepcopy(tokenizer) 

137 try: 

138 # The setter rebuilds the post-processor; the stubs declare the property read-only. 

139 cast(Any, tokenizer_with_bos).add_bos_token = True 

140 except ValueError: 

141 return tokenizer 

142 return tokenizer_with_bos 

143 

144 

145def get_tokenizer_with_bos(tokenizer: PreTrainedTokenizerBase) -> PreTrainedTokenizerBase: 

146 """ 

147 Returns the tokenizer initialized with add_bos_token=True. 

148 Such a tokenizer should be set as the default tokenizer because the tokenization of some 

149 tokenizers like LlamaTokenizer are different when bos token is automatically/manually 

150 prepended. 

151 

152 Note: For tokenizers without a BOS token (e.g., T5), this returns the original tokenizer 

153 unchanged since add_bos_token=True would fail in transformers v5+ when bos_token is None. 

154 

155 Note: For tokenizers built in memory (no ``name_or_path`` to reload from), BOS is enabled 

156 on a copy of the tokenizer; the original is returned when that is not possible. 

157 

158 Args: 

159 tokenizer (PreTrainedTokenizerBase): The tokenizer to initialize with add_bos_token=True. 

160 

161 Returns: 

162 PreTrainedTokenizerBase: The tokenizer initialized with add_bos_token=True, 

163 or the original tokenizer if it has no BOS token. 

164 """ 

165 # If the tokenizer has no BOS token, we can't set add_bos_token=True 

166 # This is the case for T5 and other encoder-decoder models 

167 if tokenizer.bos_token is None: 

168 return tokenizer 

169 

170 init_kwargs = deepcopy(tokenizer.init_kwargs) 

171 # Tokenizers built in memory have no ``name_or_path`` entry and nothing to reload. 

172 pretrained_model_name_or_path = init_kwargs.pop("name_or_path", None) or tokenizer.name_or_path 

173 add_bos_token = init_kwargs.pop("add_bos_token", None) 

174 if add_bos_token is None: 

175 add_bos_token = getattr(tokenizer, "add_bos_token", False) 

176 

177 if add_bos_token: 

178 tokenizer_with_bos = tokenizer 

179 elif not pretrained_model_name_or_path: 

180 return _enable_bos_in_memory(tokenizer) 

181 else: 

182 huggingface_token = os.environ.get("HF_TOKEN", "") 

183 try: 

184 tokenizer_with_bos = AutoTokenizer.from_pretrained( 

185 pretrained_model_name_or_path, 

186 add_bos_token=True, 

187 token=huggingface_token if len(huggingface_token) > 0 else None, 

188 **init_kwargs, 

189 ) 

190 except ValueError: 

191 # tokenizers' TemplateProcessing cannot express special tokens 

192 # containing ':' (e.g. Seed-OSS's <seed:bos>), so add_bos_token=True 

193 # crashes when rebuilding the post-processor. Keep the original 

194 # tokenizer — such models do not auto-prepend BOS anyway. 

195 return tokenizer 

196 # Preserve padding_side from the original tokenizer, since AutoTokenizer.from_pretrained 

197 # resets it to the HuggingFace default (usually "right"). Without this, callers who 

198 # explicitly set tokenizer.padding_side = "left" before passing the tokenizer in would 

199 # have that setting silently discarded. See issue #801. 

200 tokenizer_with_bos.padding_side = tokenizer.padding_side 

201 

202 return tokenizer_with_bos 

203 

204 

205def get_input_with_manually_prepended_bos( 

206 bos_token: Optional[str], input: str | list[str] 

207) -> str | list[str]: 

208 """ 

209 Manually prepends the bos token to the input. 

210 

211 Args: 

212 bos_token (Optional[str]): The BOS token to prepend, or None for a tokenizer 

213 that has none (e.g. BERT, T5). 

214 input (str | list[str]): The input to prepend the bos token to. 

215 

216 Returns: 

217 str | list[str]: The input with the bos token manually prepended, or unchanged 

218 when there is no BOS token to prepend. 

219 """ 

220 if bos_token is None: 

221 # Nothing to prepend. Callers reach this when prepend_bos is asked for and 

222 # cfg.tokenizer_prepends_bos is False — correctly so for a BOS-less tokenizer, 

223 # since detect_tokenizer_bos_eos() requires a bos_token_id. Concatenating 

224 # would raise a TypeError naming neither the tokenizer nor the flag. 

225 return input 

226 

227 if isinstance(input, str): 

228 input = bos_token + input 

229 else: 

230 input = [bos_token + string for string in input] 

231 return input 

232 

233 

234def get_tokens_with_bos_removed( 

235 tokenizer: PreTrainedTokenizerBase, 

236 tokens: torch.Tensor, 

237 padding_side: str | None = None, 

238) -> torch.Tensor: 

239 """ 

240 Removes the bos token from the beginning of each sequence in `tokens`. 

241 The last dimension of `tokens` must be the sequence length. 

242 

243 Args: 

244 tokenizer (PreTrainedTokenizerBase): The tokenizer used to tokenize the input. 

245 tokens (torch.Tensor): The tokenized input. 

246 padding_side: The side used to pad ``tokens``. Defaults to the tokenizer setting. 

247 

248 Returns: 

249 torch.Tensor: The tokenized input with the bos token removed. 

250 """ 

251 if tokenizer.bos_token_id is None: 

252 # Nothing to remove (#1628). Callers reach this when cfg.tokenizer_prepends_bos 

253 # says the tokenizer prepends a BOS but the tokenizer has none — a stale 

254 # flag, since detect_tokenizer_bos_eos() requires a bos_token_id. Trusting 

255 # it here would drop a real first token under right padding ([CLS] for a 

256 # BERT tokenizer), and compare tokens against None under left padding. 

257 return tokens 

258 

259 if padding_side is None: 

260 padding_side = tokenizer.padding_side 

261 

262 if padding_side == "right": 

263 return tokens[..., 1:] 

264 

265 else: 

266 bos_removed_shape = list(tokens.shape) 

267 bos_removed_shape[-1] -= 1 

268 

269 if tokenizer.pad_token_id is None: 

270 n_leading_pads = torch.zeros(tokens.shape[:-1], dtype=torch.long, device=tokens.device) 

271 else: 

272 is_not_pad_token = tokens.ne(tokenizer.pad_token_id) 

273 is_leading_pad = get_cumsum_along_dim(is_not_pad_token, -1, reverse=False) == 0 

274 n_leading_pads = is_leading_pad.sum(-1) 

275 

276 if tokenizer.bos_token_id == tokenizer.pad_token_id: 

277 # The prepended BOS is the last of the leading pads. 

278 real_bos_positions = n_leading_pads - 1 

279 has_bos = n_leading_pads > 0 

280 else: 

281 # The prepended token is the first non-pad one; CLS counts as it does in 

282 # detect_tokenizer_bos_eos, so BERT-style tokenizers drop [CLS] here too. 

283 leading_ids = [tokenizer.bos_token_id] 

284 cls_token_id = getattr(tokenizer, "cls_token_id", None) 

285 if isinstance(cls_token_id, int): 

286 leading_ids.append(cls_token_id) 

287 real_bos_positions = n_leading_pads 

288 has_bos = n_leading_pads < tokens.shape[-1] 

289 if tokens.shape[-1] > 0: 289 ↛ 295line 289 didn't jump to line 295 because the condition on line 289 was always true

290 first_real = tokens.gather( 

291 -1, n_leading_pads.clamp(max=tokens.shape[-1] - 1).unsqueeze(-1) 

292 ).squeeze(-1) 

293 has_bos &= torch.isin(first_real, torch.tensor(leading_ids, device=tokens.device)) 

294 

295 if not bool(has_bos.all()): 

296 # Dropping a column from such a row would remove a real token (or index 

297 # out of bounds), and keeping it would leave the rows ragged. 

298 raise ValueError( 

299 f"Cannot remove BOS: {int((~has_bos).sum())} left-padded row(s) do not start " 

300 f"with the BOS token (id {tokenizer.bos_token_id}) after their padding. " 

301 "Rows passed here must each carry the BOS the tokenizer prepends." 

302 ) 

303 

304 tokens = tokens.scatter(dim=-1, index=real_bos_positions.unsqueeze(-1), value=-100) 

305 return tokens[tokens != -100].view(*bos_removed_shape) 

306 

307 

308def get_attention_mask( 

309 tokenizer: PreTrainedTokenizerBase, 

310 tokens: torch.Tensor, 

311 prepend_bos: bool, 

312 padding_side: str | None = None, 

313) -> torch.Tensor: 

314 """ 

315 Computes the attention mask for the tokenized input. 

316 NOTE: Only the leftmost leading pads (when `padding_side == left`) 

317 or rightmost trailing pads (when `padding_side == right`) are 

318 considered as real pad tokens that should not be attended. 

319 

320 Args: 

321 tokenizer (PreTrainedTokenizerBase): The tokenizer used for tokenization. 

322 tokens (torch.Tensor): The tokenized input. 

323 prepend_bos (bool): If True, a BOS token is prepended to the input. 

324 padding_side: The side used to pad ``tokens``. Defaults to the tokenizer setting. 

325 

326 Returns: 

327 torch.Tensor: The attention mask for the input. 

328 """ 

329 

330 # Default to attending every token; pad positions are zeroed below. 

331 attention_mask = torch.ones_like(tokens) 

332 if tokenizer is None: 332 ↛ 333line 332 didn't jump to line 333 because the condition on line 332 was never true

333 return attention_mask 

334 if padding_side is None: 

335 padding_side = tokenizer.padding_side 

336 is_not_pad_token = tokens.ne(tokenizer.pad_token_id) 

337 

338 if padding_side == "right": 

339 # Zero-out the rightmost trailing pad tokens 

340 is_trailing_pad = get_cumsum_along_dim(is_not_pad_token, -1, reverse=True) == 0 

341 attention_mask[is_trailing_pad] = 0 

342 else: 

343 # Zero-out the leftmost leading pad tokens 

344 is_leading_pad = get_cumsum_along_dim(is_not_pad_token, -1, reverse=False) == 0 

345 attention_mask[is_leading_pad] = 0 

346 

347 # Unmask BOS when it shares the same ID as pad token 

348 if prepend_bos and tokenizer.bos_token_id == tokenizer.pad_token_id: 

349 pad_bos_positions = is_leading_pad.sum(-1) - 1 

350 attention_mask[torch.arange(attention_mask.shape[0]), pad_bos_positions] = 1 

351 

352 return attention_mask