import os import tqdm import numpy as np import tiktoken from tokenizer import NurTokenizer # import requests # ----------------------------------------------------------------------------- # Configuration input_file_path = 'data/input.txt' # Put your raw text here output_train_path = 'data/train.bin' output_val_path = 'data/val.bin' split_ratio = 0.9 chunk_size = 1024 * 1024 # 1MB chunks for reading # ----------------------------------------------------------------------------- def prepare(): os.makedirs('data', exist_ok=True) if not os.path.exists(input_file_path): print(f"Error: {input_file_path} not found.") return # Check file size file_size = os.path.getsize(input_file_path) print(f"Input file size: {file_size / (1024*1024*1024):.2f} GB") # 1. Train Tokenizer (Efficiently) # The 'tokenizers' library is Rust-based and memory mapped, so it handles large files well. print("Training/Loading Tokenizer...") tokenizer = NurTokenizer() if not os.path.exists("nur_tokenizer.json"): print("Training new BPE tokenizer...") # We can pass the file path directly; tokenizers library manages memory tokenizer.train([input_file_path]) tokenizer.save("nur_tokenizer.json") else: tokenizer.load("nur_tokenizer.json") # 2. Stream and Encode # We will read the file in chunks, encode, and distribute to train/val bin files print("Encoding data in chunks (Streaming)...") # We need to decide where to cut for validation. # Since we are streaming, exact 90/10 split is hard to pre-calculate without a pass. # Approximation: We will switch to validation after reading 90% of BYTES. split_byte = int(file_size * split_ratio) # Open binary files for writing with open(output_train_path, 'wb') as f_train, open(output_val_path, 'wb') as f_val: with open(input_file_path, 'r', encoding='utf-8', errors='ignore') as f_in: pbar = tqdm.tqdm(total=file_size, unit='B', unit_scale=True, desc="Processing") current_bytes = 0 while True: chunk = f_in.read(chunk_size) if not chunk: break # Encode chunk # Note: chunk boundaries might cut a token, but for massive pretraining code data # this minor noise is usually acceptable or handled by the tokenizer's robustness. # Ideally we read lines, but large code files might have huge lines or no newlines. # CodeParrot relies on <|startoftext|> markers, so we are fine. ids = tokenizer.encode(chunk) # Convert to uint16 ids_np = np.array(ids, dtype=np.uint16) # Write to appropriate file if current_bytes < split_byte: bytes_written = f_train.write(ids_np.tobytes()) else: bytes_written = f_val.write(ids_np.tobytes()) # Update progress chunk_len = len(chunk.encode('utf-8')) # Approximate byte length read current_bytes += chunk_len pbar.update(chunk_len) pbar.close() print(f"Done. Saved to {output_train_path} and {output_val_path}") if __name__ == "__main__": prepare()