Download datasets/preprocess.py from Ian26/MarsLM: direct link, hf CLI and curl.
- Browser
- Download file 2.18 kB
-
https://huggingface.co/Ian26/MarsLM/resolve/main/datasets/preprocess.py
- Command line
-
hf download hf://Ian26/MarsLM/datasets/preprocess.py
-
curl -L -o preprocess.py https://huggingface.co/Ian26/MarsLM/resolve/main/datasets/preprocess.py
2.18 kB
| import argparse | |
| import sys | |
| from pathlib import Path | |
| import torch | |
| ROOT = Path(__file__).resolve().parents[1] | |
| if str(ROOT) not in sys.path: | |
| sys.path.append(str(ROOT)) | |
| from tokenizer.tokenizer_utils import load_tokenizer, encode_text | |
| def _stream_lines(paths): | |
| for path in [Path(p) for p in paths]: | |
| if path.suffix == ".jsonl": | |
| with path.open("r", encoding="utf-8") as handle: | |
| for line in handle: | |
| yield line.strip() | |
| else: | |
| with path.open("r", encoding="utf-8") as handle: | |
| for line in handle: | |
| yield line | |
| def preprocess_dataset(input_paths, tokenizer_path, output_path, block_size=512): | |
| tokenizer = load_tokenizer(tokenizer_path) | |
| output_path = Path(output_path) | |
| output_path.parent.mkdir(parents=True, exist_ok=True) | |
| buffer = [] | |
| chunk_count = 0 | |
| for text in _stream_lines(input_paths): | |
| if not text: | |
| continue | |
| ids = encode_text(tokenizer, text, add_special_tokens=False) | |
| buffer.extend(ids) | |
| while len(buffer) >= block_size: | |
| chunk = torch.tensor(buffer[:block_size], dtype=torch.long) | |
| chunk_file = output_path.parent / f"chunk-{chunk_count:06d}.pt" | |
| torch.save({"tokens": chunk}, chunk_file) | |
| chunk_count += 1 | |
| buffer = buffer[block_size:] | |
| if chunk_count == 0: | |
| raise ValueError("No data could be written. Check the input corpus and block_size.") | |
| print(f"Saved {chunk_count} chunks to {output_path.parent}") | |
| def main(): | |
| parser = argparse.ArgumentParser(description="Tokenize and chunk a text corpus") | |
| parser.add_argument("--input", nargs="+", required=True) | |
| parser.add_argument("--tokenizer", required=True) | |
| parser.add_argument("--output", required=True) | |
| parser.add_argument("--block-size", type=int, default=512) | |
| args = parser.parse_args() | |
| output_path = Path(args.output).resolve() | |
| output_path.parent.mkdir(parents=True, exist_ok=True) | |
| preprocess_dataset(args.input, Path(args.tokenizer).resolve(), output_path, block_size=args.block_size) | |
| if __name__ == "__main__": | |
| main() | |