""" Bhaari AI - Phase 1: BhaariTok Tokenizer Training Uses HuggingFace tokenizers library for fast BPE training """ import os import sys import json import torch import shutil import random import requests from pathlib import Path from datetime import datetime sys.path.insert(0, str(Path(__file__).parent.parent)) from tokenizer.special_tokens import SPECIAL_TOKENS from scripts.generate_report import generate_tokenizer_report from scripts.push_to_hf import push_to_huggingface def check_gpu(): print("\n" + "=" * 60) print("GPU Information") print("=" * 60) if torch.cuda.is_available(): print("CUDA Available: Yes") print("GPU: " + torch.cuda.get_device_name(0)) print("GPU Memory: %.1f GB" % (torch.cuda.get_device_properties(0).total_memory / 1e9)) print("CUDA Version: " + torch.version.cuda) return True else: print("CUDA Not Available") return False def fetch_real_code_data(target_count=50000): print("\n" + "=" * 60) print("Fetching Real Code Data from HuggingFace") print("=" * 60) HF_TOKEN = os.environ.get("HF_TOKEN", "") headers = {"Authorization": "Bearer " + HF_TOKEN} base_url = "https://datasets-server.huggingface.co/rows" all_texts = [] offset = 0 batch_size = 100 total_fetched = 0 print("Fetching from codeparrot/codeparrot-clean...") while total_fetched < target_count: params = { "dataset": "codeparrot/codeparrot-clean", "config": "default", "split": "train", "offset": offset, "length": batch_size } try: r = requests.get(base_url, params=params, headers=headers, timeout=30) data = r.json() if "rows" not in data: print("API error: %s" % str(data)) break rows = data["rows"] if not rows: print("No more rows at offset %d" % offset) break for row in rows: content = row["row"].get("content", "") if len(content) > 200 and len(content) < 50000: all_texts.append(content) total_fetched += 1 offset += batch_size if total_fetched % 5000 == 0: print(" Fetched %d samples (offset: %d)" % (total_fetched, offset)) except Exception as e: print(" Fetch error at offset %d: %s" % (offset, str(e))) break print(" Total fetched: %d real code samples" % total_fetched) return all_texts def generate_synthetic_code_data(target_count=50000): print("\n" + "=" * 60) print("Generating Synthetic Multi-Language Code Data") print("=" * 60) func_names = ["calculate", "process", "transform", "validate", "parse", "generate", "fetch", "update", "create", "delete", "search", "sort", "filter", "map", "reduce", "aggregate", "compute", "execute", "run", "handle", "initialize", "configure", "setup", "cleanup", "load", "save", "export", "import", "convert", "format", "render", "build", "compile", "optimize", "debug", "test", "verify", "check", "monitor", "log", "trace", "profile", "benchmark", "measure", "evaluate", "analyze", "inspect", "examine", "review", "audit", "scan", "detect", "identify", "classify", "categorize", "organize", "arrange", "sequence", "connect", "attach", "detach", "separate", "split", "join", "merge", "combine", "integrate", "embed", "inject", "extract", "remove", "add", "insert", "append", "replace", "substitute", "swap", "transfer", "move", "copy", "clone", "replicate", "reproduce"] var_names = ["x", "y", "z", "i", "j", "k", "n", "m", "a", "b", "c", "data", "result", "output", "input", "value", "item", "element", "node", "index", "count", "total", "sum", "avg", "min", "max", "key", "val", "name", "id", "type", "size", "length", "width", "height", "config", "options", "params", "args", "kwargs", "self", "obj", "ctx", "env", "state", "status", "flag", "mode", "level", "score", "grade", "rate", "price", "cost", "amount", "quantity", "number", "error", "delta", "diff", "change", "step", "offset", "base", "root", "source", "target", "origin", "dest", "start", "end", "begin", "finish", "first", "last", "next", "prev", "curr", "old", "new", "tmp", "temp", "buf", "buffer", "cache", "store", "heap", "stack", "queue", "list", "array", "vec", "dict", "map", "set", "tree", "graph", "path", "url", "file", "dir", "title", "label", "desc", "text", "msg", "info", "note", "comment", "doc", "code", "func", "method", "class", "struct", "enum", "var", "const", "let", "ref", "ptr", "handle", "session", "token", "auth", "user", "role", "perm", "access", "hash", "salt", "key", "secret", "pass", "login", "logout", "signup", "register", "confirm", "reset", "recover", "read", "write", "open", "close", "init", "pause", "resume", "cancel", "abort", "retry", "repeat", "loop", "iterate", "cycle", "spin", "wait", "sleep", "wake", "notify", "signal", "trigger", "fire", "emit", "broadcast", "send", "receive", "get", "set", "put", "post", "patch", "del", "head", "options"] modules = ["os", "sys", "json", "math", "random", "datetime", "collections", "itertools", "functools", "typing", "pathlib", "logging", "asyncio", "threading", "multiprocessing", "socket", "http", "urllib", "re", "string", "time", "calendar", "hashlib", "hmac", "secrets", "copy", "pprint", "textwrap", "unicodedata", "difflib", "enum", "graphlib", "operator", "decimal", "fractions", "statistics", "array", "heapq", "bisect", "queue", "struct", "codecs", "csv", "configparser", "tomllib", "dataclasses", "contextlib", "abc", "atexit", "traceback", "warnings", "weakref", "types", "inspect", "dis", "pickle", "shelve", "dbm", "sqlite3", "zlib", "gzip", "bz2", "lzma", "zipfile", "tarfile", "io", "tempfile", "glob", "fnmatch", "shutil", "filecmp", "subprocess", "sched", "signal", "mmap", "ctypes", "select", "selectors", "ssl", "xml", "html", "email", "mailbox", "mimetypes", "base64", "binascii", "quopri", "uu"] exceptions = ["Exception", "ValueError", "TypeError", "KeyError", "IndexError", "AttributeError", "RuntimeError", "IOError", "OSError", "FileNotFoundError", "PermissionError", "TimeoutError", "ConnectionError", "StopIteration", "GeneratorExit", "SystemExit", "KeyboardInterrupt", "MemoryError", "RecursionError", "NotImplementedError", "AssertionError", "ImportError", "ModuleNotFoundError", "NameError", "UnboundLocalError", "SyntaxError", "IndentationError", "TabError"] rust_types = ["i32", "i64", "u32", "u64", "f32", "f64", "bool", "String", "str", "Vec", "Vec", "Option", "Result", "HashMap", "Box", "Rc", "Arc", "Mutex", "RwLock"] all_texts = [] dataset_stats = [] # Python print("Generating Python code...") py_count = target_count // 2 for idx in range(py_count): fn = random.choice(func_names) a = ", ".join(random.sample(var_names, random.randint(1, 4))) v1, v2, v3 = random.sample(var_names, 3) imp = random.choice(modules) exc = random.choice(exceptions) afn = "async_" + random.choice(func_names) aa = ", ".join(random.sample(var_names, random.randint(1, 3))) cls = fn.title() + "Model" ia = ", ".join(random.sample(var_names, random.randint(1, 3))) mn = random.choice(func_names) ma = ", ".join(random.sample(var_names, random.randint(1, 3))) n = random.randint(1, 100) code = "def %s(%s):\n" % (fn, a) code += " result = %s + %s\n" % (v1, v2) code += " value = %s * %s\n" % (v2, v3) code += " return %s\n\n" % v1 code += "class %s:\n" % cls code += " def __init__(self, %s):\n" % ia code += " self.%s = %s\n" % (v1, v2) code += " self.%s = []\n\n" % v3 code += " def %s(self, %s):\n" % (mn, ma) code += " return %s * 2\n\n" % v1 code += "import %s\n" % imp code += "from %s import %s\n\n" % (imp, random.choice(func_names)) code += "%s = [%s ** 2 for %s in range(%d) if %s > 0]\n\n" % (v1, v2, v3, n, v3) code += "try:\n" code += " %s.process()\n" % v1 code += "except %s as e:\n" % exc code += " print('Error:', %s)\n" % v2 code += "finally:\n" code += " %s.cleanup()\n\n" % v1 code += "async def %s(%s):\n" % (afn, aa) code += " await %s.fetch()\n" % v1 code += " return %s\n" % v2 all_texts.append(code) dataset_stats.append(["synthetic", "Python", "%d" % py_count]) print(" Done: %d Python samples" % py_count) # JavaScript print("Generating JavaScript code...") js_count = target_count // 4 LB = "{" RB = "}" for idx in range(js_count): fn = random.choice(func_names) a = ", ".join(random.sample(var_names, random.randint(1, 3))) v1, v2, v3 = random.sample(var_names, 3) cls = fn.title() + "Service" ia = ", ".join(random.sample(var_names, random.randint(1, 3))) mn = random.choice(func_names) ma = ", ".join(random.sample(var_names, random.randint(1, 3))) exp = ", ".join(random.sample(func_names, random.randint(1, 3))) imp_mod = random.choice(modules).replace(".", "/") code = "const %s = (%s) => %s\n" % (fn, a, LB) code += " const result = %s + %s;\n" % (v1, v2) code += " const value = %s * %s;\n" % (v2, v3) code += " return %s;\n" % v1 code += "%s;\n\n" % RB code += "class %s %s\n" % (cls, LB) code += " constructor(%s) %s\n" % (ia, LB) code += " this.%s = %s;\n" % (v1, v2) code += " this.%s = [];\n" % v3 code += " %s\n\n" % RB code += " %s(%s) %s\n" % (mn, ma, LB) code += " return %s * 2;\n" % v1 code += " %s\n" % RB code += "%s\n\n" % RB code += "async function async%s(%s) %s\n" % (fn.title(), a, LB) code += " const %s = await %s.fetch();\n" % (v1, v2) code += " return %s;\n" % v3 code += "%s\n\n" % RB code += "try %s\n" % LB code += " %s.process();\n" % v1 code += "%s catch (err) %s\n" % (RB, LB) code += " console.error(err);\n" code += "%s finally %s\n" % (RB, LB) code += " %s.cleanup();\n" % v1 code += "%s\n\n" % RB code += "export %s %s, %s %s from './%s';\n" % (LB, exp, RB, LB, imp_mod) code += "import %s %s %s from './%s';\n" % (LB, exp, RB, imp_mod) code += "const %s = %s.map(%s => %s * 2).filter(%s => %s > 0);\n" % (v1, v2, v3, v3, v3, v3) all_texts.append(code) dataset_stats.append(["synthetic", "JavaScript", "%d" % js_count]) print(" Done: %d JavaScript samples" % js_count) # Rust print("Generating Rust code...") rust_count = target_count - py_count - js_count for idx in range(rust_count): fn = random.choice(func_names) v1, v2, v3 = random.sample(var_names, 3) t1, t2, t3 = random.sample(rust_types, 3) cls = fn.title() + "Struct" trt = fn.title() + "Trait" mn = random.choice(func_names) ma = random.choice(var_names) mt = random.choice(rust_types) mrt = random.choice(rust_types) ret_type = random.choice(rust_types) args_parts = ["%s: %s" % (v, random.choice(rust_types)) for v in random.sample(var_names, random.randint(1, 3))] args = ", ".join(args_parts) new_args_parts = ["%s: %s" % (v, random.choice(rust_types)) for v in random.sample(var_names, random.randint(1, 3))] new_args = ", ".join(new_args_parts) code = "fn %s(%s) -> %s %s\n" % (fn, args, ret_type, LB) code += " let result = %s + %s;\n" % (v1, v2) code += " let value = %s * %s;\n" % (v2, v3) code += " %s\n" % v1 code += "%s\n\n" % RB code += "struct %s %s\n" % (cls, LB) code += " %s: %s,\n" % (v1, t1) code += " %s: %s,\n" % (v2, t2) code += " %s: %s,\n" % (v3, t3) code += "%s\n\n" % RB code += "impl %s %s\n" % (cls, LB) code += " fn new(%s) -> Self %s\n" % (new_args, LB) code += " Self %s %s: %s %s\n" % (LB, v1, v1, RB) code += " %s\n\n" % RB code += " fn %s(&self, %s: %s) -> %s %s\n" % (mn, ma, mt, mrt, LB) code += " self.%s\n" % v1 code += " %s\n" % RB code += "%s\n\n" % RB code += "pub trait %s %s\n" % (trt, LB) code += " fn %s(&self, %s: %s) -> %s;\n" % (random.choice(func_names), random.choice(var_names), random.choice(rust_types), random.choice(rust_types)) code += "%s\n\n" % RB code += "match %s %s\n" % (v1, LB) code += " Some(x) => %s,\n" % v2 code += " None => %s,\n" % v3 code += " _ => Default::default(),\n" code += "%s\n" % RB all_texts.append(code) dataset_stats.append(["synthetic", "Rust", "%d" % rust_count]) print(" Done: %d Rust samples" % rust_count) print("\nTotal synthetic: %d code samples" % len(all_texts)) return all_texts, dataset_stats def train_tokenizer(): print("\n" + "=" * 60) print("Bhaari AI - Phase 1: BhaariTok Tokenizer") print("=" * 60) print("Date: %s" % datetime.now().strftime("%Y-%m-%d %H:%M:%S")) has_gpu = check_gpu() # Fetch real code real_texts = fetch_real_code_data(target_count=50000) # Generate synthetic synth_texts, synth_stats = generate_synthetic_code_data(target_count=50000) all_texts = real_texts + synth_texts dataset_stats = [["codeparrot-clean", "Python", "%d" % len(real_texts)]] + synth_stats print("\nTotal training texts: %d" % len(all_texts)) if len(all_texts) == 0: print("ERROR: No training data!") return None # Use HuggingFace tokenizers library for fast BPE training print("\n" + "=" * 60) print("Training BPE Tokenizer (HuggingFace tokenizers)") print("=" * 60) from tokenizers import Tokenizer from tokenizers.models import BPE from tokenizers.trainers import BpeTrainer from tokenizers.pre_tokenizers import Split from tokenizers.normalizers import Sequence import regex # Create tokenizer with Llama 3 pattern llama3_pattern = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}{1,3}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+""" tokenizer = Tokenizer(BPE(unk_token="[UNK]")) tokenizer.pre_tokenizer = Split(pattern=llama3_pattern, behavior="isolated") # Special tokens special_tokens_list = list(SPECIAL_TOKENS.keys()) trainer = BpeTrainer( vocab_size=128000, min_frequency=2, special_tokens=special_tokens_list, show_progress=True, ) # Train on texts print("Training BPE on %d texts..." % len(all_texts)) tokenizer.train_from_iterator(all_texts, trainer=trainer) # Save output_dir = "./tokenizer_model" os.makedirs(output_dir, exist_ok=True) tokenizer.save(os.path.join(output_dir, "tokenizer.json")) # Save vocab and merges separately for compatibility vocab = tokenizer.get_vocab() print("Final vocab size: %d" % len(vocab)) # Save in our format model_data = { "vocab": vocab, "vocab_size": len(vocab), "special_tokens": SPECIAL_TOKENS, "pattern": llama3_pattern, } with open(os.path.join(output_dir, "model.json"), "w") as f: json.dump(model_data, f) print("Tokenizer saved to %s" % output_dir) # Test print("\n" + "=" * 60) print("Testing Tokenizer") print("=" * 60) test_cases = [ "def hello_world():\n print('Hello, Bhaari AI!')", "const x = (a, b) => a + b;", 'fn main() { println!("Hello"); }', "import torch\nmodel = torch.nn.Linear(10, 5)", "async function fetchData() { await fetch('/api'); }", "pub struct User { name: String, age: u32 }", ] test_results = [] for test in test_cases: encoded = tokenizer.encode(test) tokens = encoded.tokens decoded = tokenizer.decode(encoded.ids) match = test == decoded test_results.append({ "input": test, "num_tokens": len(tokens), "decoded": decoded, "match": match }) status = "OK" if match else "MISMATCH" print("%s: %s... Tokens: %d" % (status, test[:50], len(tokens))) tokenizer_stats = { "vocab_size": len(vocab), "total_merges": len(vocab) - 256 - len(SPECIAL_TOKENS), "special_tokens": len(SPECIAL_TOKENS), "special_token_list": SPECIAL_TOKENS, "training_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), } training_data_stats = { "datasets": dataset_stats, "total_samples": "%d" % len(all_texts) } # Generate report print("\n" + "=" * 60) print("Generating PDF Report") print("=" * 60) timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") report_path = "reports/bhaari_tok_phase1_%s.pdf" % timestamp os.makedirs("reports", exist_ok=True) generate_tokenizer_report( tokenizer_stats=tokenizer_stats, training_data_stats=training_data_stats, test_results=test_results, output_path=report_path ) # Upload to HF print("\n" + "=" * 60) print("Uploading to HuggingFace Hub") print("=" * 60) hf_token = os.environ.get("HF_TOKEN") if hf_token: try: repo_id = "mohit-vashishta/bhaari-tok-v1" push_to_huggingface( folder_path=output_dir, repo_id=repo_id, commit_message="BhaariTok v1 - 128K vocab %s" % datetime.now().strftime("%Y-%m-%d"), token=hf_token ) push_to_huggingface( folder_path="reports", repo_id="mohit-vashishta/bhaari-ai-reports", commit_message="Phase 1 Report %s" % datetime.now().strftime("%Y-%m-%d"), token=hf_token ) print("Uploaded to HuggingFace Hub") except Exception as e: print("Upload failed: %s" % str(e)) else: print("HF_TOKEN not set - skipping upload") # Cleanup print("\n" + "=" * 60) print("Cleaning Up Studio Machine") print("=" * 60) for d in ["data", "__pycache__", "src/__pycache__", "src/tokenizer/__pycache__", "scripts/__pycache__"]: if os.path.exists(d): shutil.rmtree(d, ignore_errors=True) print("Removed: %s" % d) print("Cleanup complete") print("\n" + "=" * 60) print("Phase 1 Complete!") print("=" * 60) print("Tokenizer trained: %d vocab" % len(vocab)) print("Model saved to: %s" % output_dir) print("Report saved to: %s" % report_path) print("GPU used: %s" % ("L40S" if has_gpu else "CPU")) print("Training samples: %d" % len(all_texts)) passed = sum(1 for t in test_results if t["match"]) print("Test cases passed: %d/%d" % (passed, len(test_results))) if hf_token: print("Uploaded to: https://huggingface.co/mohit-vashishta/bhaari-tok-v1") print("\nNext: Phase 2 - BhaariCore-1M Architecture") return tokenizer if __name__ == "__main__": train_tokenizer()