File size: 2,175 Bytes
0f2ce63 8f20aff 0f2ce63 8f20aff 0f2ce63 | 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 | 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()
|