File size: 4,350 Bytes
673d750
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
"""Stream HF chat conversations through a tokenizer into uint16 memmaps."""

from __future__ import annotations

import argparse
import json
from pathlib import Path

import numpy as np
from tokenizers import Tokenizer
from tqdm import tqdm

from chat_data import format_conversation, stream_hf_rows

DATASET_NAME = "HuggingFaceH4/no_robots"
TRAIN_SPLIT = "train"
VALIDATION_SPLIT = "test"
END_OF_TEXT = "<|endoftext|>"
INITIAL_CAPACITY = 1 << 20
ENCODE_BATCH_SIZE = 256


class GrowingMemmap:
	def __init__(self, path: Path, initial_capacity: int = INITIAL_CAPACITY) -> None:
		self.path = path
		self.capacity = initial_capacity
		self.length = 0
		path.parent.mkdir(parents=True, exist_ok=True)
		with path.open("wb") as output:
			output.truncate(self.capacity * np.dtype(np.uint16).itemsize)
		self.array = np.memmap(path, dtype=np.uint16, mode="r+", shape=(self.capacity,))

	def append(self, token_ids: list[int]) -> None:
		if not token_ids:
			return
		needed = self.length + len(token_ids)
		if needed > self.capacity:
			self.array.flush()
			del self.array
			self.capacity = max(self.capacity * 2, needed)
			with self.path.open("r+b") as output:
				output.truncate(self.capacity * np.dtype(np.uint16).itemsize)
			self.array = np.memmap(
				self.path, dtype=np.uint16, mode="r+", shape=(self.capacity,)
			)
		self.array[self.length : needed] = np.asarray(token_ids, dtype=np.uint16)
		self.length = needed

	def close(self) -> None:
		self.array.flush()
		del self.array
		with self.path.open("r+b") as output:
			output.truncate(self.length * np.dtype(np.uint16).itemsize)
		if self.length < 2:
			raise RuntimeError(f"Not enough tokens were written to {self.path}")


def write_split(
	dataset_name: str,
	split: str,
	output_path: Path,
	tokenizer: Tokenizer,
	eos_token_id: int,
	max_conversations: int | None,
) -> int:
	writer = GrowingMemmap(output_path)
	texts: list[str] = []
	processed = 0
	progress = tqdm(desc=f"Tokenizing {split}", unit="conversations")

	def flush_batch() -> None:
		if not texts:
			return
		for encoding in tokenizer.encode_batch(texts):
			writer.append(encoding.ids)
			writer.append([eos_token_id])
		texts.clear()

	try:
		for row in stream_hf_rows(dataset_name, split):
			if max_conversations is not None and processed >= max_conversations:
				break
			processed += 1
			progress.update(1)
			text = format_conversation(row)
			if text is not None:
				texts.append(text)
			if len(texts) >= ENCODE_BATCH_SIZE:
				flush_batch()
		flush_batch()
	finally:
		progress.close()
		writer.close()

	print(f"Wrote {writer.length:,} uint16 tokens to {output_path}")
	return writer.length


def main() -> None:
	parser = argparse.ArgumentParser(description=__doc__)
	parser.add_argument("--tokenizer", type=Path, default=Path("agent-tokenizer.json"))
	parser.add_argument("--output-dir", type=Path, default=Path("agent-data"))
	parser.add_argument("--dataset", default=DATASET_NAME)
	parser.add_argument("--train-split", default=TRAIN_SPLIT)
	parser.add_argument("--validation-split", default=VALIDATION_SPLIT)
	parser.add_argument("--max-train-conversations", type=int, default=None)
	parser.add_argument("--max-val-conversations", type=int, default=None)
	args = parser.parse_args()
	if not args.tokenizer.is_file():
		parser.error(f"Tokenizer not found: {args.tokenizer}")
	tokenizer = Tokenizer.from_file(str(args.tokenizer))
	if tokenizer.get_vocab_size() > np.iinfo(np.uint16).max + 1:
		parser.error("Tokenizer vocabulary does not fit in uint16 token IDs")
	eos_token_id = tokenizer.token_to_id(END_OF_TEXT)
	if eos_token_id is None:
		parser.error(f"Tokenizer must contain the special token {END_OF_TEXT}")
	args.output_dir.mkdir(parents=True, exist_ok=True)
	manifest_path = args.output_dir / "dataset.json"
	manifest_path.unlink(missing_ok=True)
	write_split(
		args.dataset,
		args.train_split,
		args.output_dir / "train.bin",
		tokenizer,
		eos_token_id,
		args.max_train_conversations,
	)
	write_split(
		args.dataset,
		args.validation_split,
		args.output_dir / "val.bin",
		tokenizer,
		eos_token_id,
		args.max_val_conversations,
	)
	manifest_path.write_text(
		json.dumps(
			{
				"dataset": args.dataset,
				"train_split": args.train_split,
				"validation_split": args.validation_split,
			},
			indent=2,
		)
		+ "\n",
		encoding="utf-8",
	)


if __name__ == "__main__":
	main()