Translation
Transformers
Safetensors
Burmese
English
mytranslation
text2text-generation
Translation
Safetensors
Burmese
English
myanmartranslator
MyanmarLLM
custom_code
myanmar
Run this model with HF Jobs
Run freococo/MyTranslation_300M_Base on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/freococo/MyTranslation_300M_Base. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/freococo/MyTranslation_300M_Base on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use freococo/MyTranslation_300M_Base with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use freococo/MyTranslation_300M_Base with Transformers:
# Use a pipeline as a high-level helper # Warning: Pipeline type "translation" is no longer supported in transformers v5. # You must load the model directly (see below) or downgrade to v4.x with: # pip install "transformers<5.0.0" from transformers import pipeline pipe = pipeline("translation", model="freococo/MyTranslation_300M_Base", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForSeq2SeqLM model = AutoModelForSeq2SeqLM.from_pretrained("freococo/MyTranslation_300M_Base", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Update checkpoint-stage1-step-58000/training_codes.txt
Browse files123import osos.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727# === PHASE 1, CELL 1: Stratified Corpus Sampling Across All 33 Subsets ===import osimport randomimport timefrom collections import defaultdictfrom concurrent.futures import ThreadPoolExecutor, as_completedimport pyarrow.parquet as pqfrom google.colab import userdatafrom huggingface_hub import HfApi, HfFileSystemfrom huggingface_hub.hf_api import RepoFileREPO_ID = "freococo/myanmar-english-corpus"HF_TOKEN = userdata.get("HF_TOKEN")assert HF_TOKEN, "HF_TOKEN not found in Colab Secrets!"TOK_TEXT_FILE = "/content/mytranslation_tok_train.txt"api = HfApi(token=HF_TOKEN)fs = HfFileSystem(token=HF_TOKEN)print(f"π Listing all Parquet files in {REPO_ID}...")tree = list(api.list_repo_tree(repo_id=REPO_ID, repo_type="dataset", path_in_repo="data", recursive=True))subset_files = defaultdict(list)for item in tree:if isinstance(item, RepoFile) and item.path.endswith(".parquet"):parts = item.path.split("/")if len(parts) == 4:group, subset = parts[1], parts[2]subset_files[(group, subset)].append(item.path)print(f"π¦ Found {len(subset_files)} subsets across {sum(len(v) for v in subset_files.values())} Parquet files.")# Sampling budget (rows per subset) β 100% of small/specialized sets, balanced slices of huge setsTARGET_ROWS_BY_GROUP = {"non_myanmartranslator": 160_000, # Takes 100% of all <160k sets (musannaf, quran, proverbs, idioms, pali, taco, etc.)"MyanmarTranslator_works": 120_000, # Balanced slice per MT domain (literature, spoken, written, news, wiki, etc.)}# Give finetranslations & myanmar-xnli slightly more weight as core large parallel setsCUSTOM_QUOTA = {"finetranslations": 300_000,"myanmar-xnli": 180_000,"myanmar-literature-corpus": 150_000,"myanmar-wikipedia-corpus": 150_000,"myanmar_spoken_corpus": 150_000,"myanmar-written-corpus": 150_000,}rng = random.Random(2026)def sample_subset(group, subset, file_paths):quota = CUSTOM_QUOTA.get(subset, TARGET_ROWS_BY_GROUP[group])file_paths = sorted(file_paths)# Pick up to 6 evenly spaced files if folder has many shardsif len(file_paths) > 6:step = len(file_paths) / 6.0picked_files = [file_paths[int(i * step)] for i in range(6)]else:picked_files = file_pathsper_file_quota = max(1, (quota + len(picked_files) - 1) // len(picked_files))lines = []for fp_path in picked_files:with fs.open(f"datasets/{REPO_ID}/{fp_path}", "rb") as f:pf = pq.ParquetFile(f)n_rg = pf.num_row_groupsrg_indices = list(range(n_rg))if n_rg > 4:# Sample evenly across row groupsstep_rg = n_rg / 4.0rg_indices = sorted({rg_indices[int(i * step_rg)] for i in range(4)})collected_my, collected_en = [], []per_rg_cap = max(500, (per_file_quota + len(rg_indices) - 1) // len(rg_indices))for rg_i in rg_indices:tbl = pf.read_row_group(rg_i, columns=["myanmar_text_original", "english_text_translation"])n_r = tbl.num_rowsif n_r > per_rg_cap:stride = max(1, n_r // per_rg_cap)idx_slice = list(range(0, n_r, stride))[:per_rg_cap]tbl = tbl.take(idx_slice)d = tbl.to_pydict()collected_my.extend(d["myanmar_text_original"])collected_en.extend(d["english_text_translation"])for m, e in zip(collected_my, collected_en):if isinstance(m, str):for para in m.splitlines():p = para.strip()if p:lines.append(p)if isinstance(e, str):for para in e.splitlines():p = para.strip()if p:lines.append(p)if len(lines) >= quota * 2:breakif len(lines) >= quota * 2:breakreturn group, subset, linest0 = time.time()all_lines = []print("\nβ³ Streaming stratified samples across all 33 subsets...")with ThreadPoolExecutor(max_workers=10) as ex:futures = [ex.submit(sample_subset, grp, sub, paths)for (grp, sub), paths in sorted(subset_files.items())]for fut in as_completed(futures):grp, sub, lines = fut.result()all_lines.extend(lines)print(f" β {grp}/{sub:<44} -> {len(lines):>8,} lines")rng.shuffle(all_lines)with open(TOK_TEXT_FILE, "w", encoding="utf-8") as f:for ln in all_lines:f.write(ln + "\n")mb = os.path.getsize(TOK_TEXT_FILE) / 1e6print(f"\nπ Saved stratified tokenizer corpus: {TOK_TEXT_FILE}")print(f" β’ Total lines: {len(all_lines):,} | Size: {mb:.1f} MB | Elapsed: {time.time() - t0:.1f}s")# === PHASE 1, CELL 2 (FIXED PRE-FLIGHT): Train 49k & 65k Unigram+ByteFallback & benchmark ===import osimport timeimport pyarrow.parquet as pqimport sentencepiece as spmfrom google.colab import userdatafrom huggingface_hub import HfApi, HfFileSystem, hf_hub_downloadfrom huggingface_hub.hf_api import RepoFileHF_TOKEN = userdata.get("HF_TOKEN")TOK_TEXT_FILE = "/content/mytranslation_tok_train.txt"TOK_OUT_DIR = "/content/mytranslation_tokenizers"os.makedirs(TOK_OUT_DIR, exist_ok=True)CONTROL_SYMBOLS = ["<2my>", "<2en>", "<formal>", "<spoken>", "<bt>", "<denoise>", "<mask>"]# 0. Pre-flight check on first 5,000 lines to verify '\n' and control tokens roundtrip 100%mini_txt = "/content/_mini_preflight.txt"with open(TOK_TEXT_FILE, "r", encoding="utf-8") as fin, open(mini_txt, "w", encoding="utf-8") as fout:for i, line in enumerate(fin):fout.write(line)if i >= 5000:breakfout.write("Hello world.\nαααΊαΉααα¬αα« αααΊαα»α¬α\n12345\n")spm.SentencePieceTrainer.train(input=mini_txt,model_prefix="/content/_mini_tok",vocab_size=1000,model_type="unigram",character_coverage=0.9999,byte_fallback=True,split_digits=True,normalization_rule_name="identity",remove_extra_whitespaces=False,allow_whitespace_only_pieces=True,unk_id=0, bos_id=1, eos_id=2, pad_id=3,user_defined_symbols=CONTROL_SYMBOLS,)sp_pre = spm.SentencePieceProcessor()sp_pre.load("/content/_mini_tok.model")for test_s in ["Hello\n\nWorld", "αααΊαΉααα¬αα«\n\nαα±αα±α¬ααΊαΈαα¬αΈ", "<2my> <formal> Hello\n123"]:dec_s = sp_pre.decode_ids(sp_pre.encode_as_ids(test_s))assert dec_s == test_s, f"Pre-flight newline roundtrip failed: {repr(test_s)} -> {repr(dec_s)}"print("β Pre-flight check PASSED: '\\n' and control tokens roundtrip 100.0% identically!")# 1. Train Candidate A (49,152) and Candidate B (65,536)trained_models = {}for label, v_size in [("MyTranslation-49k", 49152), ("MyTranslation-65k", 65536)]:prefix = os.path.join(TOK_OUT_DIR, f"tok_{v_size}")print(f"\nποΈ Training {label} (vocab_size={v_size:,}) on {TOK_TEXT_FILE} ...")t0 = time.time()spm.SentencePieceTrainer.train(input=TOK_TEXT_FILE,model_prefix=prefix,vocab_size=v_size,model_type="unigram",character_coverage=0.9999,byte_fallback=True,split_digits=True,normalization_rule_name="identity",remove_extra_whitespaces=False,allow_whitespace_only_pieces=True,max_sentencepiece_length=16,input_sentence_size=2_500_000,shuffle_input_sentence=True,num_threads=max(4, os.cpu_count() or 4),unk_id=0, bos_id=1, eos_id=2, pad_id=3,user_defined_symbols=CONTROL_SYMBOLS,)sp_m = spm.SentencePieceProcessor()sp_m.load(prefix + ".model")trained_models[label] = (sp_m, prefix + ".model")print(f" β {label} trained in {time.time() - t0:.1f}s | actual vocab={sp_m.get_piece_size():,}")# Load old 210M-Pro tokenizer for baseline comparisonold_tok_path = hf_hub_download(repo_id="freococo/MyanmarTranslator-210M-Pro", filename="tokenizer.model", token=HF_TOKEN)sp_old = spm.SentencePieceProcessor()sp_old.load(old_tok_path)all_toks = {"Old-210M-65k": sp_old,"MyTrans-49k": trained_models["MyTranslation-49k"][0],"MyTrans-65k": trained_models["MyTranslation-65k"][0],}# 2. Side-by-Side Benchmark across the exact 8 subsetsCORPUS_REPO = "freococo/myanmar-english-corpus"api = HfApi(token=HF_TOKEN)fs = HfFileSystem(token=HF_TOKEN)TARGETS = ["data/MyanmarTranslator_works/myanmar-literature-corpus","data/non_myanmartranslator/finetranslations","data/non_myanmartranslator/alpaca_myanmar_burmese_taco","data/non_myanmartranslator/musannaf_ibn_abi_shaybah","data/non_myanmartranslator/arabic_names_with_myanmar_and_english_transliteration","data/non_myanmartranslator/myanmar-english-pali-dictionary","data/non_myanmartranslator/quran_written_spoken_myanmar_english","data/non_myanmartranslator/myanmar_proverbs_lexicon",]print("\n" + "=" * 116)print(f"{'SUBSET':<38} {'SIDE':<4} | {'OLD CH/T':>8} {'OLD BYT%':>8} {'OLD RT%':>7} | {'49K CH/T':>8} {'49K BYT%':>8} {'49K RT%':>7} | {'65K CH/T':>8} {'65K BYT%':>8} {'65K RT%':>7}")print("=" * 116)for folder_path in TARGETS:tree = list(api.list_repo_tree(repo_id=CORPUS_REPO, repo_type="dataset", path_in_repo=folder_path))first_pq = next(item.path for item in tree if isinstance(item, RepoFile) and item.path.endswith(".parquet"))with fs.open(f"datasets/{CORPUS_REPO}/{first_pq}", "rb") as f:tbl = pq.ParquetFile(f).read_row_group(0).slice(0, 500).to_pydict()subset = folder_path.split("/")[-1][:37]for side, col in [("MY", "myanmar_text_original"), ("EN", "english_text_translation")]:texts = [t for t in tbl[col] if isinstance(t, str) and t.strip()]row_metrics = {}for mname, sp_inst in all_toks.items():tot_ch, tot_tok, tot_byte, rt_ok = 0, 0, 0, 0for t in texts:ids = sp_inst.encode_as_ids(t)dec = sp_inst.decode_ids(ids)tot_ch += len(t)tot_tok += len(ids)tot_byte += sum(1 for i in ids if sp_inst.is_byte(i))if dec == t:rt_ok += 1row_metrics[mname] = (tot_ch / max(1, tot_tok),100.0 * tot_byte / max(1, tot_tok),100.0 * rt_ok / max(1, len(texts)),)o = row_metrics["Old-210M-65k"]m49 = row_metrics["MyTrans-49k"]m65 = row_metrics["MyTrans-65k"]print(f"{subset:<38} {side:<4} | "f"{o[0]:>8.2f} {o[1]:>7.2f}% {o[2]:>6.1f}% | "f"{m49[0]:>8.2f} {m49[1]:>7.2f}% {m49[2]:>6.1f}% | "f"{m65[0]:>8.2f} {m65[1]:>7.2f}% {m65[2]:>6.1f}%")print("\nπ Control Token IDs check (MyTrans-65k):")for sym in ["<unk>", "<s>", "</s>", "<pad>"] + CONTROL_SYMBOLS:print(f" {sym:<10} -> {trained_models['MyTranslation-65k'][0].piece_to_id(sym)}")# === PHASE 1 BACKUP: Convert tok_train.txt -> Parquet & upload package to freococo/mytrans_backup ===import osimport shutilimport timeimport pyarrow as paimport pyarrow.parquet as pqfrom google.colab import userdatafrom huggingface_hub import HfApi, create_repoHF_TOKEN = userdata.get("HF_TOKEN")assert HF_TOKEN, "HF_TOKEN not found in Colab Secrets!"BACKUP_REPO = "freococo/mytrans_backup"TXT_PATH = "/content/mytranslation_tok_train.txt"TOK_DIR = "/content/mytranslation_tokenizers"PKG_DIR = "/content/mytrans_backup_pkg"assert os.path.exists(TXT_PATH), f"Missing {TXT_PATH}"os.makedirs(os.path.join(PKG_DIR, "tokenizers", "49k"), exist_ok=True)os.makedirs(os.path.join(PKG_DIR, "tokenizers", "65k"), exist_ok=True)# 1. Stream-convert /content/mytranslation_tok_train.txt -> compressed Parquet (low RAM)pq_out = os.path.join(PKG_DIR, "tok_train_corpus.parquet")schema = pa.schema([("text", pa.string())])writer = pq.ParquetWriter(pq_out, schema, compression="zstd")print("π¦ Converting mytranslation_tok_train.txt -> tok_train_corpus.parquet (zstd) ...")t0 = time.time()buf = []total_lines = 0CHUNK = 500_000with open(TXT_PATH, "r", encoding="utf-8") as f:for line in f:s = line.rstrip("\r\n")if not s:continuebuf.append(s)total_lines += 1if len(buf) >= CHUNK:writer.write_table(pa.Table.from_pydict({"text": buf}, schema=schema))buf.clear()print(f" Written {total_lines:,} lines...")if buf:writer.write_table(pa.Table.from_pydict({"text": buf}, schema=schema))buf.clear()writer.close()pq_mb = os.path.getsize(pq_out) / 1e6print(f"β Parquet built: {total_lines:,} lines | {pq_mb:.1f} MB in {time.time() - t0:.1f}s")# 2. Copy both 49k and 65k tokenizers into package folderfor sz, tag in [(49152, "49k"), (65536, "65k")]:for ext in (".model", ".vocab"):src = os.path.join(TOK_DIR, f"tok_{sz}{ext}")dst = os.path.join(PKG_DIR, "tokenizers", tag, f"tokenizer{ext}")assert os.path.exists(src), f"Missing {src}"shutil.copyfile(src, dst)readme_txt = f"""---pretty_name: MyTranslation Project Backuplanguage:- my- en---# `freococo/mytrans_backup`Private project backup for **MyTranslation** (tokenizer training corpus, trained SentencePiece models, and tokenized memmaps).## Contents- `tok_train_corpus.parquet` β {total_lines:,} stratified lines across all 33 subsets of `freococo/myanmar-english-corpus` ({pq_mb:.1f} MB, zstd).- `tokenizers/49k/tokenizer.model` & `.vocab` β `49,152` Unigram + byte-fallback (`identity` norm, newline-preserving).- `tokenizers/65k/tokenizer.model` & `.vocab` β `65,536` Unigram + byte-fallback (`identity` norm, newline-preserving, **winner on compression**).## Special & Control Token IDs- `0`: `<unk>` | `1`: `<s>` | `2`: `</s>` | `3`: `<pad>`- `4`: `<2my>` | `5`: `<2en>` | `6`: `<formal>` | `7`: `<spoken>` | `8`: `<bt>` | `9`: `<denoise>` | `10`: `<mask>`"""with open(os.path.join(PKG_DIR, "README.md"), "w", encoding="utf-8") as f:f.write(readme_txt)# 3. Create private repo & upload entire packageapi = HfApi(token=HF_TOKEN)create_repo(BACKUP_REPO, repo_type="dataset", private=True, exist_ok=True)print(f"\nβοΈ Uploading package to private repo https://huggingface.co/datasets/{BACKUP_REPO} ...")t1 = time.time()api.upload_folder(folder_path=PKG_DIR,repo_id=BACKUP_REPO,repo_type="dataset",commit_message="Backup stratified tokenizer corpus Parquet + 49k & 65k MyTranslation tokenizers",)print(f"π Backup complete in {time.time() - t1:.1f}s! https://huggingface.co/datasets/{BACKUP_REPO}")# === PHASE 1C, CELL 1: Tokenize all 48.35M+ rows with MyTrans-65k into canonical uint16 memmaps ===import gcimport jsonimport osimport shutilimport timefrom collections import defaultdictfrom concurrent.futures import ThreadPoolExecutorimport numpy as npimport pyarrow.parquet as pqimport sentencepiece as spmfrom google.colab import userdatafrom huggingface_hub import HfApi, hf_hub_downloadfrom huggingface_hub.hf_api import RepoFileHF_TOKEN = userdata.get("HF_TOKEN")assert HF_TOKEN, "HF_TOKEN not found in Colab Secrets!"CORPUS_REPO = "freococo/myanmar-english-corpus"BACKUP_REPO = "freococo/mytrans_backup"# Clean up Phase 1 raw txt/pkg to maximize disk spacefor old_p in ["/content/mytranslation_tok_train.txt", "/content/mytrans_backup_pkg", "/content/_mini_preflight.txt"]:if os.path.isdir(old_p):shutil.rmtree(old_p, ignore_errors=True)elif os.path.exists(old_p):os.remove(old_p)MEMMAP_DIR = "/content/mytrans_memmap_65k"DL_CACHE_DIR = "/content/_tmp_pq_cache"os.makedirs(MEMMAP_DIR, exist_ok=True)os.makedirs(DL_CACHE_DIR, exist_ok=True)# Load MyTrans-65k (local if present, else pull from freococo/mytrans_backup)LOCAL_TOK = "/content/mytranslation_tokenizers/tok_65536.model"if os.path.exists(LOCAL_TOK):TOK_PATH = LOCAL_TOKelse:TOK_PATH = hf_hub_download(repo_id=BACKUP_REPO, repo_type="dataset", filename="tokenizers/65k/tokenizer.model", token=HF_TOKEN)shutil.copyfile(TOK_PATH, os.path.join(MEMMAP_DIR, "tokenizer.model"))sp = spm.SentencePieceProcessor()sp.load(TOK_PATH)assert sp.get_piece_size() == 65536, f"Expected 65536 vocab, got {sp.get_piece_size()}"N_THREADS = max(4, os.cpu_count() or 8)try:_ = sp.encode(["test"], out_type=int, num_threads=N_THREADS)USE_SP_THREADS = Trueprint(f"β‘ SentencePiece native C++ batch encode enabled (num_threads={N_THREADS})")except TypeError:USE_SP_THREADS = Falseprint(f"β‘ SentencePiece fallback encode (using {N_THREADS} threads via pool)")def encode_batch(texts: list[str]) -> list[list[int]]:if USE_SP_THREADS:return sp.encode(texts, out_type=int, num_threads=N_THREADS)return [sp.encode_as_ids(t) for t in texts]# 1. Discover all 247 Parquet files across all 33 subsetsapi = HfApi(token=HF_TOKEN)tree = list(api.list_repo_tree(repo_id=CORPUS_REPO, repo_type="dataset", path_in_repo="data", recursive=True))subset_files = defaultdict(list)for item in tree:if isinstance(item, RepoFile) and item.path.endswith(".parquet"):parts = item.path.split("/")if len(parts) == 4:subset_files[(parts[1], parts[2])].append(item.path)all_subsets = sorted(subset_files.keys())subset_to_id = {f"{g}/{s}": idx for idx, (g, s) in enumerate(all_subsets)}print(f"π¦ Found {len(all_subsets)} subsets across {sum(len(v) for v in subset_files.values())} Parquet files")# Style & BT flags bitmaskFLAG_BT = 1 # bit 0: MyanmarTranslator_works synthetic EN sideFLAG_FORMAL = 2 # bit 1: Formal/written styleFLAG_SPOKEN = 4 # bit 2: Spoken/conversational styleFORMAL_SUBSETS = {"myanmar-written-corpus","jw_myanmar_bible_dataset","tipitaka_myanmar_translation_books","myanmar-wikipedia-corpus","myanmar-wikipedia-dataset","combined_4_repos","musannaf_ibn_abi_shaybah","imam_albani_weaknfab_series_dataset","Quran_English_Myanmar_Parrelel_Corpus",}SPOKEN_SUBSETS = {"myanmar_spoken_corpus","mig-english-myanmar-translation","MT-myanmar-english","english-myanmar",}MAX_SEQ_TOKENS = 2040 # Leaves room for prefix control tokens + EOS inside max_seq_len=2048INDEX_DTYPE = np.dtype([("my_off", np.uint64),("my_len", np.uint16),("en_off", np.uint64),("en_len", np.uint16),("subset_id", np.uint8),("flags", np.uint8),])# Build flat ordered task list: (group, subset, subset_id, file_idx_in_subset, remote_path)tasks = []for g, s in all_subsets:sid = subset_to_id[f"{g}/{s}"]for f_i, rp in enumerate(sorted(subset_files[(g, s)])):tasks.append((g, s, sid, f_i, rp))def download_one(remote_path: str) -> str:return hf_hub_download(repo_id=CORPUS_REPO,repo_type="dataset",filename=remote_path,local_dir=DL_CACHE_DIR,token=HF_TOKEN,)# Open binary writerstrain_my_f = open(os.path.join(MEMMAP_DIR, "train_my.bin"), "wb")train_en_f = open(os.path.join(MEMMAP_DIR, "train_en.bin"), "wb")val_my_f = open(os.path.join(MEMMAP_DIR, "val_my.bin"), "wb")val_en_f = open(os.path.join(MEMMAP_DIR, "val_en.bin"), "wb")train_my_off = 0train_en_off = 0val_my_off = 0val_en_off = 0train_idx_chunks = []val_idx_chunks = []subset_stats = defaultdict(lambda: {"train_rows": 0, "val_rows": 0, "my_toks": 0, "en_toks": 0})t_global = time.time()total_rows_seen = 0total_skipped = 0# Prefetch pipeline (1 ahead)with ThreadPoolExecutor(max_workers=2) as dl_pool:next_fut = dl_pool.submit(download_one, tasks[0][4])for t_idx, (g, s, sid, f_i, rp) in enumerate(tasks):local_pq = next_fut.result()if t_idx + 1 < len(tasks):next_fut = dl_pool.submit(download_one, tasks[t_idx + 1][4])t_file = time.time()pf = pq.ParquetFile(local_pq)file_total_rows = pf.metadata.num_rows# Deterministic stratified val selection ONLY from the first file of each subsetval_set_local = set()if f_i == 0 and file_total_rows >= 20:val_target = min(1000, max(20, file_total_rows // 50))stride = max(1, file_total_rows // val_target)val_set_local = set(range(0, file_total_rows, stride)[:val_target])base_flag = FLAG_BT if g == "MyanmarTranslator_works" else 0if s in FORMAL_SUBSETS:base_flag |= FLAG_FORMALelif s in SPOKEN_SUBSETS:base_flag |= FLAG_SPOKENlocal_row_cursor = 0t_idx_buf = []v_idx_buf = []for batch in pf.iter_batches(batch_size=40_000, columns=["myanmar_text_original", "english_text_translation"]):my_raw = batch.column(0).to_pylist()en_raw = batch.column(1).to_pylist()valid_pairs = []valid_pos = []for k, (m, e) in enumerate(zip(my_raw, en_raw)):r_pos = local_row_cursor + kif isinstance(m, str) and isinstance(e, str):ms, es = m.strip(), e.strip()if ms and es:valid_pairs.append((ms, es))valid_pos.append(r_pos)else:total_skipped += 1else:total_skipped += 1local_row_cursor += len(my_raw)if not valid_pairs:continuemy_tok_lists = encode_batch([p[0] for p in valid_pairs])en_tok_lists = encode_batch([p[1] for p in valid_pairs])t_my_arrays, t_en_arrays = [], []v_my_arrays, v_en_arrays = [], []for r_pos, m_ids, e_ids in zip(valid_pos, my_tok_lists, en_tok_lists):if not m_ids or not e_ids:total_skipped += 1continueif len(m_ids) > MAX_SEQ_TOKENS:m_ids = m_ids[:MAX_SEQ_TOKENS]if len(e_ids) > MAX_SEQ_TOKENS:e_ids = e_ids[:MAX_SEQ_TOKENS]m_arr = np.asarray(m_ids, dtype=np.uint16)e_arr = np.asarray(e_ids, dtype=np.uint16)ml = len(m_arr)el = len(e_arr)row_flag = base_flagif s == "quran_written_spoken_myanmar_english":row_flag |= (FLAG_FORMAL if (r_pos % 2 == 0) else FLAG_SPOKEN)elif s == "myanmar_quran_parallel_human_vs_ai_native":row_flag |= (FLAG_FORMAL if (r_pos % 3 in (0, 1)) else FLAG_SPOKEN)key = f"{g}/{s}"subset_stats[key]["my_toks"] += mlsubset_stats[key]["en_toks"] += elif r_pos in val_set_local:v_idx_buf.append((val_my_off, ml, val_en_off, el, sid, row_flag))v_my_arrays.append(m_arr)v_en_arrays.append(e_arr)val_my_off += mlval_en_off += elsubset_stats[key]["val_rows"] += 1else:t_idx_buf.append((train_my_off, ml, train_en_off, el, sid, row_flag))t_my_arrays.append(m_arr)t_en_arrays.append(e_arr)train_my_off += mltrain_en_off += elsubset_stats[key]["train_rows"] += 1if t_my_arrays:train_my_f.write(np.concatenate(t_my_arrays).tobytes())train_en_f.write(np.concatenate(t_en_arrays).tobytes())if v_my_arrays:val_my_f.write(np.concatenate(v_my_arrays).tobytes())val_en_f.write(np.concatenate(v_en_arrays).tobytes())total_rows_seen += len(my_raw)if t_idx_buf:train_idx_chunks.append(np.asarray(t_idx_buf, dtype=INDEX_DTYPE))if v_idx_buf:val_idx_chunks.append(np.asarray(v_idx_buf, dtype=INDEX_DTYPE))# Remove temporary downloaded Parquet file immediately to keep disk lowif os.path.exists(local_pq):os.remove(local_pq)if (t_idx + 1) % 10 == 0 or (t_idx + 1) == len(tasks):elapsed = time.time() - t_globalrate = total_rows_seen / max(1e-3, elapsed)tot_tok_b = (train_my_off + train_en_off + val_my_off + val_en_off) / 1e9print(f" [{t_idx + 1:3d}/{len(tasks)}] {g}/{s:<38} | "f"Rows: {total_rows_seen:>10,} ({rate:,.0f} rows/s) | "f"Tokens: {tot_tok_b:.2f}B | Elapsed: {elapsed/60:.1f}m")train_my_f.close()train_en_f.close()val_my_f.close()val_en_f.close()shutil.rmtree(DL_CACHE_DIR, ignore_errors=True)train_index = np.concatenate(train_idx_chunks) if train_idx_chunks else np.empty(0, dtype=INDEX_DTYPE)val_index = np.concatenate(val_idx_chunks) if val_idx_chunks else np.empty(0, dtype=INDEX_DTYPE)del train_idx_chunks, val_idx_chunksgc.collect()np.save(os.path.join(MEMMAP_DIR, "train_index.npy"), train_index)np.save(os.path.join(MEMMAP_DIR, "val_index.npy"), val_index)meta = {"vocab_size": 65536,"max_seq_tokens": MAX_SEQ_TOKENS,"special_tokens": {"unk": 0, "bos": 1, "eos": 2, "pad": 3,"2my": 4, "2en": 5, "formal": 6, "spoken": 7, "bt": 8, "denoise": 9, "mask": 10,},"flags": {"FLAG_BT": FLAG_BT, "FLAG_FORMAL": FLAG_FORMAL, "FLAG_SPOKEN": FLAG_SPOKEN},"subset_to_id": subset_to_id,"id_to_subset": {str(v): k for k, v in subset_to_id.items()},"totals": {"train_rows": int(len(train_index)),"val_rows": int(len(val_index)),"skipped_rows": int(total_skipped),"train_my_tokens": int(train_my_off),"train_en_tokens": int(train_en_off),"val_my_tokens": int(val_my_off),"val_en_tokens": int(val_en_off),},"per_subset": dict(subset_stats),}with open(os.path.join(MEMMAP_DIR, "meta.json"), "w", encoding="utf-8") as f:json.dump(meta, f, indent=2)# Verify memmap roundtrip integrity on random train & val entriestr_my_mm = np.memmap(os.path.join(MEMMAP_DIR, "train_my.bin"), dtype=np.uint16, mode="r")tr_en_mm = np.memmap(os.path.join(MEMMAP_DIR, "train_en.bin"), dtype=np.uint16, mode="r")for probe_i in [0, len(train_index) // 2, len(train_index) - 1]:rec = train_index[probe_i]m_dec = sp.decode_ids(tr_my_mm[int(rec["my_off"]) : int(rec["my_off"]) + int(rec["my_len"])].tolist())e_dec = sp.decode_ids(tr_en_mm[int(rec["en_off"]) : int(rec["en_off"]) + int(rec["en_len"])].tolist())assert m_dec and e_dec, f"Empty decode at {probe_i}"disk_gb = sum(os.path.getsize(os.path.join(MEMMAP_DIR, fn)) for fn in os.listdir(MEMMAP_DIR)) / 1e9print("\n" + "=" * 95)print(f"π TOKENIZATION COMPLETE in {(time.time() - t_global)/60:.1f} min! Saved to: {MEMMAP_DIR}")print(f" β’ Train rows : {len(train_index):,} | Val rows: {len(val_index):,} | Skipped: {total_skipped:,}")print(f" β’ Train tokens: MY={train_my_off/1e9:.3f}B + EN={train_en_off/1e9:.3f}B = {(train_my_off+train_en_off)/1e9:.3f}B tokens")print(f" β’ Total Memmap Disk Size: {disk_gb:.2f} GB")print("=" * 95)# === PHASE 1C, CELL 2: Backup tokenized 48.35M memmap to freococo/mytrans_backup/tokenized_65k/ ===import osimport timefrom google.colab import userdatafrom huggingface_hub import HfApiHF_TOKEN = userdata.get("HF_TOKEN")BACKUP_REPO = "freococo/mytrans_backup"MEMMAP_DIR = "/content/mytrans_memmap_65k"assert os.path.exists(os.path.join(MEMMAP_DIR, "train_index.npy")), "Run Cell 1 first!"api = HfApi(token=HF_TOKEN)print("π¦ Files to upload:")for fn in sorted(os.listdir(MEMMAP_DIR)):fp = os.path.join(MEMMAP_DIR, fn)print(f" β’ {fn:<20} {os.path.getsize(fp)/1e9:.3f} GB")print(f"\nβοΈ Uploading {MEMMAP_DIR} -> {BACKUP_REPO}/tokenized_65k/ ...")t0 = time.time()api.upload_folder(folder_path=MEMMAP_DIR,path_in_repo="tokenized_65k",repo_id=BACKUP_REPO,repo_type="dataset",commit_message="Backup canonical uint16 tokenized 48.35M+ memmap (MyTrans-65k)",)print(f"π Uploaded tokenized_65k in {(time.time() - t0)/60:.1f} min! https://huggingface.co/datasets/{BACKUP_REPO}")import osos.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
checkpoint-stage1-step-58000/training_codes.txt+724