Download prepare_data.py from Valeztiro/Micro-llm: direct link, hf CLI and curl.
- Browser
- Download file 4.35 kB
-
https://huggingface.co/Valeztiro/Micro-llm/resolve/main/prepare_data.py
- Command line
-
hf download hf://Valeztiro/Micro-llm/prepare_data.py
-
curl -L -o prepare_data.py https://huggingface.co/Valeztiro/Micro-llm/resolve/main/prepare_data.py
4.35 kB
| """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() |