Spaces:
Running
Running
Upload folder using huggingface_hub
Browse filesFiles changed (37)
- ocr-training/scripts/audit_v25_submissions.pyAdded+111
- ocr-training/scripts/benchmark_orchestrator.pyAdded+512
- ocr-training/scripts/benchmark_worker.pyAdded+351
- ocr-training/scripts/build_dict_v25.pyAdded+234
- ocr-training/scripts/dict_extension_v24.py+2
- ocr-training/scripts/dict_extension_v25.pyAdded+73
- ocr-training/scripts/download_v24_zip.py+2-2
- ocr-training/scripts/download_v25_stage1.pyAdded+187
- ocr-training/scripts/download_v25_stage2.pyAdded+211
- ocr-training/scripts/download_v25_stage3.pyAdded+181
- ocr-training/scripts/dry_run_v25_scheduler.pyAdded+155
- ocr-training/scripts/eval_stage3_summary.pyAdded+47
- ocr-training/scripts/eval_stages_summary.pyAdded+34
- ocr-training/scripts/export_v25.pyAdded+58
- ocr-training/scripts/generate_comparative_report.pyAdded+142
- ocr-training/scripts/generate_data.py+76-24
- ocr-training/scripts/generate_detector_data_v2.py+1-1
- ocr-training/scripts/get_live_log.py+2-2
- ocr-training/scripts/kaggle_auth.pyAdded+44
- ocr-training/scripts/kaggle_ops.py+5-5
- ocr-training/scripts/kaggle_train_det.py+4-5
- ocr-training/scripts/kaggle_train_rec_v25.pyAdded+268
- ocr-training/scripts/kaggle_watchdog_v24.py+3-2
- ocr-training/scripts/kaggle_watchdog_v25.pyAdded+304
- ocr-training/scripts/monitor_v25_kernel.pyAdded+141
- ocr-training/scripts/orchestrate_v25_lightning.pyAdded+309
- ocr-training/scripts/prepare_benchmark_notebook.pyAdded+644
- ocr-training/scripts/prepare_v25_kaggle.pyAdded+1039
- ocr-training/scripts/run_benchmark_cloud.pyAdded+252
- ocr-training/scripts/run_kaggle_benchmark.pyAdded+177
- ocr-training/scripts/run_lightning_remote.py+1-1
- ocr-training/scripts/surgery_v25_weights.pyAdded+234
- ocr-training/scripts/test_kernel_mount.pyAdded+78
- ocr-training/scripts/upload_v25_stage1_dataset.pyAdded+40
- ocr-training/scripts/upload_v25_stage2_dataset.pyAdded+40
- ocr-training/scripts/v25_quota_watchdog_and_resume.pyAdded+147
- ocr-training/scripts/validate_unicode_source_labels.py+3-3
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111#!/usr/bin/env python3# -*- coding: utf-8 -*-"""Audit generated V25 Kaggle submissions for syntax, safety, and invariants."""
import osimport sysimport jsonimport astimport yaml
if sys.stdout and hasattr(sys.stdout, 'reconfigure'): sys.stdout.reconfigure(encoding='utf-8')
TRAINING_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def audit(): stages = [1, 2, 3] for st in stages: nb_path = os.path.join(TRAINING_DIR, 'output', f'kaggle_v25_stage{st}_submission', f'paddleocr_cham_v25_stage{st}.ipynb') meta_path = os.path.join(TRAINING_DIR, 'output', f'kaggle_v25_stage{st}_submission', 'kernel-metadata.json') with open(nb_path, 'r', encoding='utf-8') as f: nb = json.load(f) with open(meta_path, 'r', encoding='utf-8') as f: meta = json.load(f) print(f"=== STAGE {st} AUDIT ===") assert meta['accelerator'] == 'NvidiaTeslaT4', f"Stage {st}: wrong accelerator" assert meta['machine_shape'] == 'NvidiaTeslaT4', f"Stage {st}: wrong machine_shape" print(f" • Metadata accelerator: {meta['accelerator']}") print(f" • Kernel sources : {meta.get('kernel_sources')}") print(f" • Dataset sources : {meta.get('dataset_sources')}") code_cells = [c for c in nb['cells'] if c['cell_type'] == 'code'] print(f" • Total code cells : {len(code_cells)}") full_nb_text = '' for idx, c in enumerate(code_cells): src = ''.join(c['source']) full_nb_text += src + '\n' # If cell writes a file via %%writefile if src.startswith('%%writefile'): first_line = src.splitlines()[0] target_filename = first_line.split()[-1] body = '\n'.join(src.splitlines()[1:]) if target_filename.endswith('.py'): try: ast.parse(body) except SyntaxError as e: print(f"❌ SyntaxError in embedded file {target_filename} (Stage {st} Cell {idx+1}): {e}") return 1 elif target_filename.endswith('.json'): try: json.loads(body) except json.JSONDecodeError as e: print(f"❌ JSONDecodeError in {target_filename} (Stage {st} Cell {idx+1}): {e}") return 1 elif target_filename.endswith('.yml') or target_filename.endswith('.yaml'): try: yaml.safe_load(body) except Exception as e: print(f"❌ YAMLError in {target_filename} (Stage {st} Cell {idx+1}): {e}") return 1 continue
# Standard Python cell: filter jupyter magics and shell continuations py_lines = [] in_multiline_shell = False for line in src.splitlines(): sline = line.strip() if in_multiline_shell: if not sline.endswith('\\'): in_multiline_shell = False continue if sline.startswith('!') or sline.startswith('%'): if sline.endswith('\\'): in_multiline_shell = True continue py_lines.append(line) py_code = '\n'.join(py_lines) try: ast.parse(py_code) except SyntaxError as e: print(f"❌ SyntaxError in Stage {st} Cell {idx+1}: {e}") print("Code snippet:\n", py_code) return 1 # Check invariants assert "os.walk('/kaggle')" not in full_nb_text, f"Stage {st} still contains os.walk('/kaggle')!" assert 'Global.epoch_num=40' in full_nb_text, f"Stage {st} missing Global.epoch_num=40!" if st == 1: assert 'Global.stage_end_epoch=12' in full_nb_text, "Stage 1 missing Global.stage_end_epoch=12" assert 'Global.pretrained_model=' in full_nb_text, "Stage 1 missing Global.pretrained_model" assert 'cham_v25_val_freeze.zip' in full_nb_text, "Stage 1 missing cham_v25_val_freeze.zip" elif st == 2: assert 'Global.stage_end_epoch=22' in full_nb_text, "Stage 2 missing Global.stage_end_epoch=22" assert 'Global.checkpoints=' in full_nb_text, "Stage 2 missing Global.checkpoints" assert 'cham_v25_val_freeze.zip' in full_nb_text, "Stage 2 missing cham_v25_val_freeze.zip" elif st == 3: assert 'Global.stage_end_epoch=40' in full_nb_text, "Stage 3 missing Global.stage_end_epoch=40" assert 'Global.checkpoints=' in full_nb_text, "Stage 3 missing Global.checkpoints"
print(f"✅ Stage {st} PASS 100% (AST Syntax, Invariants, Deterministic Paths)\n")
print("🎉 ALL STAGES (1, 2, 3) VERIFIED 100% VALID AND COMPLIANT!") return 0
if __name__ == '__main__': sys.exit(audit())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512#!/usr/bin/env python3# -*- coding: utf-8 -*-"""Automated Multi-GPU Benchmark & Profiling Orchestrator.Discovers optimal num_workers, sweeps batch sizes, performs binary search on OOM,and computes 40-epoch economic projections (Time, Cost, IPS/$)."""
import osimport sysimport timeimport jsonimport argparseimport subprocessimport shutil
if sys.stdout and hasattr(sys.stdout, 'reconfigure'): try: sys.stdout.reconfigure(encoding='utf-8') except Exception: passif sys.stderr and hasattr(sys.stderr, 'reconfigure'): try: sys.stderr.reconfigure(encoding='utf-8') except Exception: pass
PRICING_TABLE = { "A100": 2.19, "A100-SXM4-40GB": 2.19, "NVIDIA A100": 2.19, "L4": 0.79, "NVIDIA L4": 0.79, "L40S": 2.14, "NVIDIA L40S": 2.14, "T4": 0.40, "NVIDIA T4": 0.40,}
TOTAL_DATASET_SAMPLES = 250000TOTAL_EPOCHS = 40TOTAL_TRAIN_SAMPLES = TOTAL_DATASET_SAMPLES * TOTAL_EPOCHS # 10,000,000
def detect_gpu_name(): try: res = subprocess.run( ["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"], capture_output=True, text=True, timeout=2.0 ) if res.returncode == 0 and res.stdout.strip(): return res.stdout.strip().split("\n")[0] except Exception: pass return "Unknown_GPU"
def round_to_multiple_of_32(val): return max(32, (int(val) // 32) * 32)
def round_to_multiple_of_16(val): return max(16, (int(val) // 16) * 16)
def run_single_trial(python_bin, worker_script, config_path, batch_size, num_workers, warmup_steps, measure_steps, output_dir): trial_json = os.path.join(output_dir, f"trial_b{batch_size}_w{num_workers}.json") if os.path.exists(trial_json): try: os.remove(trial_json) except Exception: pass
cmd = [ python_bin, worker_script, "-c", config_path, "-b", str(batch_size), "-w", str(num_workers), "--warmup_steps", str(warmup_steps), "--measure_steps", str(measure_steps), "-o", trial_json ]
print(f"\n>>> [Trial] Launching subprocess: Batch={batch_size}, Workers={num_workers} (Warmup={warmup_steps}, Measure={measure_steps})", flush=True) t0 = time.time() res = subprocess.run(cmd) elapsed = time.time() - t0
if os.path.exists(trial_json): try: with open(trial_json, 'r', encoding='utf-8') as f: data = json.load(f) data["elapsed_wall_time"] = round(elapsed, 2) return data except Exception as e: print(f"Failed to read trial json: {e}")
# Fallback if trial json was not written status = "OOM" if res.returncode in (137, -9) else "CRASH" return { "batch_size": batch_size, "num_workers": num_workers, "warmup_steps": warmup_steps, "measure_steps": measure_steps, "status": status, "ips": 0.0, "avg_reader_cost": 0.0, "avg_batch_cost": 0.0, "reader_ratio": 0.0, "peak_vram_mb": 0.0, "total_vram_mb": 0.0, "vram_pct": 0.0, "avg_gpu_util": 0.0, "avg_cpu_pct": 0.0, "error": f"Process exited with code {res.returncode}", "elapsed_wall_time": round(elapsed, 2) }
def compute_economics(trial, cost_per_hour): ips = trial.get("ips", 0.0) if ips > 0: est_hours = TOTAL_TRAIN_SAMPLES / (ips * 3600.0) est_cost = est_hours * cost_per_hour ips_per_dollar = ips / cost_per_hour else: est_hours = 0.0 est_cost = 0.0 ips_per_dollar = 0.0
trial["est_40_epoch_hours"] = round(est_hours, 2) trial["est_40_epoch_cost"] = round(est_cost, 2) trial["ips_per_dollar"] = round(ips_per_dollar, 2) trial["cost_per_hour"] = cost_per_hour return trial
def run_benchmark_suite(config_path, gpu_name=None, cost_per_hour=None, python_bin=None, warmup_steps=100, measure_steps=300, output_dir="benchmark_results"): os.makedirs(output_dir, exist_ok=True) if not python_bin: python_bin = sys.executable
script_dir = os.path.dirname(os.path.abspath(__file__)) worker_script = os.path.join(script_dir, "benchmark_worker.py") if not os.path.exists(worker_script): raise FileNotFoundError(f"Worker script not found: {worker_script}")
detected_gpu = detect_gpu_name() if not gpu_name: gpu_name = detected_gpu
if cost_per_hour is None: cost_per_hour = 2.19 for k, v in PRICING_TABLE.items(): if k.lower() in gpu_name.lower(): cost_per_hour = v break
cpu_count = os.cpu_count() or 8 print("=" * 80) print(f"🚀 PADDLEOCR AUTOMATED HARDWARE BENCHMARK SUITE") print(f"GPU: {gpu_name} (Detected: {detected_gpu}) | Cost: ${cost_per_hour:.2f}/h") print(f"CPU Cores: {cpu_count} | Python: {python_bin}") print(f"Config: {config_path}") print(f"Warmup: {warmup_steps} steps | Measure: {measure_steps} steps") print("=" * 80, flush=True)
all_trials = []
# --------------------------------------------------------- # PHASE 1: FIND OPTIMAL NUM_WORKERS AT BASE BATCH # --------------------------------------------------------- base_batch = 128 initial_oom_batch = None
print(f"\nTesting initial base batch {base_batch} with 4 workers...") test_init = run_single_trial( python_bin, worker_script, config_path, batch_size=base_batch, num_workers=4, warmup_steps=warmup_steps, measure_steps=measure_steps, output_dir=output_dir ) test_init = compute_economics(test_init, cost_per_hour) all_trials.append(test_init)
if test_init["status"] == "OOM": initial_oom_batch = base_batch print(f"⚠️ Base batch {base_batch} encountered OOM on {gpu_name}! Stepping down to locate viable batch...") found_base = False for fallback_b in [96, 64, 48, 32]: print(f"Testing fallback batch {fallback_b}...") t_fb = run_single_trial( python_bin, worker_script, config_path, batch_size=fallback_b, num_workers=4, warmup_steps=warmup_steps, measure_steps=measure_steps, output_dir=output_dir ) t_fb = compute_economics(t_fb, cost_per_hour) all_trials.append(t_fb) if t_fb["status"] == "SUCCESS": base_batch = fallback_b found_base = True print(f"✅ Viable base batch found: {base_batch} (VRAM: {t_fb['vram_pct']:.1f}%)") break if not found_base: raise RuntimeError(f"Unable to find viable batch size even at batch 32 on {gpu_name}")
print("\n" + "=" * 60) print(f"📍 [PHASE 1/3] SWEEPING NUM_WORKERS AT BATCH SIZE {base_batch}") print("=" * 60, flush=True)
candidate_workers = [4, 8, 12, 16, 24] max_reasonable_workers = min(24, max(8, cpu_count * 2)) candidate_workers = [w for w in candidate_workers if w <= max_reasonable_workers] if 4 not in candidate_workers: candidate_workers.insert(0, 4)
best_worker = 4 best_worker_ips = 0.0 worker_trials = []
for w in candidate_workers: # Check if already tested existing = [t for t in all_trials if t["batch_size"] == base_batch and t["num_workers"] == w] if existing: trial = existing[0] else: trial = run_single_trial( python_bin, worker_script, config_path, batch_size=base_batch, num_workers=w, warmup_steps=warmup_steps, measure_steps=measure_steps, output_dir=output_dir ) trial = compute_economics(trial, cost_per_hour) all_trials.append(trial)
worker_trials.append(trial)
if trial["status"] == "SUCCESS": print(f" -> Workers={w:2d} | IPS={trial['ips']:6.1f} | Reader={trial['avg_reader_cost']:.4f}s | Batch={trial['avg_batch_cost']:.4f}s | ReaderRatio={trial['reader_ratio']:.2f}") if trial["ips"] > best_worker_ips: best_worker_ips = trial["ips"] best_worker = w else: print(f" -> Workers={w:2d} | FAILED ({trial['status']}): {trial.get('error')}")
print(f"\n✅ Optimal num_workers selected: {best_worker} (IPS: {best_worker_ips:.1f} samples/s)")
# --------------------------------------------------------- # PHASE 2: BATCH SIZE SCALING # --------------------------------------------------------- print("\n" + "=" * 60) print(f"📍 [PHASE 2/3] BATCH SIZE PROGRESSION (WORKERS = {best_worker})") print("=" * 60, flush=True)
if base_batch < 128: # Fine-grained progression for smaller GPUs batch_progression = [base_batch, 80, 96, 112, 128, 144, 160, 192, 224, 256] else: batch_progression = [128, 160, 192, 224, 256, 320, 384, 512, 768, 1024]
# Filter only batches >= base_batch batch_progression = sorted(list(set([b for b in batch_progression if b >= base_batch])))
batch_trials = [] last_safe_batch = base_batch last_safe_trial = next((t for t in worker_trials if t["batch_size"] == base_batch and t["num_workers"] == best_worker and t["status"] == "SUCCESS"), None) oom_batch = initial_oom_batch best_batch = base_batch best_batch_ips = best_worker_ips diminishing_returns_detected = False
for b in batch_progression: # If batch 128 was already tested in Phase 1 with the same worker, reuse result existing = [t for t in worker_trials if t["batch_size"] == b and t["num_workers"] == best_worker] if existing: trial = existing[0] else: trial = run_single_trial( python_bin, worker_script, config_path, batch_size=b, num_workers=best_worker, warmup_steps=warmup_steps, measure_steps=measure_steps, output_dir=output_dir ) trial = compute_economics(trial, cost_per_hour) all_trials.append(trial)
batch_trials.append(trial)
if trial["status"] == "SUCCESS": cur_ips = trial["ips"] vram_pct = trial["vram_pct"] reader_ratio = trial["reader_ratio"]
# Calculate improvement over previous successful batch delta_ips_pct = 0.0 if last_safe_trial and last_safe_trial["ips"] > 0: delta_ips_pct = ((cur_ips - last_safe_trial["ips"]) / last_safe_trial["ips"]) * 100
print(f" -> Batch={b:4d} | IPS={cur_ips:6.1f} ({delta_ips_pct:+5.1f}%) | VRAM={trial['peak_vram_mb']:5.0f}MB ({vram_pct:4.1f}%) | ReaderRatio={reader_ratio:.2f} | Est: {trial['est_40_epoch_hours']:.1f}h (${trial['est_40_epoch_cost']:.2f})")
# Check for best throughput batch if cur_ips > best_batch_ips: best_batch_ips = cur_ips best_batch = b
# Check diminishing returns: if gain < 3% compared to previous batch if last_safe_trial and delta_ips_pct < 3.0: print(f" ⚠️ Diminishing returns detected at Batch={b} (Throughput gain {delta_ips_pct:.2f}% < 3.0%). Sweet spot identified.") diminishing_returns_detected = True
last_safe_batch = b last_safe_trial = trial
# Check if VRAM exceeds 92% (danger zone) if vram_pct >= 92.0: print(f" ⚠️ VRAM usage reached {vram_pct:.1f}% (>= 92%). Halting batch scaling to avoid sudden hard OOM.") break
# If diminishing returns detected and VRAM is already high, stop scaling further if diminishing_returns_detected and vram_pct >= 85.0: print(f" 🏁 Stopping batch progression: Throughput saturated and VRAM comfortably utilized.") break
elif trial["status"] == "OOM": print(f" 💥 OOM encountered at Batch={b}!") oom_batch = b break else: print(f" ❌ Trial failed at Batch={b} with status {trial['status']}: {trial.get('error')}") break
# --------------------------------------------------------- # PHASE 3: BINARY SEARCH FOR EXACT MAX SAFE BATCH # --------------------------------------------------------- max_safe_batch = last_safe_batch if oom_batch is not None and last_safe_batch is not None: print("\n" + "=" * 60) print(f"📍 [PHASE 3/3] BINARY SEARCH BETWEEN {last_safe_batch} (SAFE) AND {oom_batch} (OOM)") print("=" * 60, flush=True)
low = last_safe_batch high = oom_batch while (high - low) > 16: mid = round_to_multiple_of_16((low + high) / 2) if mid == low or mid == high: break
print(f"\n[Binary Search] Testing midpoint Batch={mid} (range: [{low}, {high}])...") trial = run_single_trial( python_bin, worker_script, config_path, batch_size=mid, num_workers=best_worker, warmup_steps=warmup_steps, measure_steps=measure_steps, output_dir=output_dir ) trial = compute_economics(trial, cost_per_hour) all_trials.append(trial)
if trial["status"] == "SUCCESS": print(f" -> Batch={mid} succeeded! IPS={trial['ips']:.1f}, VRAM={trial['vram_pct']:.1f}%") low = mid if trial["ips"] > best_batch_ips and not diminishing_returns_detected: best_batch_ips = trial["ips"] best_batch = mid else: print(f" -> Batch={mid} failed with {trial['status']}.") high = mid
max_safe_batch = low print(f"\n🎯 Binary Search Complete: Max Safe Batch = {max_safe_batch}")
# --------------------------------------------------------- # PHASE 4: BOTTLENECK ANALYSIS & REPORT GENERATION # --------------------------------------------------------- best_trial = next((t for t in all_trials if t["batch_size"] == best_batch and t["num_workers"] == best_worker and t["status"] == "SUCCESS"), last_safe_trial) # Identify primary bottleneck bottleneck = "Balanced" if best_trial: if best_trial["vram_pct"] >= 90.0: bottleneck = "VRAM Capacity Limited" elif best_trial["reader_ratio"] >= 0.40: bottleneck = "DataLoader / CPU Bound" elif best_trial["avg_gpu_util"] >= 80.0 and best_trial["reader_ratio"] < 0.20: bottleneck = "GPU Compute Saturated (Optimal)" elif best_trial["avg_cpu_pct"] >= 85.0: bottleneck = "Host CPU Bound" else: bottleneck = "Memory Bandwidth / Pipeline Latency"
summary = { "gpu_name": gpu_name, "cost_per_hour": cost_per_hour, "optimal_workers": best_worker, "best_batch": best_batch, "max_safe_batch": max_safe_batch, "best_ips": best_trial["ips"] if best_trial else 0.0, "primary_bottleneck": bottleneck, "best_trial": best_trial, "all_trials": all_trials }
# Save JSON summary summary_file = os.path.join(output_dir, f"benchmark_{gpu_name.replace(' ', '_')}.json") with open(summary_file, 'w', encoding='utf-8') as f: json.dump(summary, f, indent=2, ensure_ascii=False)
# Generate Markdown Report md_report = generate_markdown_report(summary) md_file = os.path.join(output_dir, f"benchmark_{gpu_name.replace(' ', '_')}.md") with open(md_file, 'w', encoding='utf-8') as f: f.write(md_report)
print("\n" + "=" * 80) print("📊 BENCHMARK REPORT COMPLETED") print(f"JSON Output: {summary_file}") print(f"MD Output: {md_file}") print("=" * 80) print(md_report)
return summary
def generate_markdown_report(summary): gpu = summary["gpu_name"] cost = summary["cost_per_hour"] best_b = summary["best_batch"] max_b = summary["max_safe_batch"] workers = summary["optimal_workers"] bottleneck = summary["primary_bottleneck"] trials = summary["all_trials"]
lines = [] lines.append(f"# Benchmark & Hardware Limit Analysis: {gpu}") lines.append(f"**Cluster / GPU**: `{gpu}` | **Pricing**: `${cost:.2f}/h` | **Primary Bottleneck**: `{bottleneck}`\n")
lines.append("## 1. Kết Quả Đo Lường Chi Tiết (Full Measurement Trials)") lines.append("| Batch | Workers | Status | IPS (mẫu/s) | GPU Util % | VRAM (MB) | VRAM % | Reader Cost | Batch Cost | Reader Ratio | Est 40 Epoch | Est Cost | IPS/$ |") lines.append("|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|")
for t in trials: b = t["batch_size"] w = t["num_workers"] st = t["status"] if st == "SUCCESS": ips = f"{t['ips']:.1f}" gpu_u = f"{t['avg_gpu_util']:.0f}%" vram_mb = f"{t['peak_vram_mb']:.0f}" vram_p = f"{t['vram_pct']:.1f}%" r_cost = f"{t['avg_reader_cost']:.4f}s" b_cost = f"{t['avg_batch_cost']:.4f}s" r_ratio = f"{t['reader_ratio']:.2f}" est_h = f"{t['est_40_epoch_hours']:.2f}h" est_c = f"${t['est_40_epoch_cost']:.2f}" ips_d = f"{t['ips_per_dollar']:.1f}" else: ips = "-" gpu_u = "-" vram_mb = "-" vram_p = "-" r_cost = "-" b_cost = "-" r_ratio = "-" est_h = "-" est_c = "-" ips_d = "-"
# Highlight best and max tag = "" if b == best_b and w == workers and st == "SUCCESS": tag = " 🌟 *(Best)*" elif b == max_b and w == workers and st == "SUCCESS": tag = " 🛡️ *(Max Safe)*" elif st == "OOM": tag = " 💥 *(OOM)*"
lines.append(f"| {b}{tag} | {w} | {st} | {ips} | {gpu_u} | {vram_mb} | {vram_p} | {r_cost} | {b_cost} | {r_ratio} | {est_h} | {est_c} | {ips_d} |")
lines.append("\n## 2. Kết Luận & Đề Xuất Cấu Hình") best_t = summary.get("best_trial") if best_t: lines.append(f"- **Max Batch Chạy Được (Hardware Limit)**: `{max_b}` (ngưỡng tối đa trước khi tràn VRAM).") lines.append(f"- **Best Batch Nên Dùng (Sweet Spot)**: `{best_b}` (đạt throughput `{best_t['ips']:.1f}` mẫu/s, khai thác `{best_t['vram_pct']:.1f}%` VRAM).") lines.append(f"- **Workers Tối Ưu**: `{workers}` (giữ `reader_ratio = {best_t['reader_ratio']:.2f}`, đảm bảo GPU không bị đói dữ liệu).") lines.append(f"- **Điểm Nghẽn Chính (Bottleneck)**: `{bottleneck}`.") lines.append(f"- **Thời Gian Huấn Luyện Full 40 Epoch (10M samples)**: `{best_t['est_40_epoch_hours']:.2f} giờ` (~`{best_t['est_40_epoch_hours']*60:.0f} phút`).") lines.append(f"- **Chi Phí Ước Tính Full 40 Epoch**: `${best_t['est_40_epoch_cost']:.2f}`.") lines.append(f"- **Hiệu Suất Kinh Tế (Throughput / $)**: `{best_t['ips_per_dollar']:.1f} samples / $`.") return "\n".join(lines)
if __name__ == "__main__": parser = argparse.ArgumentParser(description="Automated PaddleOCR Benchmark Suite") parser.add_argument("-c", "--config_path", type=str, required=True, help="Path to YAML config") parser.add_argument("--gpu_name", type=str, default=None, help="GPU identifier name") parser.add_argument("--cost_per_hour", type=float, default=None, help="Hourly cost in USD") parser.add_argument("--python_bin", type=str, default=None, help="Path to Python interpreter") parser.add_argument("--warmup_steps", type=int, default=100, help="Warmup steps") parser.add_argument("--measure_steps", type=int, default=300, help="Measure steps") parser.add_argument("-o", "--output_dir", type=str, default="benchmark_results", help="Directory to save results") args = parser.parse_args()
run_benchmark_suite( config_path=args.config_path, gpu_name=args.gpu_name, cost_per_hour=args.cost_per_hour, python_bin=args.python_bin, warmup_steps=args.warmup_steps, measure_steps=args.measure_steps, output_dir=args.output_dir )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351#!/usr/bin/env python3# -*- coding: utf-8 -*-"""Isolated Benchmark Worker for PaddleOCR Training.Executes a single (batch_size, num_workers) trial in an isolated subprocess.Exits cleanly on success (code 0), OOM (code 137), NaN loss (code 138), or error (code 1)."""
import osimport sysimport timeimport jsonimport argparseimport tracebackimport threading
# 1. NumPy 2.x compatibility monkeypatchimport numpy as npif not hasattr(np, 'sctypes'): np.sctypes = { 'int': [np.int8, np.int16, np.int32, np.int64], 'uint': [np.uint8, np.uint16, np.uint32, np.uint64], 'float': [np.float16, np.float32, np.float64], 'complex': [np.complex64, np.complex128], 'others': [bool, object, bytes, str] }if not hasattr(np, 'bool'): np.bool = boolif not hasattr(np, 'int'): np.int = intif not hasattr(np, 'float'): np.float = floatif not hasattr(np, 'typeDict'): np.typeDict = {}
# 2. Add PaddleOCR pathcurrent_dir = os.path.dirname(os.path.abspath(__file__))# Check possible PaddleOCR locationspaddleocr_dirs = [ os.path.join(current_dir, "..", "PaddleOCR"), os.path.join(current_dir, "..", "..", "ocr-studio", "PaddleOCR"), os.path.join(current_dir, "..", "..", "PaddleOCR"), "/teamspace/studios/this_studio/Cham-OCR/ocr-training/PaddleOCR",]for p in paddleocr_dirs: if os.path.isdir(p): sys.path.insert(0, os.path.abspath(p)) break
import yamlimport paddleimport paddle.distributed as dist
from ppocr.data import build_dataloader, set_signal_handlersfrom ppocr.modeling.architectures import build_model, apply_to_staticfrom ppocr.losses import build_lossfrom ppocr.optimizer import build_optimizerfrom ppocr.postprocess import build_post_processfrom ppocr.utils.logging import get_logger
try: import psutilexcept ImportError: psutil = None
def to_float32(preds): if isinstance(preds, dict): for k in preds: if isinstance(preds[k], dict): for sub_k in preds[k]: preds[k][sub_k] = preds[k][sub_k].astype(paddle.float32) else: preds[k] = preds[k].astype(paddle.float32) elif isinstance(preds, list): preds = [pred.astype(paddle.float32) for pred in preds] else: preds = preds.astype(paddle.float32) return preds
class GPUMonitor(threading.Thread): """Monitors GPU utilization and VRAM in a background thread.""" def __init__(self, interval=0.3): super().__init__(daemon=True) self.interval = interval self.running = True self.gpu_utils = [] self.vram_used_mb = [] self.total_vram_mb = 0.0 self.cpu_percents = []
def run(self): while self.running: try: # Query nvidia-smi import subprocess res = subprocess.run( ["nvidia-smi", "--query-gpu=utilization.gpu,memory.used,memory.total", "--format=csv,noheader,nounits"], capture_output=True, text=True, timeout=1.5 ) if res.returncode == 0 and res.stdout.strip(): parts = [float(x.strip()) for x in res.stdout.strip().split("\n")[0].split(",")] self.gpu_utils.append(parts[0]) self.vram_used_mb.append(parts[1]) self.total_vram_mb = parts[2] except Exception: pass
if psutil: try: self.cpu_percents.append(psutil.cpu_percent(interval=None)) except Exception: pass
time.sleep(self.interval)
def stop(self): self.running = False
def run_benchmark(config_path, batch_size, num_workers, warmup_steps=100, measure_steps=300, output_json="trial_result.json"): result = { "batch_size": batch_size, "num_workers": num_workers, "warmup_steps": warmup_steps, "measure_steps": measure_steps, "status": "UNKNOWN", "ips": 0.0, "avg_reader_cost": 0.0, "avg_batch_cost": 0.0, "reader_ratio": 0.0, "peak_vram_mb": 0.0, "total_vram_mb": 0.0, "vram_pct": 0.0, "avg_gpu_util": 0.0, "avg_cpu_pct": 0.0, "error": None }
monitor = GPUMonitor(interval=0.3) monitor.start()
try: with open(config_path, 'r', encoding='utf-8') as f: config = yaml.safe_load(f)
# Override configurations config['Global']['distributed'] = False config['Global']['use_gpu'] = True config['Global']['cal_metric_during_train'] = False config['Global']['epoch_num'] = 100 config['Train']['loader']['batch_size_per_card'] = batch_size config['Train']['loader']['num_workers'] = num_workers config['Train']['loader']['drop_last'] = True config['Eval'] = None
device = 'gpu' paddle.set_device('gpu:0') logger = get_logger(name="benchmark_worker")
# Set signal handlers & build DataLoader set_signal_handlers() train_dataloader = build_dataloader(config, 'Train', device, logger, seed=42) if len(train_dataloader) == 0: raise RuntimeError("DataLoader is empty! Check dataset paths in config.")
global_config = config['Global'] post_process_class = build_post_process(config['PostProcess'], global_config)
# MultiHead channel adjustments if hasattr(post_process_class, 'character'): char_num = len(getattr(post_process_class, 'character')) if config['Architecture']['Head']['name'] == 'MultiHead': if config['PostProcess']['name'] == 'NRTRLabelDecode': char_num = char_num - 3 out_channels_list = {'CTCLabelDecode': char_num} if len(config['Loss']['loss_config_list']) > 1 and list(config['Loss']['loss_config_list'][1].keys())[0] == 'NRTRLoss': out_channels_list['NRTRLabelDecode'] = char_num + 3 config['Architecture']['Head']['out_channels_list'] = out_channels_list else: config['Architecture']['Head']['out_channels'] = char_num
model = build_model(config['Architecture']) model = apply_to_static(model, config, logger) model.train() loss_class = build_loss(config['Loss']) optimizer, lr_scheduler = build_optimizer( config['Optimizer'], epochs=config['Global']['epoch_num'], step_each_epoch=len(train_dataloader), model=model )
use_amp = config['Global'].get('use_amp', False) amp_level = config['Global'].get('amp_level', 'O1') amp_dtype = config['Global'].get('amp_dtype', 'float16') scaler = paddle.amp.GradScaler() if use_amp else None
extra_input_models = [ "SRN", "NRTR", "SAR", "SEED", "SVTR", "SVTR_LCNet", "SPIN", "VisionLAN", "RobustScanner", "RFL", 'DRRG', 'SATRN', 'SVTR_HGNet', "ParseQ", "CPPD" ] extra_input = config['Architecture'].get('algorithm', '') in extra_input_models or config['Architecture']['Head'].get('name', '') == 'MultiHead'
total_steps = warmup_steps + measure_steps step_idx = 0
total_reader_time = 0.0 total_batch_time = 0.0 total_samples = 0
data_iter = iter(train_dataloader) print(f"[Worker] Starting trial: Batch={batch_size}, Workers={num_workers}, Warmup={warmup_steps}, Measure={measure_steps}, ExtraInput={extra_input}", flush=True)
reader_start = time.perf_counter() while step_idx < total_steps: try: batch = next(data_iter) except StopIteration: data_iter = iter(train_dataloader) batch = next(data_iter)
t_read = time.perf_counter() - reader_start images = batch[0] batch_samples = len(images)
# Forward + Backward if scaler: with paddle.amp.auto_cast(level=amp_level, dtype=amp_dtype): if extra_input: preds = model(images, data=batch[1:]) else: preds = model(images) preds = to_float32(preds) loss = loss_class(preds, batch) avg_loss = loss['loss'] loss_val = float(avg_loss) if np.isnan(loss_val) or np.isinf(loss_val): raise ValueError(f"Loss exploded: {loss_val}") scaled_avg_loss = scaler.scale(avg_loss) scaled_avg_loss.backward() scaler.minimize(optimizer, scaled_avg_loss) else: if extra_input: preds = model(images, data=batch[1:]) else: preds = model(images) loss = loss_class(preds, batch) avg_loss = loss['loss'] loss_val = float(avg_loss) if np.isnan(loss_val) or np.isinf(loss_val): raise ValueError(f"Loss exploded: {loss_val}") avg_loss.backward() optimizer.step()
optimizer.clear_grad() if not isinstance(lr_scheduler, float): lr_scheduler.step()
# Synchronize CUDA to get exact batch execution time try: paddle.device.cuda.synchronize() except Exception: pass t_batch = time.perf_counter() - reader_start
if step_idx >= warmup_steps: total_reader_time += t_read total_batch_time += t_batch total_samples += batch_samples
step_idx += 1 if step_idx % 50 == 0: cur_ips = batch_samples / t_batch if t_batch > 0 else 0 phase = "WARMUP" if step_idx <= warmup_steps else "MEASURE" print(f"[Worker] Step {step_idx}/{total_steps} [{phase}] - IPS: {cur_ips:.1f} - BatchTime: {t_batch:.4f}s - Reader: {t_read:.4f}s", flush=True)
reader_start = time.perf_counter()
# Stop monitoring monitor.stop()
avg_reader_cost = total_reader_time / measure_steps if measure_steps > 0 else 0 avg_batch_cost = total_batch_time / measure_steps if measure_steps > 0 else 0 ips = total_samples / total_batch_time if total_batch_time > 0 else 0
# Memory stats paddle_peak_bytes = paddle.device.cuda.max_memory_allocated() paddle_peak_mb = paddle_peak_bytes / (1024 * 1024) smi_peak_mb = max(monitor.vram_used_mb) if monitor.vram_used_mb else paddle_peak_mb peak_vram_mb = max(paddle_peak_mb, smi_peak_mb) total_vram_mb = monitor.total_vram_mb if monitor.total_vram_mb > 0 else 40960.0 vram_pct = (peak_vram_mb / total_vram_mb) * 100 if total_vram_mb > 0 else 0
avg_gpu = sum(monitor.gpu_utils) / len(monitor.gpu_utils) if monitor.gpu_utils else 0.0 avg_cpu = sum(monitor.cpu_percents) / len(monitor.cpu_percents) if monitor.cpu_percents else 0.0
result.update({ "status": "SUCCESS", "ips": round(ips, 2), "avg_reader_cost": round(avg_reader_cost, 4), "avg_batch_cost": round(avg_batch_cost, 4), "reader_ratio": round(avg_reader_cost / avg_batch_cost, 3) if avg_batch_cost > 0 else 0, "peak_vram_mb": round(peak_vram_mb, 1), "total_vram_mb": round(total_vram_mb, 1), "vram_pct": round(vram_pct, 1), "avg_gpu_util": round(avg_gpu, 1), "avg_cpu_pct": round(avg_cpu, 1) }) print(f"[Worker SUCCESS] Batch={batch_size} Workers={num_workers} => IPS={ips:.1f} samples/s, VRAM={vram_pct:.1f}%, ReaderRatio={result['reader_ratio']}", flush=True) exit_code = 0
except Exception as e: monitor.stop() err_str = str(e).lower() full_tb = traceback.format_exc() print(f"[Worker ERROR] {e}\n{full_tb}", file=sys.stderr, flush=True)
if "out of memory" in err_str or "bad_alloc" in err_str or "cudabadalloc" in err_str or "memoryerror" in err_str: result["status"] = "OOM" result["error"] = "CUDA Out Of Memory" exit_code = 137 elif "loss exploded" in err_str or "nan" in err_str or "inf" in err_str: result["status"] = "NAN_LOSS" result["error"] = str(e) exit_code = 138 else: result["status"] = "CRASH" result["error"] = str(e) exit_code = 1
with open(output_json, 'w', encoding='utf-8') as f: json.dump(result, f, indent=2, ensure_ascii=False)
sys.exit(exit_code)
if __name__ == "__main__": parser = argparse.ArgumentParser(description="Isolated PaddleOCR Benchmark Worker") parser.add_argument("-c", "--config_path", type=str, required=True, help="Path to YAML training config") parser.add_argument("-b", "--batch_size", type=int, required=True, help="Batch size per card") parser.add_argument("-w", "--num_workers", type=int, required=True, help="Number of DataLoader workers") parser.add_argument("--warmup_steps", type=int, default=100, help="Warmup steps before measuring") parser.add_argument("--measure_steps", type=int, default=300, help="Measured steps") parser.add_argument("-o", "--output_json", type=str, default="trial_result.json", help="Path to write trial JSON") args = parser.parse_args()
run_benchmark( config_path=args.config_path, batch_size=args.batch_size, num_workers=args.num_workers, warmup_steps=args.warmup_steps, measure_steps=args.measure_steps, output_json=args.output_json )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234#!/usr/bin/env python3# -*- coding: utf-8 -*-"""Kịch bản xây dựng từ điển V25 tự động & Preflight Validation:1. Chuẩn hóa nhãn văn bản với Unicode NFC (unicodedata.normalize('NFC', ...))2. Giữ nguyên 100% thứ tự token V24 (103 tokens) làm nền tảng cố định3. Tự động phát hiện và append các token mới vào cuối từ điển (không hardcode số lượng)4. Quét phân bố độ dài nhãn (P50, P90, P95, P99, Max) và xác định max_text_length = P995. Chạy Preflight Validation: - unknown_char == 0 - invalid_unicode == 0 - labels_exceeding_max_len == 0"""
import osimport sysimport jsonimport unicodedataimport mathimport numpy as np
if sys.stdout and hasattr(sys.stdout, 'reconfigure'): sys.stdout.reconfigure(encoding='utf-8')
def load_v24_dict(v24_dict_path): """Nạp danh sách token V24, bảo tồn chính xác thứ tự.""" if not os.path.exists(v24_dict_path): raise FileNotFoundError(f"Không tìm thấy từ điển V24 tại: {v24_dict_path}") tokens = [] with open(v24_dict_path, 'r', encoding='utf-8') as f: for line in f: token = line.rstrip('\r\n') if token: tokens.append(token) return tokens
def is_valid_unicode(char): """Kiểm tra ký tự có phải là Unicode hợp lệ (không phải surrogate hay control vô nghĩa).""" try: cat = unicodedata.category(char) # Loại trừ lone surrogates (Cs) và format control không nhìn thấy if cat in ('Cs',): return False return True except Exception: return False
def build_dict_and_validate(label_files, v24_dict_path, output_dict_path, report_path=None, enforced_max_len=None): print("=" * 80) print("🚀 BẮT ĐẦU XÂY DỰNG TỪ ĐIỂN V25 ĐỘNG & CHẠY PREFLIGHT VALIDATION") print("=" * 80) # 1. Nạp từ điển V24 gốc v24_tokens = load_v24_dict(v24_dict_path) print(f"✅ Đã nạp {len(v24_tokens)} tokens cơ sở từ V24 (bảo toàn 100% thứ tự).") v24_token_set = set(v24_tokens) new_token_set = set() all_lengths = [] total_lines = 0 invalid_unicode_chars = set() sample_labels = [] # 2. Đọc toàn bộ nhãn từ các tệp dữ liệu print(f"📂 Đang quét các tệp nhãn: {label_files}") for lf in label_files: if not os.path.exists(lf): print(f"⚠️ Bỏ qua tệp không tồn tại: {lf}") continue with open(lf, 'r', encoding='utf-8') as f: for line_idx, line in enumerate(f): line = line.strip() if not line: continue total_lines += 1 parts = line.split('\t', 1) text = parts[1] if len(parts) > 1 else parts[0] # Bắt buộc chuẩn hóa Unicode NFC norm_text = unicodedata.normalize('NFC', text) all_lengths.append(len(norm_text)) if total_lines <= 10: sample_labels.append(norm_text) for char in norm_text: if not is_valid_unicode(char): invalid_unicode_chars.add(char) continue if char != ' ' and char not in v24_token_set: new_token_set.add(char) print(f"📊 Đã quét tổng cộng {total_lines:,} dòng nhãn.") # Sắp xếp các ký tự mới append để đảm bảo tính nhất quán (deterministic order) # Nhóm ký tự tiếng Việt / Latin / dấu câu được sắp xếp theo codepoint sorted_new_tokens = sorted(list(new_token_set), key=lambda c: ord(c)) # Ghép từ điển V25 hoàn chỉnh: [V24 Tokens] + [New Tokens appended at the end] v25_tokens = v24_tokens + sorted_new_tokens v25_token_set = set(v25_tokens) print(f"✨ Số token V24 ban đầu: {len(v24_tokens)}") print(f"✨ Số token mới phát hiện và bổ sung: {len(sorted_new_tokens)}") print(f"✨ Tổng kích thước từ điển V25: {len(v25_tokens)} tokens") # 3. Phân bố độ dài nhãn (Length Percentiles Scan) if all_lengths: arr_len = np.array(all_lengths) p50 = float(np.percentile(arr_len, 50)) p90 = float(np.percentile(arr_len, 90)) p95 = float(np.percentile(arr_len, 95)) p99 = float(np.percentile(arr_len, 99)) max_len = int(np.max(arr_len)) min_len = int(np.min(arr_len)) mean_len = float(np.mean(arr_len)) else: p50 = p90 = p95 = p99 = max_len = min_len = mean_len = 0 recommended_max_len = int(math.ceil(p99)) target_max_len = enforced_max_len if enforced_max_len else recommended_max_len # 4. Chạy Preflight Validation unknown_chars = set() labels_exceeding_max_len = 0 for lf in label_files: if not os.path.exists(lf): continue with open(lf, 'r', encoding='utf-8') as f: for line in f: line = line.strip() if not line: continue parts = line.split('\t', 1) text = parts[1] if len(parts) > 1 else parts[0] norm_text = unicodedata.normalize('NFC', text) if len(norm_text) > target_max_len: labels_exceeding_max_len += 1 for char in norm_text: if char != ' ' and char not in v25_token_set: unknown_chars.add(char) # 5. Lưu từ điển V25 os.makedirs(os.path.dirname(os.path.abspath(output_dict_path)), exist_ok=True) with open(output_dict_path, 'w', encoding='utf-8', newline='\n') as f_out: for t in v25_tokens: f_out.write(t + '\n') # 6. Tổng hợp báo cáo kiểm định Preflight validation_status = ( len(unknown_chars) == 0 and len(invalid_unicode_chars) == 0 and labels_exceeding_max_len == 0 ) report = { "status": "PASS" if validation_status else "WARNING/FAIL", "preflight_checks": { "unknown_characters_count": len(unknown_chars), "unknown_characters_list": list(unknown_chars), "invalid_unicode_count": len(invalid_unicode_chars), "invalid_unicode_list": [f"U+{ord(c):04X}" for c in invalid_unicode_chars], "labels_exceeding_max_len_count": labels_exceeding_max_len, "labels_exceeding_percentage": round((labels_exceeding_max_len / total_lines * 100), 2) if total_lines > 0 else 0.0 }, "vocabulary_metrics": { "v24_base_tokens": len(v24_tokens), "new_appended_tokens": len(sorted_new_tokens), "v25_total_tokens": len(v25_tokens), "sample_new_tokens": sorted_new_tokens[:25] }, "label_length_percentiles": { "min": min_len, "p50_median": p50, "p90": p90, "p95": p95, "p99": p99, "max": max_len, "mean": round(mean_len, 2), "recommended_max_text_length": recommended_max_len, "configured_max_text_length": target_max_len } } if report_path: os.makedirs(os.path.dirname(os.path.abspath(report_path)), exist_ok=True) with open(report_path, 'w', encoding='utf-8') as f_rep: json.dump(report, f_rep, indent=2, ensure_ascii=False) print("\n" + "="*80) print("📋 KẾT QUẢ PREFLIGHT VALIDATION TỪ ĐIỂN V25:") print("="*80) print(f" • Trạng thái Preflight: {'✅ PASS' if validation_status else '⚠️ CẦN LƯU Ý'}") print(f" • Ký tự lạ (Unknown chars): {len(unknown_chars)}") print(f" • Ký tự Unicode không hợp lệ: {len(invalid_unicode_chars)}") print(f" • Phân bố độ dài nhãn: P50={p50:.1f} | P90={p90:.1f} | P95={p95:.1f} | P99={p99:.1f} | Max={max_len}") print(f" • Max Text Length đề xuất (dựa trên P99): {recommended_max_len}") print(f" • Số nhãn vượt ngưỡng {target_max_len}: {labels_exceeding_max_len}") print(f" • Từ điển V25 đã lưu tại: {output_dict_path}") if report_path: print(f" • Báo cáo chi tiết lưu tại: {report_path}") print("="*80) return v25_tokens, report
if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description="Build V25 dictionary and run preflight checks") parser.add_argument("--v24-dict", default="ocr-training/data/cham_dict_v24.txt", help="Path to V24 base dictionary") parser.add_argument("--output-dict", default="ocr-training/data/cham_dict_v25.txt", help="Path to save V25 dictionary") parser.add_argument("--report", default="ocr-training/data/v25_dict_preflight_report.json", help="Path to save validation report") parser.add_argument("--label-files", nargs="*", default=[], help="Explicit list of label files to scan") parser.add_argument("--max-len", type=int, default=None, help="Enforce specific max text length") args = parser.parse_args()
if args.label_files: avail_labels = args.label_files else: label_candidates = [ "ocr-training/data/cham_synthetic_v24/train_label.txt", "ocr-training/data/cham_synthetic_v24/val_label.txt", "ocr-training/data/cham_synthetic_v23_1/train_label.txt", "ocr-training/data/cham_synthetic_images/train_label.txt" ] avail_labels = [p for p in label_candidates if os.path.exists(p)] build_dict_and_validate(avail_labels, args.v24_dict, args.output_dict, args.report, args.max_len)
48 unmodified lines49505152535448 unmodified linesfor c in new_chars:f_out.write(c + '\n')report = {"old_dict_size": old_dict_size,"new_dict_size": new_dict_size,48 unmodified lines495051525354555648 unmodified linesfor c in new_chars:f_out.write(c + '\n')new_dict_sha = sha256(new_dict_path)report = {"old_dict_size": old_dict_size,"new_dict_size": new_dict_size,
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273#!/usr/bin/env python3# -*- coding: utf-8 -*-"""Dictionary Generator for Cham OCR Model V25.Expands cham_dict_v24.txt into a Unified Multilingual Dictionary (cham_dict_v25.txt)including:- Full Cham characters, diacritics, finals, digits, punctuation (84 tokens)- En-dash '–', Em-dash '—', '?', '!', '"', '\''- Latin alphabet (a-z, A-Z)- Complete Vietnamese alphabet with all tone marks (both lower and upper case)"""
import osimport sys
# Force UTF-8 encodingif sys.stdout and hasattr(sys.stdout, 'reconfigure'): sys.stdout.reconfigure(encoding='utf-8')
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))PROJECT_ROOT = os.path.dirname(os.path.dirname(SCRIPT_DIR))TRAINING_DIR = os.path.join(PROJECT_ROOT, "ocr-training")STUDIO_DIR = os.path.join(PROJECT_ROOT, "ocr-studio")
V24_DICT_PATH = os.path.join(TRAINING_DIR, "data", "cham_dict_v24.txt")V25_DICT_TRAIN = os.path.join(TRAINING_DIR, "data", "cham_dict_v25.txt")V25_DICT_STUDIO = os.path.join(STUDIO_DIR, "data", "cham_dict_v25.txt")
with open(V24_DICT_PATH, "r", encoding="utf-8") as f: existing_lines = [line.strip("\r\n") for line in f if line.strip("\r\n") != ""]
viet_lower = "àáảãạăắằẳẵặâấầẩẫậèéẻẽẹêếềểễệìíỉĩịòóỏõọôốồổỗộơớờởỡợùúủũụưứừửữựỳýỷỹỵđ"viet_upper = "ÀÁẢÃẠĂẮẰẲẴẶÂẤẦẨẪẬÈÉẺẼẸÊẾỀỂỄỆÌÍỈĨỊÒÓỎÕỌÔỐỒỔỖỘƠỚỜỞỠỢÙÚỦŨỤƯỨỪỬỮỰỲÝỶỸỴĐ"latin_lower = "abcdefghijklmnopqrstuvwxyz"latin_upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"extra_punct = ["–", "—", "?", "!", "\"", "'"]
ordered_tokens = []seen = set()
# 1. Existing tokens from v24for tok in existing_lines: if tok not in seen: seen.add(tok) ordered_tokens.append(tok)
# 2. Add extra punctuationfor tok in extra_punct: if tok not in seen: seen.add(tok) ordered_tokens.append(tok)
# 3. Add Latin charactersfor tok in latin_lower + latin_upper: if tok not in seen: seen.add(tok) ordered_tokens.append(tok)
# 4. Add Vietnamese diacritic charactersfor tok in viet_lower + viet_upper: if tok not in seen: seen.add(tok) ordered_tokens.append(tok)
# Write to both ocr-training and ocr-studiofor out_path in [V25_DICT_TRAIN, V25_DICT_STUDIO]: os.makedirs(os.path.dirname(out_path), exist_ok=True) with open(out_path, "w", encoding="utf-8") as f: for tok in ordered_tokens: f.write(tok + "\n") print(f"✅ Saved {len(ordered_tokens)} unified tokens to: {out_path}")
print(f"\n🎉 Unified Dictionary V25 created successfully with {len(ordered_tokens)} tokens!")6 unmodified lines78910111213146 unmodified linesif sys.stdout and hasattr(sys.stdout, 'reconfigure'):sys.stdout.reconfigure(encoding='utf-8')os.environ["KAGGLE_USERNAME"] = "gustavnguyen"os.environ["KAGGLE_KEY"] = "6bf56db7e5c0fa7895d157167961d92b"from kaggle.api.kaggle_api_extended import KaggleApifrom kagglesdk.kernels.types.kernels_api_service import ApiDownloadKernelOutputRequest6 unmodified lines78910111213146 unmodified linesif sys.stdout and hasattr(sys.stdout, 'reconfigure'):sys.stdout.reconfigure(encoding='utf-8')from kaggle_auth import init_kaggle_authinit_kaggle_auth()from kaggle.api.kaggle_api_extended import KaggleApifrom kagglesdk.kernels.types.kernels_api_service import ApiDownloadKernelOutputRequest
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187#!/usr/bin/env python3# -*- coding: utf-8 -*-"""Script tải an toàn và giải nén output V25 Stage 1 từ Kaggle.Hỗ trợ:- Stream chunked download (không nghẽn RAM)- Tự động resume (HTTP Range header) nếu mạng gián đoạn- Tự động giải nén rec_cham_v25_stage1_checkpoint.zip"""
import osimport sysimport timeimport requestsimport zipfile
sys.path.insert(0, os.path.dirname(__file__))import kaggle_authfrom kaggle.api.kaggle_api_extended import KaggleApi, ApiListKernelSessionOutputRequest
def get_remote_file_size(url): """Lấy kích thước chuẩn của file remote trên Cloud.""" try: r = requests.get(url, headers={"Range": "bytes=0-0"}, timeout=30) if r.status_code == 206: cr = r.headers.get("Content-Range", "") if "/" in cr: return int(cr.split("/")[-1]) if "Content-Length" in r.headers: return int(r.headers["Content-Length"]) except Exception as e: print(f"⚠️ Không lấy được kích thước remote: {e}") return None
def download_file(url, target_path, chunk_size=1024*1024*8, max_retries=10): """Tải file theo từng chunk có hỗ trợ resume và tự động retry nếu ngắt mạng.""" total_remote_bytes = get_remote_file_size(url) if total_remote_bytes: print(f"🌐 Kích thước file remote: {total_remote_bytes / (1024*1024):.2f} MB ({total_remote_bytes} bytes)")
for attempt in range(max_retries): try: existing_bytes = os.path.getsize(target_path) if os.path.exists(target_path) else 0
if total_remote_bytes is not None: if existing_bytes > total_remote_bytes: print(f"⚠️ File local lớn hơn remote ({existing_bytes} > {total_remote_bytes}). Xóa file cũ để tải mới...") os.remove(target_path) existing_bytes = 0 elif existing_bytes == total_remote_bytes and existing_bytes > 0: print(f"✅ File đã tồn tại trọn vẹn ({existing_bytes / (1024*1024):.2f} MB)!") return target_path
headers = {} if existing_bytes > 0: headers["Range"] = f"bytes={existing_bytes}-" print(f"🔄 Lần thử {attempt + 1}/{max_retries}: Tiếp tục tải từ byte {existing_bytes} ({existing_bytes / (1024*1024):.2f} MB)...") else: print(f"📥 Bắt đầu tải mới về: {target_path}...")
resp = requests.get(url, headers=headers, stream=True, timeout=60) if resp.status_code == 416: print("✅ File đã được tải đầy đủ (HTTP 416)!") return target_path
if resp.status_code not in (200, 206): resp.raise_for_status()
total_bytes = total_remote_bytes if total_remote_bytes is not None else (existing_bytes + int(resp.headers.get("content-length", 0))) remaining_mb = (total_bytes - existing_bytes) / (1024*1024) print(f"📊 Còn lại: {remaining_mb:.2f} MB / Tổng: {total_bytes / (1024*1024):.2f} MB")
mode = "ab" if existing_bytes > 0 and resp.status_code == 206 else "wb" downloaded = existing_bytes start_time = time.time() last_print = start_time
with open(target_path, mode) as f: for chunk in resp.iter_content(chunk_size=chunk_size): if chunk: f.write(chunk) downloaded += len(chunk) now = time.time() if now - last_print >= 5: speed = (downloaded - existing_bytes) / (now - start_time) / (1024*1024) if (now - start_time) > 0 else 0 percent = (downloaded / total_bytes * 100) if total_bytes > 0 else 0 print(f"⚡ Đã tải: {downloaded / (1024*1024):.1f} MB / {total_bytes / (1024*1024):.1f} MB ({percent:.1f}%) | Tốc độ: {speed:.2f} MB/s", flush=True) last_print = now
if os.path.exists(target_path) and os.path.getsize(target_path) >= total_bytes: print(f"\n✅ Tải hoàn tất 100%! Tổng dung lượng: {os.path.getsize(target_path) / (1024*1024):.2f} MB") return target_path except Exception as e: print(f"⚠️ Mạng gián đoạn: {e}. Đang tự động kết nối lại sau 3 giây...") time.sleep(3)
raise RuntimeError(f"❌ Không thể tải file sau {max_retries} lần thử!")
def main(): sys.stdout.reconfigure(encoding='utf-8', errors='replace') sys.stderr.reconfigure(encoding='utf-8', errors='replace')
print("=" * 80) print("🚀 ĐỒNG BỘ VÀ TẢI CHECKPOINT V25 STAGE 1 TỪ KAGGLE") print("=" * 80)
kaggle_auth.init_kaggle_auth() api = KaggleApi() api.authenticate()
kernel_id = "gustavnguyen/paddleocr-cham-v25-stage1" output_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "output", "v25_stage1")) os.makedirs(output_dir, exist_ok=True)
print(f"🔍 Đang truy vấn URL tải từ kernel: {kernel_id}...") owner, slug, _ = api.parse_kernel_string(kernel_id) req = ApiListKernelSessionOutputRequest() req.user_name = owner req.kernel_slug = slug
client = api.build_kaggle_client() res = client.kernels.kernels_api_client.list_kernel_session_output(req)
if not res.files: print("❌ LỖI: Không tìm thấy file output nào trên Kaggle!") return 1
print(f"📦 Tìm thấy {len(res.files)} file(s) trong output của kernel:") for i, f in enumerate(res.files): print(f" [{i+1}] {f.file_name} (URL: {f.url[:50]}...)")
# Tải từng file downloaded_zips = [] for f_info in res.files: target_file = os.path.join(output_dir, f_info.file_name) print(f"\n⬇️ Đang xử lý tải: {f_info.file_name}...") download_file(f_info.url, target_file) if target_file.endswith(".zip"): downloaded_zips.append(target_file)
# Giải nén extract_dir = os.path.join(output_dir, "extracted") os.makedirs(extract_dir, exist_ok=True) final_ckpt_dir = os.path.join(output_dir, "stage1_final_checkpoint") os.makedirs(final_ckpt_dir, exist_ok=True)
for zip_path in downloaded_zips: print(f"\n📂 Đang kiểm tra tệp ZIP: {os.path.basename(zip_path)} ({os.path.getsize(zip_path)/(1024*1024):.2f} MB)...") try: with zipfile.ZipFile(zip_path, 'r') as z: namelist = z.namelist() print(f" • Tổng số file bên trong: {len(namelist)}") # Nếu chính file này là checkpoint zip if "rec_cham_v25_stage1_checkpoint" in os.path.basename(zip_path): print(f" 🎯 Đây là file checkpoint stage 1! Đang giải nén vào {final_ckpt_dir}...") z.extractall(final_ckpt_dir) print(f" ✅ Đã giải nén xong vào: {final_ckpt_dir}") else: for item in namelist: if any(k in item for k in ['rec_cham_v25', 'best_accuracy', 'cham_dict', 'cham_v25_val']): z.extract(item, extract_dir) print(f" + Đã trích xuất: {item}") except Exception as e: print(f" ⚠️ Lỗi giải nén {zip_path}: {e}")
# Kiểm tra nếu có rec_cham_v25_stage1_checkpoint.zip nằm bên trong extract_dir stage1_nested = None for root, _, files in os.walk(extract_dir): for f in files: if f == "rec_cham_v25_stage1_checkpoint.zip": stage1_nested = os.path.join(root, f) break if stage1_nested: print(f"\n🎉 Tìm thấy file nén con: {stage1_nested} ({os.path.getsize(stage1_nested)/(1024*1024):.2f} MB)") with zipfile.ZipFile(stage1_nested, 'r') as sz: sz.extractall(final_ckpt_dir) print(f"✅ ĐÃ GIẢI NÉN TOÀN BỘ CHECKPOINT VÀO: {final_ckpt_dir}")
print("\n" + "=" * 80) print("🎉 HOÀN TẤT ĐỒNG BỘ CHECKPOINT V25 STAGE 1 VỀ MÁY CỤC BỘ!") print("=" * 80) return 0
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211#!/usr/bin/env python3# -*- coding: utf-8 -*-"""High-Speed Streaming Downloader cho Checkpoint V25 Stage 2.Trích xuất trực tiếp các byte range của rec_cham_v25_stage2_checkpoint.zip và cham_v25_val_freeze.zipqua single persistent HTTP stream with resume capability."""
import osimport sysimport ioimport timeimport structimport requestsimport zipfileimport pickleimport shutil
if sys.stdout and hasattr(sys.stdout, 'reconfigure'): sys.stdout.reconfigure(encoding='utf-8')
sys.path.insert(0, os.path.dirname(__file__))import kaggle_authfrom kaggle.api.kaggle_api_extended import ApiListKernelSessionOutputRequestfrom kaggle_ops import get_authenticated_api
class HttpRangeReader(io.RawIOBase): def __init__(self, url, size): self.url = url self.size = size self.pos = 0 def seek(self, offset, whence=io.SEEK_SET): if whence == io.SEEK_SET: self.pos = offset elif whence == io.SEEK_CUR: self.pos += offset elif whence == io.SEEK_END: self.pos = self.size + offset return self.pos def tell(self): return self.pos def seekable(self): return True def readable(self): return True def readinto(self, b): if self.pos >= self.size: return 0 end = min(self.pos + len(b) - 1, self.size - 1) r = requests.get(self.url, headers={'Range': f'bytes={self.pos}-{end}'}, timeout=30) data = r.content b[:len(data)] = data self.pos += len(data) return len(data)
def stream_download_range(url, start_byte, end_byte, dest_path, desc=""): total_bytes = end_byte - start_byte + 1 existing = os.path.getsize(dest_path) if os.path.exists(dest_path) else 0
if existing == total_bytes: print(f"✅ Đã có sẵn hoàn chỉnh: {desc} ({existing / (1024*1024):.2f} MB)") return
if existing > total_bytes: os.remove(dest_path) existing = 0
resume_start = start_byte + existing headers = {"Range": f"bytes={resume_start}-{end_byte}"}
print(f"⬇️ Đang tải {desc} ({total_bytes / (1024*1024):.2f} MB)...") if existing > 0: print(f" 🔄 Resume từ byte {existing} ({existing / (1024*1024):.2f} MB)...")
mode = "ab" if existing > 0 else "wb" t0 = time.time() last_print = t0 downloaded_this_run = 0
with requests.get(url, headers=headers, stream=True, timeout=120) as r: r.raise_for_status() with open(dest_path, mode) as f: for chunk in r.iter_content(chunk_size=1024 * 1024 * 4): # 4 MB chunks if chunk: f.write(chunk) downloaded_this_run += len(chunk) curr_total = existing + downloaded_this_run now = time.time() if now - last_print >= 5.0 or curr_total == total_bytes: speed = (downloaded_this_run / (1024 * 1024)) / max(now - t0, 0.1) pct = curr_total / total_bytes * 100 print(f" 📊 [{pct:5.1f}%] {curr_total / (1024*1024):.1f} / {total_bytes / (1024*1024):.1f} MB ({speed:.1f} MB/s)", flush=True) last_print = now
el = time.time() - t0 avg_speed = (downloaded_this_run / (1024 * 1024)) / max(el, 0.1) print(f"✅ Hoàn tất tải {desc} trong {el:.1f}s ({avg_speed:.1f} MB/s)!")
def main(): owner = "gustavnguyen" slug = "paddleocr-cham-v25-stage2" scripts_dir = os.path.dirname(os.path.abspath(__file__)) training_dir = os.path.dirname(scripts_dir) output_dir = os.path.join(training_dir, "output", "v25_stage2") final_ckpt_dir = os.path.join(output_dir, "stage2_final_checkpoint") dataset_dir = os.path.join(training_dir, "output", "v25_stage2_dataset")
os.makedirs(output_dir, exist_ok=True) os.makedirs(final_ckpt_dir, exist_ok=True) os.makedirs(dataset_dir, exist_ok=True)
print("=" * 80) print("🚀 HIGH-SPEED STREAMING EXTRACTOR - CHAM-OCR V25 STAGE 2") print(f" • Kernel : {owner}/{slug}") print(f" • Thư mục : {output_dir}") print("=" * 80)
api = get_authenticated_api() client = api.build_kaggle_client() req = ApiListKernelSessionOutputRequest() req.user_name = owner req.kernel_slug = slug
print("\n🔍 Đang truy vấn danh sách output file trên Kaggle...") res = client.kernels.kernels_api_client.list_kernel_session_output(req) if not res.files: print("❌ Không tìm thấy file output nào!") return 1
url = res.files[0].url r = requests.get(url, headers={'Range': 'bytes=0-0'}) total_bytes = int(r.headers.get('Content-Range', '').split('/')[-1]) print(f"🌐 Remote _output_.zip size: {total_bytes / (1024*1024):.2f} MB")
print("\n📖 Đang đọc Central Directory của archive...") reader = HttpRangeReader(url, total_bytes) zf = zipfile.ZipFile(reader) print(f"✅ Đ�� tải Central Directory: {len(zf.namelist()):,} files trong archive.")
# Tìm chính xác byte offsets của các file zip lưu trữ (compress_type=0) stored_targets = [ "rec_cham_v25_stage2_checkpoint.zip", "cham_v25_val_freeze.zip" ]
for name in stored_targets: if name in zf.namelist(): info = zf.getinfo(name) assert info.compress_type == 0, f"{name} không phải STORED zip!" # Đọc 30 bytes header cục bộ để tính data_start h_r = requests.get(url, headers={'Range': f'bytes={info.header_offset}-{info.header_offset+64}'}, timeout=30) sig, ver, flags, comp, mtime, mdate, crc, csize, usize, fname_len, extra_len = struct.unpack('<IHHHHHIIIHH', h_r.content[:30]) data_start = info.header_offset + 30 + fname_len + extra_len data_end = data_start + info.compress_size - 1
dest_path = os.path.join(output_dir, name) stream_download_range(url, data_start, data_end, dest_path, desc=name)
# Giải nén rec_cham_v25_stage2_checkpoint.zip vào final_ckpt_dir stage2_zip = os.path.join(output_dir, "rec_cham_v25_stage2_checkpoint.zip") if os.path.exists(stage2_zip): print(f"\n📦 Đang giải nén Checkpoint vào {final_ckpt_dir}...") with zipfile.ZipFile(stage2_zip, 'r') as sz: for m in sz.namelist(): fname = os.path.basename(m) if fname: target_fp = os.path.join(final_ckpt_dir, fname) with sz.open(m) as sf, open(target_fp, 'wb') as df: shutil.copyfileobj(sf, df) print("✅ Giải nén toàn bộ Checkpoint hoàn tất!")
# Chuẩn bị dataset folder cho Stage 3 print("\n📁 Đang chuẩn bị thư mục Dataset Stage 2 cho Chặng 3...") for f in ["rec_cham_v25_stage2_checkpoint.zip", "cham_v25_val_freeze.zip"]: src_p = os.path.join(output_dir, f) dst_p = os.path.join(dataset_dir, f) if os.path.exists(src_p): if not os.path.exists(dst_p) or os.path.getsize(dst_p) != os.path.getsize(src_p): print(f" Copy {f} sang {dataset_dir}...") shutil.copy2(src_p, dst_p)
dict_src = os.path.join(training_dir, "data", "cham_dict_v25.txt") if os.path.exists(dict_src): shutil.copy2(dict_src, os.path.join(dataset_dir, "cham_dict_v25.txt"))
# Tạo dataset-metadata.json meta_p = os.path.join(dataset_dir, "dataset-metadata.json") import json meta = { "title": "cham-ocr-v25-stage2-checkpoint", "id": "gustavnguyen/cham-ocr-v25-stage2-checkpoint", "licenses": [{"name": "CC0-1.0"}] } with open(meta_p, 'w', encoding='utf-8') as f: json.dump(meta, f, indent=2) print("✅ Đã tạo dataset-metadata.json cho gustavnguyen/cham-ocr-v25-stage2-checkpoint.")
# Đọc states để xác minh states_p = os.path.join(final_ckpt_dir, "latest.states") if os.path.exists(states_p): with open(states_p, 'rb') as f: st = pickle.load(f) print("\n" + "=" * 65) print("🎯 XÁC MINH TRẠNG THÁI CHECKPOINT RESUME STAGE 2 CỤC BỘ:") print(f" • Epoch đã lưu : {st.get('epoch')}") print(f" • Global step : {st.get('global_step')}") best_d = st.get('best_model_dict', {}) print(f" • Best Accuracy : {best_d.get('acc', 'N/A'):.4%}") print(f" • Best Edit Distance : {best_d.get('norm_edit_dis', 'N/A'):.4%}") print(f" • Best Epoch : {best_d.get('best_epoch')}") print("=" * 65)
print("\n🎉 HOÀN TẤT ĐỒNG BỘ CHECKPOINT V25 STAGE 2 VỀ MÁY CỤC BỘ!") return 0
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181#!/usr/bin/env python3# -*- coding: utf-8 -*-"""High-Speed Streaming Downloader cho Checkpoint V25 Stage 3 (Final Stage).Trích xuất trực tiếp các byte range của rec_cham_v25_stage3_checkpoint.zipqua single persistent HTTP stream with resume capability."""
import osimport sysimport ioimport timeimport structimport requestsimport zipfileimport pickleimport shutil
if sys.stdout and hasattr(sys.stdout, 'reconfigure'): sys.stdout.reconfigure(encoding='utf-8')
sys.path.insert(0, os.path.dirname(__file__))import kaggle_authfrom kaggle.api.kaggle_api_extended import ApiListKernelSessionOutputRequestfrom kaggle_ops import get_authenticated_api
class HttpRangeReader(io.RawIOBase): def __init__(self, url, size): self.url = url self.size = size self.pos = 0 def seek(self, offset, whence=io.SEEK_SET): if whence == io.SEEK_SET: self.pos = offset elif whence == io.SEEK_CUR: self.pos += offset elif whence == io.SEEK_END: self.pos = self.size + offset return self.pos def tell(self): return self.pos def seekable(self): return True def readable(self): return True def readinto(self, b): if self.pos >= self.size: return 0 end = min(self.pos + len(b) - 1, self.size - 1) r = requests.get(self.url, headers={'Range': f'bytes={self.pos}-{end}'}, timeout=30) data = r.content b[:len(data)] = data self.pos += len(data) return len(data)
def stream_download_range(url, start_byte, end_byte, dest_path, desc=""): total_bytes = end_byte - start_byte + 1 existing = os.path.getsize(dest_path) if os.path.exists(dest_path) else 0
if existing == total_bytes: print(f"✅ Đã có sẵn hoàn chỉnh: {desc} ({existing / (1024*1024):.2f} MB)") return
if existing > total_bytes: os.remove(dest_path) existing = 0
resume_start = start_byte + existing headers = {"Range": f"bytes={resume_start}-{end_byte}"}
print(f"⬇️ Đang tải {desc} ({total_bytes / (1024*1024):.2f} MB)...") if existing > 0: print(f" 🔄 Resume từ byte {existing} ({existing / (1024*1024):.2f} MB)...")
mode = "ab" if existing > 0 else "wb" t0 = time.time() last_print = t0 downloaded_this_run = 0
with requests.get(url, headers=headers, stream=True, timeout=120) as r: r.raise_for_status() with open(dest_path, mode) as f: for chunk in r.iter_content(chunk_size=1024 * 1024 * 4): # 4 MB chunks if chunk: f.write(chunk) downloaded_this_run += len(chunk) curr_total = existing + downloaded_this_run now = time.time() if now - last_print >= 5.0 or curr_total == total_bytes: speed = (downloaded_this_run / (1024 * 1024)) / max(now - t0, 0.1) pct = curr_total / total_bytes * 100 print(f" 📊 [{pct:5.1f}%] {curr_total / (1024*1024):.1f} / {total_bytes / (1024*1024):.1f} MB ({speed:.1f} MB/s)", flush=True) last_print = now
el = time.time() - t0 avg_speed = (downloaded_this_run / (1024 * 1024)) / max(el, 0.1) print(f"✅ Hoàn tất tải {desc} trong {el:.1f}s ({avg_speed:.1f} MB/s)!")
def main(): owner = "gustavnguyen" slug = "paddleocr-cham-v25-stage3" scripts_dir = os.path.dirname(os.path.abspath(__file__)) training_dir = os.path.dirname(scripts_dir) output_dir = os.path.join(training_dir, "output", "v25_stage3") final_ckpt_dir = os.path.join(output_dir, "stage3_final_checkpoint")
os.makedirs(output_dir, exist_ok=True) os.makedirs(final_ckpt_dir, exist_ok=True)
print("=" * 80) print("🚀 HIGH-SPEED STREAMING EXTRACTOR - CHAM-OCR V25 STAGE 3 (FINAL)") print(f" • Kernel : {owner}/{slug}") print(f" • Thư mục : {output_dir}") print("=" * 80)
api = get_authenticated_api() client = api.build_kaggle_client() req = ApiListKernelSessionOutputRequest() req.user_name = owner req.kernel_slug = slug
print("\n🔍 Đang truy vấn danh sách output file trên Kaggle...") res = client.kernels.kernels_api_client.list_kernel_session_output(req) if not res.files: print("❌ Không tìm thấy file output nào!") return 1
url = res.files[0].url r = requests.get(url, headers={'Range': 'bytes=0-0'}) total_bytes = int(r.headers.get('Content-Range', '').split('/')[-1]) print(f"🌐 Remote _output_.zip size: {total_bytes / (1024*1024):.2f} MB")
print("\n📖 Đang đọc Central Directory của archive...") reader = HttpRangeReader(url, total_bytes) zf = zipfile.ZipFile(reader) print(f"✅ Đã tải Central Directory: {len(zf.namelist()):,} files trong archive.")
stored_targets = [ "rec_cham_v25_stage3_checkpoint.zip" ]
for name in stored_targets: if name in zf.namelist(): info = zf.getinfo(name) assert info.compress_type == 0, f"{name} không phải STORED zip!" # Đọc 30 bytes header cục bộ để tính data_start h_r = requests.get(url, headers={'Range': f'bytes={info.header_offset}-{info.header_offset+64}'}, timeout=30) sig, ver, flags, comp, mtime, mdate, crc, csize, usize, fname_len, extra_len = struct.unpack('<IHHHHHIIIHH', h_r.content[:30]) data_start = info.header_offset + 30 + fname_len + extra_len data_end = data_start + info.compress_size - 1
dest_path = os.path.join(output_dir, name) stream_download_range(url, data_start, data_end, dest_path, desc=name)
# Giải nén rec_cham_v25_stage3_checkpoint.zip vào final_ckpt_dir stage3_zip = os.path.join(output_dir, "rec_cham_v25_stage3_checkpoint.zip") if os.path.exists(stage3_zip): print(f"\n📦 Đang giải nén Checkpoint vào {final_ckpt_dir}...") with zipfile.ZipFile(stage3_zip, 'r') as sz: for m in sz.namelist(): fname = os.path.basename(m) if fname: target_fp = os.path.join(final_ckpt_dir, fname) with sz.open(m) as sf, open(target_fp, 'wb') as df: shutil.copyfileobj(sf, df) print("✅ Giải nén toàn bộ Checkpoint Chặng 3 hoàn tất!")
# Đọc states để xác minh states_p = os.path.join(final_ckpt_dir, "latest.states") if os.path.exists(states_p): with open(states_p, 'rb') as f: st = pickle.load(f) print("\n" + "=" * 65) print("🎯 XÁC MINH TRẠNG THÁI CHECKPOINT RESUME STAGE 3 CỤC BỘ:") print(f" • Epoch đã lưu : {st.get('epoch')}") print(f" • Global step : {st.get('global_step')}") best_d = st.get('best_model_dict', {}) print(f" • Best Accuracy : {best_d.get('acc', 'N/A'):.4%}") print(f" • Best Edit Distance : {best_d.get('norm_edit_dis', 'N/A'):.4%}") print(f" • Best Epoch : {best_d.get('best_epoch')}") print("=" * 65)
print("\n🎉 HOÀN TẤT ĐỒNG BỘ CHECKPOINT V25 STAGE 3 (FINAL) VỀ MÁY CỤC BỘ!") return 0
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155#!/usr/bin/env python3# -*- coding: utf-8 -*-"""Dry-Run Verification Script for Cham-OCR V25 40-Epoch Cosine Schedule.Simulates and verifies: 1. Total epochs, stage ends, steps/epoch, global batch, warmup steps, T_max. 2. Mathematical LR milestones for epochs 2, 12, 13, 22, 23, 40. 3. Continuous schedule invariant (no resets across stage boundaries). 4. Dictionary hash and token count invariance."""
import osimport sysimport mathimport hashlibimport yaml
if sys.stdout and hasattr(sys.stdout, 'reconfigure'): sys.stdout.reconfigure(encoding='utf-8')
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))TRAINING_DIR = os.path.dirname(SCRIPT_DIR)PROJECT_ROOT = os.path.dirname(TRAINING_DIR)
CONFIG_PATH = os.path.join(TRAINING_DIR, "configs", "rec_cham_v25.yml")DICT_PATH = os.path.join(TRAINING_DIR, "data", "cham_dict_v25.txt")
def calculate_lr(step, warmup_steps, T_max, base_lr): if step <= warmup_steps: return base_lr * (step / warmup_steps) else: inner_step = step - warmup_steps ratio = inner_step / T_max return 0.5 * base_lr * (1.0 + math.cos(math.pi * ratio))
def run_dry_run(): print("=" * 80) print("🔬 BẮT ĐẦU DRY-RUN KIỂM THỬ INVARIANTS HUẤN LUYỆN V25 (40 EPOCHS)") print("=" * 80)
# 1. Đọc và kiểm tra file config rec_cham_v25.yml assert os.path.exists(CONFIG_PATH), f"Không tìm thấy {CONFIG_PATH}" with open(CONFIG_PATH, 'r', encoding='utf-8') as f: cfg = yaml.safe_load(f)
epoch_num = cfg['Global']['epoch_num'] stage_end_epoch = cfg['Global'].get('stage_end_epoch', 12) batch_size_per_card = cfg['Train']['loader']['batch_size_per_card'] num_gpus = 2 global_batch = batch_size_per_card * num_gpus
train_samples = 140000 steps_per_epoch = train_samples // global_batch warmup_epochs = cfg['Optimizer']['lr']['warmup_epoch'] warmup_steps = warmup_epochs * steps_per_epoch base_lr = float(cfg['Optimizer']['lr']['learning_rate']) T_max = epoch_num * steps_per_epoch
print("\n📋 1. THAM SỐ CẤU HÌNH & HẠ TẦNG TOÀN CỤC:") print(f" • Total Epochs toàn training : {epoch_num}") print(f" • Stage End Epoch (Chặng 1) : {stage_end_epoch}") print(f" • Batch size per card (GPU) : {batch_size_per_card}") print(f" • Số lượng GPU phân tán : {num_gpus} (Tesla T4x2)") print(f" • Global Batch Size hiệu dụng: {global_batch}") print(f" • Quy mô mẫu Train : {train_samples:,} mẫu") print(f" • Steps per Epoch : {steps_per_epoch} steps/epoch") print(f" • Warmup Epochs : {warmup_epochs} epochs") print(f" • Warmup Steps : {warmup_steps} steps") print(f" • T_max (Toàn bộ chu kỳ) : {T_max} steps") print(f" • Base Learning Rate (η_max) : {base_lr:.6f} ({base_lr})")
# Invariants assertions assert epoch_num == 40, f"Global.epoch_num phải bằng 40, hiện tại là {epoch_num}" assert steps_per_epoch == 2187, f"steps_per_epoch phải bằng 2187, hiện tại là {steps_per_epoch}" assert global_batch == 64, f"global_batch phải bằng 64, hiện tại là {global_batch}" assert warmup_steps == 4374, f"warmup_steps phải bằng 4374, hiện tại là {warmup_steps}" assert T_max == 87480, f"T_max phải bằng 87480, hiện tại là {T_max}" print(" 👉 [INVARIANT 1]: Cấu hình 40 epochs & batch steps: 100% PASS!")
# 2. Kiểm tra bộ từ điển V25 (Dictionary Freeze) assert os.path.exists(DICT_PATH), f"Không tìm thấy {DICT_PATH}" with open(DICT_PATH, 'r', encoding='utf-8') as f: tokens = [line.strip() for line in f if line.strip()] dict_md5 = hashlib.md5(open(DICT_PATH, 'rb').read()).hexdigest() dict_sha256 = hashlib.sha256(open(DICT_PATH, 'rb').read()).hexdigest()
print("\n📖 2. KIỂM ĐỊNH TỪ ĐIỂN V25 (DICTIONARY FREEZE):") print(f" • Số lượng tokens NFC : {len(tokens)} tokens") print(f" • MD5 Checksum : {dict_md5}") print(f" • SHA256 Checksum : {dict_sha256[:24]}...") assert len(tokens) == 162, f"Từ điển phải có đúng 162 tokens, hiện tại: {len(tokens)}" print(" 👉 [INVARIANT 2]: Từ điển và Token IDs khóa cứng: 100% PASS!")
# 3. Tính toán và xác thực Learning Rate tại các mốc trọng yếu print("\n📈 3. BẢNG MỐC LEARNING RATE TRẢI DÀI 40 EPOCHS (87,480 STEPS):") print("-" * 88) print(f"{'Mốc Thời Điểm':<32} | {'Epoch':<6} | {'Step':<7} | {'Cosine Ratio':<12} | {'Learning Rate':<18}") print("-" * 88)
milestones = [ ("Khởi đầu Warmup", 0, 1, "0.0000"), ("Giữa Warmup (Epoch 1)", 1, 1 * steps_per_epoch, "0.0000"), ("Cuối Warmup (Epoch 2)", 2, 2 * steps_per_epoch, "0.0000"), ("Cuối Chặng 1 (Epoch 12)", 12, 12 * steps_per_epoch, "0.2500"), ("Đầu Chặng 2 (Epoch 13)", 13, 12 * steps_per_epoch + 1, "0.2500"), ("Cuối Chặng 2 (Epoch 22)", 22, 22 * steps_per_epoch, "0.5000"), ("Đầu Chặng 3 (Epoch 23)", 23, 22 * steps_per_epoch + 1, "0.5000"), ("Tiệm cận cuối (Epoch 35)", 35, 35 * steps_per_epoch, "0.8250"), ("Kết thúc Toàn bộ (Epoch 40)", 40, 40 * steps_per_epoch, "0.9500") ]
calculated_lrs = {} for desc, ep, step, expected_ratio in milestones: lr_val = calculate_lr(step, warmup_steps, T_max, base_lr) calculated_lrs[ep] = lr_val inner_step = max(0, step - warmup_steps) ratio = inner_step / T_max print(f"{desc:<32} | {ep:<6} | {step:<7} | {ratio:<12.4f} | {lr_val:.8e}")
print("-" * 88)
# Xác thực toán học các mốc yêu cầu lr_ep2 = calculated_lrs[2] lr_ep12 = calculated_lrs[12] lr_ep13 = calculated_lrs[13] lr_ep22 = calculated_lrs[22] lr_ep23 = calculated_lrs[23] lr_ep40 = calculated_lrs[40]
assert abs(lr_ep2 - 1.0e-4) < 1e-9, f"LR Epoch 2 phải bằng 1e-4, tính ra: {lr_ep2}" assert abs(lr_ep12 - 8.53553391e-5) < 1e-9, f"LR Epoch 12 phải bằng 8.5355e-5, tính ra: {lr_ep12}" assert abs(lr_ep13 - 8.53540694e-5) < 1e-9, f"LR Epoch 13 phải bằng 8.5354e-5, tính ra: {lr_ep13}" assert abs(lr_ep22 - 5.0e-5) < 1e-9, f"LR Epoch 22 phải bằng 5.0e-5, tính ra: {lr_ep22}" assert abs(lr_ep23 - 4.99982044e-5) < 1e-9, f"LR Epoch 23 phải bằng 4.9998e-5, tính ra: {lr_ep23}" assert abs(lr_ep40 - 6.15582970e-7) < 1e-9, f"LR Epoch 40 phải bằng 6.1558e-7, tính ra: {lr_ep40}"
# Kiểm tra tính liên tục qua ranh giới chặng (Stage boundary continuity) step_diff_12_13 = abs(lr_ep12 - lr_ep13) step_diff_22_23 = abs(lr_ep22 - lr_ep23) print(f"\n🔄 4. ĐỘ LIÊN TỤC TẠI RANH GIỚI CÁC CHẶNG:") print(f" • Chặng 1 -> Chặng 2 (Epoch 12 -> 13): Bước nhảy Δ = {step_diff_12_13:.2e} (Hoàn toàn mượt mà)") print(f" • Chặng 2 -> Chặng 3 (Epoch 22 -> 23): Bước nhảy Δ = {step_diff_22_23:.2e} (Hoàn toàn mượt mà)") assert step_diff_12_13 < 1e-7, "Bước nhảy LR giữa Chặng 1 và Chặng 2 không liên tục!" assert step_diff_22_23 < 1e-7, "Bước nhảy LR giữa Chặng 2 và Chặng 3 không liên tục!" print(" 👉 [INVARIANT 3]: Tính liên tục toán học toàn cục: 100% PASS!")
print("\n🎉 TOÀN BỘ CÁC INVARIANTS ĐÃ ĐƯỢC XÁC THỰC THÀNH CÔNG!") print("=" * 80) return True
if __name__ == '__main__': run_dry_run()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647import reimport syssys.stdout.reconfigure(encoding='utf-8')
log_path = r'C:\Users\admin\.gemini\antigravity\brain\4840561f-5c42-4e77-b2e3-145dae823fb9\.system_generated\tasks\task-4158.log'epochs = {}evals = []
with open(log_path, 'r', encoding='utf-8', errors='ignore') as f: for line in f: m = re.search(r'epoch: \[(\d+)/40\], global_step: (\d+), lr: ([0-9.e-]+), CTCLoss: ([0-9.]+), NRTRLoss: ([0-9.]+), loss: ([0-9.]+)', line) if m: ep = int(m.group(1)) ctc = float(m.group(4)) nrtr = float(m.group(5)) loss = float(m.group(6)) if ep not in epochs: epochs[ep] = {'ctc': [], 'nrtr': [], 'loss': []} epochs[ep]['ctc'].append(ctc) epochs[ep]['nrtr'].append(nrtr) epochs[ep]['loss'].append(loss) m_eval = re.search(r'\[([^\]]+)\] ppocr INFO: cur metric, acc: ([0-9.]+), norm_edit_dis: ([0-9.]+)', line) if m_eval: evals.append({ 'time': m_eval.group(1), 'acc': float(m_eval.group(2)), 'ned': float(m_eval.group(3)) })
print("=== TIẾN TRÌNH LOSS TỪNG EPOCH (CHẶNG 3) ===")for ep in sorted(epochs.keys()): c = epochs[ep] avg_loss = sum(c['loss']) / len(c['loss']) avg_ctc = sum(c['ctc']) / len(c['ctc']) avg_nrtr = sum(c['nrtr']) / len(c['nrtr']) min_loss = min(c['loss']) min_ctc = min(c['ctc']) print(f"Epoch {ep:02d}: Avg Loss = {avg_loss:.4f} [Min: {min_loss:.3f}], Avg CTCLoss = {avg_ctc:.4f} [Min: {min_ctc:.3f}], NRTRLoss = {avg_nrtr:.4f} ({len(c['loss'])} log points)")
print("\n=== CÁC MỐC ĐÁNH GIÁ (EVAL) NỔI BẬT CHẶNG 3 ===")# Sort by acc descendingsorted_evals = sorted(evals, key=lambda x: x['acc'], reverse=True)for i, ev in enumerate(sorted_evals[:8]): print(f"Top {i+1}: Thời điểm {ev['time']} | Acc = {ev['acc']*100:.2f}% | Norm Edit Dis = {ev['ned']*100:.2f}%")
print(f"\nTổng số lần đánh giá định kỳ trong Chặng 3: {len(evals)}")12345678910111213141516171819202122232425262728293031323334import reimport os
def analyze_losses(path): epochs = {} if not os.path.exists(path): print(f"File not found: {path}") return with open(path, 'r', encoding='utf-8', errors='ignore') as f: for line in f: m = re.search(r'epoch: \[(\d+)/\d+\], global_step: (\d+), lr: ([0-9.e-]+), CTCLoss: ([0-9.]+), NRTRLoss: ([0-9.]+), loss: ([0-9.]+)', line) if m: ep = int(m.group(1)) ctc = float(m.group(4)) nrtr = float(m.group(5)) loss = float(m.group(6)) if ep not in epochs: epochs[ep] = {'ctc': [], 'nrtr': [], 'loss': []} epochs[ep]['ctc'].append(ctc) epochs[ep]['nrtr'].append(nrtr) epochs[ep]['loss'].append(loss) for ep in sorted(epochs.keys()): c = epochs[ep] avg_loss = sum(c['loss']) / len(c['loss']) avg_ctc = sum(c['ctc']) / len(c['ctc']) avg_nrtr = sum(c['nrtr']) / len(c['nrtr']) min_loss = min(c['loss']) max_loss = max(c['loss']) print(f"Epoch {ep:02d}: loss={avg_loss:.4f} [min: {min_loss:.3f}, max: {max_loss:.3f}], CTCLoss={avg_ctc:.4f}, NRTRLoss={avg_nrtr:.4f} ({len(c['loss'])} log points)")
print("=== STAGE 1 LOSSES ===")analyze_losses(r"ocr-training/output/v25_stage1/stage1_final_checkpoint/output/rec_cham_v25/train.log")print("\n=== STAGE 2 LOSSES ===")analyze_losses(r"ocr-training/output/v25_stage2/stage2_final_checkpoint/train.log")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758import osimport sys
# NumPy 2.x compatibility monkeypatchimport numpy as npif not hasattr(np, 'sctypes'): np.sctypes = {'int': [np.int8, np.int16, np.int32, np.int64], 'uint': [np.uint8, np.uint16, np.uint32, np.uint64], 'float': [np.float16, np.float32, np.float64], 'complex': [np.complex64, np.complex128], 'others': [bool, object, bytes, str]}if not hasattr(np, 'bool'): np.bool = boolif not hasattr(np, 'int'): np.int = intif not hasattr(np, 'float'): np.float = floatif not hasattr(np, 'typeDict'): np.typeDict = {}
import yamlimport paddleimport shutil
# Add PaddleOCR to sys.pathBASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))PADDLEOCR_DIR = os.path.join(BASE_DIR, "ocr-studio", "PaddleOCR")if PADDLEOCR_DIR not in sys.path: sys.path.insert(0, PADDLEOCR_DIR)
from ppocr.utils.export_model import export
def run_export(): config_path = os.path.join(BASE_DIR, "ocr-training", "configs", "rec_cham_v25.yml") ckpt_path = os.path.join(BASE_DIR, "ocr-training", "output", "v25_stage3", "stage3_final_checkpoint", "best_accuracy") save_dir = os.path.join(BASE_DIR, "ocr-studio", "data", "output", "rec_cham_inference_v25") dict_path = os.path.join(BASE_DIR, "ocr-training", "data", "cham_dict_v25.txt")
os.makedirs(save_dir, exist_ok=True)
print(f"Loading config from: {config_path}") with open(config_path, 'r', encoding='utf-8') as f: config = yaml.safe_load(f)
config["Global"]["pretrained_model"] = ckpt_path config["Global"]["checkpoints"] = None config["Global"]["character_dict_path"] = dict_path config["Global"]["save_inference_dir"] = save_dir config["Global"]["export_with_pir"] = True
print(f"Exporting model from checkpoint: {ckpt_path} ...") print(f"Destination inference dir: {save_dir} ...") export(config)
# Copy dict file to save_dir as well dict_dest = os.path.join(save_dir, "cham_dict_v25.txt") shutil.copy2(dict_path, dict_dest) print(f"Copied dictionary to {dict_dest}")
print("\n✅ Export V25 completed successfully! Listing files in save_dir:") for f in os.listdir(save_dir): fp = os.path.join(save_dir, f) print(f" - {f}: {os.path.getsize(fp):,} bytes")
if __name__ == "__main__": run_export()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142#!/usr/bin/env python3# -*- coding: utf-8 -*-"""Comparative Report Generator for Cham-OCR Multi-GPU Benchmarks.Aggregates trials from benchmark_*.json and formats the final Markdown comparison."""
import osimport sysimport globimport jsonimport argparse
if sys.stdout and hasattr(sys.stdout, 'reconfigure'): try: sys.stdout.reconfigure(encoding='utf-8') except Exception: passif sys.stderr and hasattr(sys.stderr, 'reconfigure'): try: sys.stderr.reconfigure(encoding='utf-8') except Exception: pass
def generate_comparative_report(results_dir="benchmark_results", output_md="benchmark_results/COMPARATIVE_REPORT.md"): json_files = glob.glob(os.path.join(results_dir, "benchmark_*.json")) if not json_files: print(f"No benchmark JSON files found in {results_dir}") return
summaries = [] for jf in json_files: try: with open(jf, "r", encoding="utf-8") as f: data = json.load(f) summaries.append(data) except Exception as e: print(f"Error reading {jf}: {e}")
lines = [] lines.append("# Báo Cáo Đối Soánh Hiệu Năng & Chi Phí Huấn Luyện Cham-OCR Đa GPU") lines.append("## (PP-OCRv4 SVTR_LCNet - Pipeline Huấn Luyện Thật)\n")
lines.append("### 1. Bảng Tổng Hợp So Sánh Các Cấu Hình Tối Ưu (Best & Max Batch)") lines.append("| GPU | Phân Loại | Batch | Workers | IPS (mẫu/s) | GPU% | VRAM% | Reader Time | Batch Time | $/h | Est 40 Epoch | Est Cost | IPS/$ |") lines.append("|:---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|")
rankings = []
for s in summaries: gpu = s["gpu_name"] cost = s["cost_per_hour"] workers = s["optimal_workers"] best_b = s["best_batch"] max_b = s["max_safe_batch"] trials = { (t["batch_size"], t["num_workers"]): t for t in s["all_trials"] if t.get("status") == "SUCCESS" }
# Best Trial best_t = trials.get((best_b, workers)) if best_t: lines.append( f"| **{gpu}** | 🌟 **Best** | {best_b} | {workers} | " f"**{best_t['ips']:.1f}** | {best_t['avg_gpu_util']:.0f}% | {best_t['vram_pct']:.1f}% | " f"{best_t['avg_reader_cost']:.4f}s | {best_t['avg_batch_cost']:.4f}s | " f"${cost:.2f} | {best_t['est_40_epoch_hours']:.1f}h | " f"**${best_t['est_40_epoch_cost']:.2f}** | **{best_t['ips_per_dollar']:.1f}** |" ) rankings.append({ "gpu": gpu, "type": "Best", "batch": best_b, "workers": workers, "ips": best_t["ips"], "cost": cost, "est_hours": best_t["est_40_epoch_hours"], "est_cost": best_t["est_40_epoch_cost"], "ips_per_dollar": best_t["ips_per_dollar"], "bottleneck": s["primary_bottleneck"] })
# Max Safe Trial (if different from Best) if max_b != best_b: max_t = trials.get((max_b, workers)) if max_t: lines.append( f"| {gpu} | 🛡️ Max Safe | {max_b} | {workers} | " f"{max_t['ips']:.1f} | {max_t['avg_gpu_util']:.0f}% | {max_t['vram_pct']:.1f}% | " f"{max_t['avg_reader_cost']:.4f}s | {max_t['avg_batch_cost']:.4f}s | " f"${cost:.2f} | {max_t['est_40_epoch_hours']:.1f}h | " f"${max_t['est_40_epoch_cost']:.2f} | {max_t['ips_per_dollar']:.1f} |" )
lines.append("\n### 2. Kết Luận Chi Tiết Cho Từng Machine") for s in summaries: gpu = s["gpu_name"] cost = s["cost_per_hour"] workers = s["optimal_workers"] best_b = s["best_batch"] max_b = s["max_safe_batch"] bottleneck = s["primary_bottleneck"] best_t = s.get("best_trial")
lines.append(f"\n#### 🔹 Machine: **{gpu}** (${cost:.2f}/h)") lines.append(f"- **Max Batch Chạy Được**: `{max_b}` (ngưỡng giới hạn phần cứng trước khi OOM).") lines.append(f"- **Best Batch Nên Dùng**: `{best_b}` (điểm ngọt cho throughput cao nhất trước khi bão hòa).") lines.append(f"- **Num Workers Tối Ưu**: `{workers}` worker.") lines.append(f"- **Điểm Nghẽn Chính (Bottleneck)**: `{bottleneck}`.") if best_t: lines.append(f"- **Thời Gian Huấn Luyện Full 40 Epoch (10,000,000 mẫu)**: `{best_t['est_40_epoch_hours']:.2f} giờ` (~`{best_t['est_40_epoch_hours']*60:.0f} phút`).") lines.append(f"- **Chi Phí Ước Tính Full 40 Epoch**: `${best_t['est_40_epoch_cost']:.2f}`.") lines.append(f"- **Hiệu Năng / Chi Phí (P/P)**: `{best_t['ips_per_dollar']:.1f} mẫu / $`.")
# Sort rankings by IPS/$ descending rankings.sort(key=lambda x: x["ips_per_dollar"], reverse=True) lines.append("\n### 3. Xếp Hạng Hiệu Quả Đầu Tư (Performance / Price Ranking)") lines.append("| Hạng | GPU | Best Batch | Tốc Độ (IPS) | Thời Gian Full 40 Epoch | Tổng Chi Phí ($) | Hiệu Suất Kinh Tế (IPS/$) |") lines.append("|:---:|:---|:---:|:---:|:---:|:---:|:---:|")
for i, r in enumerate(rankings, 1): medal = "🥇" if i == 1 else ("🥈" if i == 2 else ("🥉" if i == 3 else f"#{i}")) lines.append(f"| {medal} | **{r['gpu']}** | {r['batch']} | {r['ips']:.1f} mẫu/s | {r['est_hours']:.1f}h | **${r['est_cost']:.2f}** | **{r['ips_per_dollar']:.1f}** |")
if rankings: top = rankings[0] lines.append(f"\n> 🏆 **LỰA CHỌN TỐI ƯU NHẤT (P/P)**: **{top['gpu']}** là cỗ máy kinh tế nhất với **{top['ips_per_dollar']:.1f} mẫu / $**, tổng chi phí train full 40 epoch chỉ **${top['est_cost']:.2f}** trong **{top['est_hours']:.1f} giờ**.")
report_content = "\n".join(lines) os.makedirs(os.path.dirname(os.path.abspath(output_md)), exist_ok=True) with open(output_md, "w", encoding="utf-8") as f: f.write(report_content)
print(f"\n✅ Comparative report written to: {output_md}") print("\n" + report_content) return report_content
if __name__ == "__main__": parser = argparse.ArgumentParser(description="Generate Comparative Benchmark Report") parser.add_argument("-d", "--results_dir", type=str, default="ocr-training/benchmark_results", help="Directory with benchmark JSONs") parser.add_argument("-o", "--output_md", type=str, default="ocr-training/benchmark_results/COMPARATIVE_REPORT.md", help="Output Markdown report path") args = parser.parse_args()
generate_comparative_report(args.results_dir, args.output_md)24 unmodified lines252627282930313233343536373839404142434422 unmodified lines676869707172737 unmodified lines818283848586877 unmodified lines959697989910015 unmodified lines11611711811912012114 unmodified lines13613713813914014114214314414514614714814915015115215315415515615715815924 unmodified lines# ==============================================================================# 1. Cấu hình Tổ hợp Ký tự & Phân nhóm Hình học tiếng Chăm# ==============================================================================PRE_SIGNS = set('ꨰꨯꨴ')VOWEL_DIACRITIC_SIGNS = set('ꨣꨤꨥꨦꨧꨨꨩꨪꨫꨬꨭꨮꨯꨰꨱꨲꨴꨵ')MEDIAL_SIGNS = set('ꨳ')FINAL_SIGNS = set('ꩀꩃꩌꩍꩆꩉꩊꩂꩅ')CHAM_DIGITS = set('꩐꩑꩒꩓꩔꩕꩖꩗꩘꩙')CHAM_PUNCT_SIGNS = set('꩜꩝꩞꩟')PUNCT_SIGNS = set('꩜꩝꩞꩟.,;:!?')FOCUS_CHARS = PRE_SIGNS | FINAL_SIGNS | MEDIAL_SIGNS | set('ꨱꨵꨮꨯꨰꨴ')CONFUSION_CHARS = set('ꨰꨯꨴꨱꨳꨵꨮꩀꩃꩌꩍꩆꩉꩊꨈꨤꨠꨥꨡꨓꨩ')consonants = set("ꨆꨇꨈꨉꨊꨋꨌꨍꨎꨏꨐꨑꨒꨓꨔꨕꨖꨗꨘꨙꨚꨛꨜꨝꨞꨟꨠꨡꨢꨣꨤꨥꨦꨧꨨꨀꨁꨂꨃꨄꨅ")pre_signs = PRE_SIGNSdiacritics = set(chr(c) for c in range(0xAA29, 0xAA37)) | set(chr(c) for c in range(0xAA40, 0xAA4E))COMBINING_MARKS = PRE_SIGNS | diacritics | FINAL_SIGNS | MEDIAL_SIGNSHEAL_REGEX = re.compile(r'\s+([ꨰꨯꨴꨳꩀꩃꩌꩍꩆꩉꩊꩂꩅ\uAA29-\uAA36\uAA40-\uAA4D])')# Danh sách từ luyện tập cụm chữ khó hay sai trên TestBenchCLUSTER_DRILLS = [22 unmodified linesreturn any(ch in PRE_SIGNS for ch in tok)def has_final(tok):return any(ch in FINAL_SIGNS for ch in tok)def shape_key(tok):"""Phân loại hình thái của token để lập nhóm drill thích hợp"""7 unmodified linesdef token_distance_key(tok):"""Trả về signature rút gọn của chữ để tìm từ đồng dạng (minimal pairs)"""return ''.join('F' if ch in FINAL_SIGNS else 'P' if ch in PRE_SIGNS else 'M' if ch in MEDIAL_SIGNS else 'V' if ch in VOWEL_DIACRITIC_SIGNS else 'B' for ch in tok)def parse_unicode_clusters(text):clusters = []7 unmodified lineswhile i < n and (text[i] in diacritics or text[i] in pre_signs):cluster.append(text[i])i += 1clusters.append(cluster)else:clusters.append([char])15 unmodified lineswhile i < n and text[i] in diacritics and text[i] not in pre_signs:cluster.append(text[i])i += 1clusters.append(cluster)else:clusters.append([text[i]])14 unmodified linesif not has_consonant:return clusterbase_consonant = [c for c in cluster if c in consonants]extracted_pre = [c for c in cluster if c in pre_signs]remaining_diacs = [c for c in cluster if c in diacritics and c not in pre_signs]medials = []others = []for d in remaining_diacs:if d in ('ꨳ', 'ꨵ', 'ꨶ'):medials.append(d)else:others.append(d)pre_ra = [c for c in extracted_pre if c == 'ꨴ']pre_vowels = [c for c in extracted_pre if c in ('ꨯ', 'ꨰ')]# Reconstruct standard relative orderreconstructed_diacs = medials + pre_ra + pre_vowels + othersreturn base_consonant + reconstructed_diacsdef unicode_to_visual(text):clusters = parse_unicode_clusters(text)24 unmodified lines25262728293031323334353637383940414243444546474822 unmodified lines7172737475767778798081827 unmodified lines909192939495969798991001011021031041051061071087 unmodified lines11611711811912012112212312412515 unmodified lines14114214314414514614714814915014 unmodified lines16516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021124 unmodified lines# ==============================================================================# 1. Cấu hình Tổ hợp Ký tự & Phân nhóm Hình học tiếng Chăm# ==============================================================================PRE_SIGNS = set('ꨯꨰ')MEDIAL_SIGNS = set('ꨴꨵꨳꨶ')MEDIAL_RA_LA = set('ꨴꨵ')MEDIAL_YA_WA = set('ꨳꨶ')VOWEL_DIACRITIC_SIGNS = set('ꨩꨪꨫꨬꨭꨮꨯꨰꨱꨲ')FINAL_SIGNS = set(chr(c) for c in range(0xAA40, 0xAA4E))# Per Unicode Standard Chapter 16 Table 16-16, U+AA25 (ꨥ) also functions as syllable-final consonantFINAL_CONSONANTS_OR_VA = FINAL_SIGNS | {'ꨥ'}CHAM_DIGITS = set('꩐꩑꩒꩓꩔꩕꩖꩗꩘꩙')CHAM_PUNCT_SIGNS = set('꩜꩝꩞꩟')PUNCT_SIGNS = set('꩜꩝꩞꩟.,;:!?')FOCUS_CHARS = PRE_SIGNS | FINAL_SIGNS | MEDIAL_SIGNS | VOWEL_DIACRITIC_SIGNSCONFUSION_CHARS = set('ꨯꨰꨴꨵꨳꨶꨪꨫꨬꨭꨮꨱꨲꩀꩃꩌꩍꩆꩉꩊꨈꨤꨠꨥꨡꨓꨩ')consonants = set("ꨆꨇꨈꨉꨊꨋꨌꨍꨎꨏꨐꨑꨒꨓꨔꨕꨖꨗꨘꨙꨚꨛꨜꨝꨞꨟꨠꨡꨢꨣꨤꨥꨦꨧꨨꨀꨁꨂꨃꨄꨅ")pre_signs = PRE_SIGNSdiacritics = set(chr(c) for c in range(0xAA29, 0xAA37)) | set(chr(c) for c in range(0xAA40, 0xAA4E))COMBINING_MARKS = PRE_SIGNS | diacritics | FINAL_SIGNS | MEDIAL_SIGNSHEAL_REGEX = re.compile(r'\s+([ꨯꨰꨴꨵꨳꨶꩀꩃꩌꩍꩆꩉꩊꩂꩅ\uAA29-\uAA36\uAA40-\uAA4D])')# Danh sách từ luyện tập cụm chữ khó hay sai trên TestBenchCLUSTER_DRILLS = [22 unmodified linesreturn any(ch in PRE_SIGNS for ch in tok)def has_final(tok):if any(ch in FINAL_SIGNS for ch in tok):return True# Per Unicode Standard Chapter 16 Table 16-16, U+AA25 (ꨥ) functions as syllable-final consonantif len(tok) > 1 and tok[-1] == 'ꨥ':return Truereturn Falsedef shape_key(tok):"""Phân loại hình thái của token để lập nhóm drill thích hợp"""7 unmodified linesdef token_distance_key(tok):"""Trả về signature rút gọn của chữ để tìm từ đồng dạng (minimal pairs)"""sig = []for idx, ch in enumerate(tok):if ch in FINAL_SIGNS or (idx > 0 and ch == 'ꨥ' and idx == len(tok) - 1):sig.append('F')elif ch in PRE_SIGNS:sig.append('P')elif ch in MEDIAL_SIGNS:sig.append('M')elif ch in VOWEL_DIACRITIC_SIGNS:sig.append('V')else:sig.append('B')return ''.join(sig)def parse_unicode_clusters(text):clusters = []7 unmodified lineswhile i < n and (text[i] in diacritics or text[i] in pre_signs):cluster.append(text[i])i += 1# Per Unicode Table 16-16: U+AA25 (ꨥ) functions as syllable-final consonantif i < n and text[i] == 'ꨥ' and len(cluster) > 1 and (i + 1 == n or text[i+1] in ' \t\n\r' or text[i+1] in PUNCT_SIGNS or text[i+1] in consonants):cluster.append(text[i])i += 1clusters.append(cluster)else:clusters.append([char])15 unmodified lineswhile i < n and text[i] in diacritics and text[i] not in pre_signs:cluster.append(text[i])i += 1# Check for Table 16-16 final VAif i < n and text[i] == 'ꨥ' and (i + 1 == n or text[i+1] in ' \t\n\r' or text[i+1] in PUNCT_SIGNS or text[i+1] in consonants):cluster.append(text[i])i += 1clusters.append(cluster)else:clusters.append([text[i]])14 unmodified linesif not has_consonant:return cluster# Reconstruct according to official Unicode Cham canonical syllabic order (Table 16-16):# 1. Base consonant# 2. Medial RA / LA (ꨴ U+AA34, ꨵ U+AA35)# 3. Medial YA / WA (ꨳ U+AA33, ꨶ U+AA36)# 4. Pre-base vowels (ꨯ U+AA2F, ꨰ U+AA30)# 5. Other dependent vowels (ꨪ, ꨫ, ꨬ, ꨭ, ꨮ, ꨱ, ꨲ)# 6. Vowel lengthener AA (ꨩ U+AA29)# 7. Final consonants & signs (U+AA40-U+AA4D, and final VA U+AA25 per Table 16-16)base_consonant = []medials_ra_la = []medials_ya_wa = []pre_vowels = []other_vowels = []aa_lengthener = []finals = []unclassified = []for c in cluster:if c in consonants:if not base_consonant:base_consonant.append(c)elif c == 'ꨥ':finals.append(c)else:base_consonant.append(c)elif c in ('ꨴ', 'ꨵ'):medials_ra_la.append(c)elif c in ('ꨳ', 'ꨶ'):medials_ya_wa.append(c)elif c in ('ꨯ', 'ꨰ'):pre_vowels.append(c)elif c == 'ꨩ':aa_lengthener.append(c)elif c in ('ꨪ', 'ꨫ', 'ꨬ', 'ꨭ', 'ꨮ', 'ꨱ', 'ꨲ'):other_vowels.append(c)elif c in FINAL_SIGNS or (0xAA40 <= ord(c) <= 0xAA4D):finals.append(c)else:unclassified.append(c)return base_consonant + medials_ra_la + medials_ya_wa + pre_vowels + other_vowels + aa_lengthener + finals + unclassifieddef unicode_to_visual(text):clusters = parse_unicode_clusters(text)
311 unmodified lines312313314315316317318311 unmodified linesos.makedirs(os.path.dirname(corpus_file), exist_ok=True)try:import urllib.requestraw_url = "https://raw.githubusercontent.com/phucsd1/Cham-OCR/main/ocr-training/data/corpus/cham_text.txt"urllib.request.urlretrieve(raw_url, corpus_file)print(f"✅ Đã tải corpus thành công về: {corpus_file}")except Exception as e:311 unmodified lines312313314315316317318311 unmodified linesos.makedirs(os.path.dirname(corpus_file), exist_ok=True)try:import urllib.requestraw_url = "https://raw.githubusercontent.com/phucsd/Cham-OCR/main/ocr-training/data/corpus/cham_text.txt"urllib.request.urlretrieve(raw_url, corpus_file)print(f"✅ Đã tải corpus thành công về: {corpus_file}")except Exception as e:
6 unmodified lines78910111213146 unmodified linesif sys.stdout and hasattr(sys.stdout, 'reconfigure'):sys.stdout.reconfigure(encoding='utf-8')os.environ['KAGGLE_USERNAME'] = 'gustavnguyen'os.environ['KAGGLE_KEY'] = '6bf56db7e5c0fa7895d157167961d92b'from kaggle.api.kaggle_api_extended import KaggleApi6 unmodified lines78910111213146 unmodified linesif sys.stdout and hasattr(sys.stdout, 'reconfigure'):sys.stdout.reconfigure(encoding='utf-8')from kaggle_auth import init_kaggle_authinit_kaggle_auth()from kaggle.api.kaggle_api_extended import KaggleApi
1234567891011121314151617181920212223242526272829303132333435363738394041424344#!/usr/bin/env python3# -*- coding: utf-8 -*-"""Hàm tiện ích nạp Kaggle credentials an toàn từ biến môi trường hoặc tệp .env (không hardcode key)."""
import osimport sys
def init_kaggle_auth(): """Tự động nạp Kaggle credentials an toàn từ .env hoặc biến môi trường.""" os.environ["PYTHONUTF8"] = "1" # 1. Kiểm tra nếu đã có trong môi trường if os.environ.get("KAGGLE_USERNAME") and os.environ.get("KAGGLE_KEY"): return os.environ["KAGGLE_USERNAME"], os.environ["KAGGLE_KEY"] # 2. Tìm tệp .env trong cây thư mục cur = os.path.abspath(os.path.dirname(__file__)) for _ in range(4): env_path = os.path.join(cur, ".env") if os.path.exists(env_path): try: with open(env_path, "r", encoding="utf-8") as f: for line in f: line = line.strip() if line and not line.startswith("#") and "=" in line: k, v = line.split("=", 1) k = k.strip() v = v.strip().strip("'\"") if k in ["KAGGLE_USERNAME", "KAGGLE_KEY"] and k not in os.environ: os.environ[k] = v except Exception: pass break cur = os.path.dirname(cur) if "KAGGLE_USERNAME" not in os.environ: os.environ["KAGGLE_USERNAME"] = "gustavnguyen" return os.environ.get("KAGGLE_USERNAME"), os.environ.get("KAGGLE_KEY")
if __name__ == "__main__": u, k = init_kaggle_auth() print(f"Kaggle User: {u}, Key loaded: {'Yes' if k else 'No'}")17 unmodified lines181920212223242526272817 unmodified linesdef get_authenticated_api():"""Khởi tạo và xác thực với Kaggle API"""try:# Tự động nạp tài khoản Kaggle riêng của dự án Cham-OCR nếu chưa cấu hình trong envif "KAGGLE_USERNAME" not in os.environ:os.environ["KAGGLE_USERNAME"] = "gustavnguyen"if "KAGGLE_KEY" not in os.environ:os.environ["KAGGLE_KEY"] = "6bf56db7e5c0fa7895d157167961d92b"api = KaggleApi()api.authenticate()17 unmodified lines181920212223242526272817 unmodified linesdef get_authenticated_api():"""Khởi tạo và xác thực với Kaggle API"""try:try:from scripts.kaggle_auth import init_kaggle_authexcept ImportError:from kaggle_auth import init_kaggle_authinit_kaggle_auth()api = KaggleApi()api.authenticate()
3 unmodified lines456789101112 unmodified lines2425262728293031323 unmodified linesKaggle Training Automation for Cham Text Detection (Phase 4).Prepares and submits a multi-GPU (T4x2) PaddleOCR DBNet training job to Kaggle,strictly following the Cham-OCR project rules:- Kaggle user: "gustavnguyen"- Key: "6bf56db7e5c0fa7895d157167961d92b"- Accelerator: NvidiaTeslaT4- Distributed multi-GPU execution: paddle.distributed.launch --gpus '0,1'"""12 unmodified linesexcept AttributeError:pass# Force Kaggle credentialsos.environ["KAGGLE_USERNAME"] = "gustavnguyen"os.environ["KAGGLE_KEY"] = "6bf56db7e5c0fa7895d157167961d92b"PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))sys.path.insert(0, os.path.join(PROJECT_ROOT, "scripts"))3 unmodified lines4567891012 unmodified lines2324252627282930313 unmodified linesKaggle Training Automation for Cham Text Detection (Phase 4).Prepares and submits a multi-GPU (T4x2) PaddleOCR DBNet training job to Kaggle,strictly following the Cham-OCR project rules:- Kaggle user: "gustavnguyen" (Key nạp tự động qua kaggle_auth / .env)- Accelerator: NvidiaTeslaT4- Distributed multi-GPU execution: paddle.distributed.launch --gpus '0,1'"""12 unmodified linesexcept AttributeError:pass# Kaggle credentialsfrom kaggle_auth import init_kaggle_authinit_kaggle_auth()PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))sys.path.insert(0, os.path.join(PROJECT_ROOT, "scripts"))
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268#!/usr/bin/env python3# -*- coding: utf-8 -*-"""Kaggle Training Automation for Cham-OCR Recognition Model V25.Supports 3-Stage Training to safely execute under Kaggle's 12-hour limit: - Stage 1: Epochs 1-14 (~7.8h) with initial surgery weights - Stage 2: Epochs 15-27 (~7.3h) resume via Global.checkpoints - Stage 3: Epochs 28-40 (~7.3h) resume via Global.checkpoints & export inference
Hardware & Rules: - Kaggle user: "gustavnguyen" (nạp tự động qua kaggle_auth / .env) - Accelerator: NvidiaTeslaT4 (GPU T4x2) - Multi-GPU Distributed Launch: paddle.distributed.launch --gpus '0,1' - Save checkpoint: save_epoch_step: 1"""
import osimport sysimport jsonimport argparseimport subprocessimport shutil
# Force UTF-8 standard output for Windows consoleif sys.stdout and sys.stdout.encoding != 'utf-8': try: sys.stdout.reconfigure(encoding='utf-8') except AttributeError: pass
# Kaggle credentialsSCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))TRAINING_DIR = os.path.dirname(SCRIPT_DIR)PROJECT_ROOT = os.path.dirname(TRAINING_DIR)sys.path.insert(0, SCRIPT_DIR)
from kaggle_auth import init_kaggle_authinit_kaggle_auth()
from kaggle_ops import get_authenticated_api, monitor_kernel, download_kernel_outputs
def build_rec_v25_notebook(stage=1, previous_kernel=None): """Generates the Jupyter Notebook for running Cham Recognition V25 on Kaggle T4x2.""" stage_title = f"# Cham OCR PP-OCRv4 Recognition Model V25 - Stage {stage}/3\n" # Define stage-specific epoch range if stage == 1: epoch_start = 1 epoch_end = 14 resume_cmd = "# Stage 1 starts from surgically adapted V24 weights" elif stage == 2: epoch_start = 15 epoch_end = 27 resume_cmd = f"# Stage 2 resumes from Stage 1: {previous_kernel}" else: epoch_start = 28 epoch_end = 40 resume_cmd = f"# Stage 3 resumes from Stage 2: {previous_kernel}"
nb = { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ stage_title, f"Automated 3-Stage Training Pipeline on Kaggle Dual Tesla T4 (NvidiaTeslaT4).\n", f"- Stage: {stage} of 3\n", f"- Epochs: {epoch_start} to {epoch_end}\n", f"- Architecture: PP-OCRv4 Rec (LCNetV3 + SVTR + NRTR + CTC)\n", f"- Resolution: 48x480 (Image Shape [3, 48, 480])\n", f"- Max Text Length: 80\n", f"- Mode: AMP O1 (Mixed Precision)\n" ] }, { "cell_type": "code", "execution_count": None, "metadata": {}, "outputs": [], "source": [ "# 1. Environment & CUDA Setup\n", "!pip install --upgrade pip\n", "!pip install \"paddlepaddle-gpu>=2.6.0\" -i https://www.paddlepaddle.org.cn/packages/stable/cu118/\n", "!pip install imgaug pyclipper shapely lmdb attrdict\n", "\n", "import paddle\n", "print(f\"PaddlePaddle version: {paddle.__version__}\")\n", "print(f\"CUDA available: {paddle.is_compiled_with_cuda()}\")\n", "num_gpus = paddle.device.cuda.device_count()\n", "print(f\"GPU count: {num_gpus}\")\n" ] }, { "cell_type": "code", "execution_count": None, "metadata": {}, "outputs": [], "source": [ "# 2. Clone PaddleOCR repository\n", "import os\n", "if not os.path.exists('PaddleOCR'):\n", " !git clone -b release/2.7 https://github.com/PaddlePaddle/PaddleOCR.git\n", "\n", "%cd PaddleOCR\n", "!pip install -r requirements.txt\n" ] }, { "cell_type": "code", "execution_count": None, "metadata": {}, "outputs": [], "source": [ "# 3. Prepare Working Directories & Fonts\n", "%cd /kaggle/working/PaddleOCR\n", "os.makedirs('data/fonts', exist_ok=True)\n", "os.makedirs('data/cham_synthetic_v25', exist_ok=True)\n", "os.makedirs('/kaggle/working/output/rec_cham_v25', exist_ok=True)\n", "\n", "# Download Cham fonts\n", "!wget -q -O data/fonts/NotoSansCham-Regular.ttf https://raw.githubusercontent.com/googlefonts/noto-fonts/main/hinted/ttf/NotoSansCham/NotoSansCham-Regular.ttf\n", "!wget -q -O data/fonts/NotoSansCham-Bold.ttf https://raw.githubusercontent.com/googlefonts/noto-fonts/main/hinted/ttf/NotoSansCham/NotoSansCham-Bold.ttf\n", "print(\"Fonts downloaded.\")\n" ] }, { "cell_type": "code", "execution_count": None, "metadata": {}, "outputs": [], "source": [ "# 4. Launch Adaptive Multi-GPU Distributed Training\n", f"{resume_cmd}\n", "import paddle\n", "num_gpus = paddle.device.cuda.device_count()\n", "config_path = '/kaggle/working/configs/rec_cham_v25.yml'\n", "\n", "# Multi-GPU launch command\n", "if num_gpus > 1:\n", " gpus = ','.join(str(i) for i in range(num_gpus))\n", " print(f\"Launching distributed training across {num_gpus} GPUs: {gpus}...\")\n", f" !python3 -m paddle.distributed.launch --gpus '{gpus}' tools/train.py -c {{config_path}} -o Global.epoch_num={epoch_end}\n", "else:\n", " print(\"Launching single GPU training...\")\n", f" !python3 tools/train.py -c {{config_path}} -o Global.epoch_num={epoch_end}\n" ] }, { "cell_type": "code", "execution_count": None, "metadata": {}, "outputs": [], "source": [ "# 5. Export Stage Output & Checkpoints\n", f"print(\"Packaging Stage {stage} outputs...\")\n", "if os.path.exists('/kaggle/working/output/rec_cham_v25/latest'):\n", f" !zip -r /kaggle/working/rec_cham_v25_stage{stage}_checkpoint.zip /kaggle/working/output/rec_cham_v25\n", f" print(\"✅ Stage {stage} checkpoint archived successfully.\")\n", "else:\n", " print(\"⚠️ Latest checkpoint directory not found.\")\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": {"name": "ipython", "version": 3}, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbformat": 4, "nbformat_minor": 4 } }, "nbformat": 4, "nbformat_minor": 4 }
# Add final inference export for Stage 3 if stage == 3: nb["cells"].append({ "cell_type": "code", "execution_count": None, "metadata": {}, "outputs": [], "source": [ "# 6. Export Final V25 Inference Model\n", "print(\"🚀 Exporting complete V25 Recognition Inference Model...\")\n", "!python3 tools/export_model.py -c /kaggle/working/configs/rec_cham_v25.yml \\\n", " -o Global.checkpoints=/kaggle/working/output/rec_cham_v25/best_accuracy \\\n", " Global.save_inference_dir=/kaggle/working/output/rec_cham_inference_v25\n", "\n", "!zip -r /kaggle/working/rec_cham_inference_v25.zip /kaggle/working/output/rec_cham_inference_v25\n", "print(\"🎉 Final V25 Inference Model is ready for download!\")\n" ] })
return nb
def main(): parser = argparse.ArgumentParser(description="Kaggle 3-Stage Training Dispatcher for Cham OCR V25") parser.add_argument("--stage", type=int, choices=[1, 2, 3], default=1, help="Giai đoạn huấn luyện (1, 2 hoặc 3)") parser.add_argument("--push", action="store_true", help="Tự động đẩy kernel lên Kaggle và chạy") parser.add_argument("--monitor", action="store_true", help="Theo dõi log thời gian thực sau khi push") args = parser.parse_args()
print("=" * 75) print(f"🚀 CHAM-OCR V25 KAGGLE DISPATCHER - GIAI ĐOẠN {args.stage}/3") print("=" * 75)
api = get_authenticated_api() if not api: print("❌ Lỗi: Không thể xác thực với Kaggle API.") return
work_dir = os.path.join(PROJECT_ROOT, "output", f"kaggle_rec_v25_stage{args.stage}") os.makedirs(work_dir, exist_ok=True)
kernel_slug = f"cham-ocr-rec-v25-stage{args.stage}" nb_path = os.path.join(work_dir, f"kaggle_rec_v25_stage{args.stage}.ipynb")
prev_kernel = f"gustavnguyen/cham-ocr-rec-v25-stage{args.stage - 1}" if args.stage > 1 else None nb_data = build_rec_v25_notebook(stage=args.stage, previous_kernel=prev_kernel)
with open(nb_path, "w", encoding="utf-8") as f: json.dump(nb_data, f, indent=2, ensure_ascii=False) print(f"📝 Đã tạo Notebook tại: {nb_path}")
# Kaggle Kernel Metadata meta = { "id": f"gustavnguyen/{kernel_slug}", "title": f"Cham OCR Rec V25 Stage {args.stage}", "code_file": os.path.basename(nb_path), "language": "python", "kernel_type": "notebook", "is_private": "true", "enable_gpu": "true", "enable_tpu": "false", "enable_internet": "true", "accelerator": "NvidiaTeslaT4", "dataset_sources": [], "kernel_sources": [prev_kernel] if prev_kernel else [] }
meta_path = os.path.join(work_dir, "kernel-metadata.json") with open(meta_path, "w", encoding="utf-8") as f: json.dump(meta, f, indent=2) print(f"📋 Đã tạo Kernel Metadata tại: {meta_path}")
if args.push: print(f"\n🚀 Đang tải kịch bản lên Kaggle ({meta['id']})...") api.kernels_push(work_dir) print("✅ Đã khởi chạy thành công tác vụ huấn luyện trên Kaggle T4x2!") if args.monitor: print("📡 Đang kết nối giám sát tiến trình...") monitor_kernel(api, "gustavnguyen", kernel_slug)
if __name__ == "__main__": main()12 unmodified lines13141516171819202112 unmodified linessocket.setdefaulttimeout(60)def get_api():os.environ["KAGGLE_USERNAME"] = "gustavnguyen"os.environ["KAGGLE_KEY"] = "6bf56db7e5c0fa7895d157167961d92b"api = KaggleApi()api.authenticate()return api12 unmodified lines1314151617181920212212 unmodified linessocket.setdefaulttimeout(60)from kaggle_auth import init_kaggle_authdef get_api():init_kaggle_auth()api = KaggleApi()api.authenticate()return api
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304#!/usr/bin/env python3# -*- coding: utf-8 -*-"""Active Watchdog & SSE Live Stream Logger for Cham-OCR V25 Training on Kaggle.Monitors the kernel run in real time, streams execution logs, provides status heartbeats,and automatically downloads checkpoints when complete."""
import osimport sysimport timeimport jsonimport zipfileimport shutilimport socketimport threadingimport argparsefrom kaggle.api.kaggle_api_extended import KaggleApi
if sys.stdout and hasattr(sys.stdout, 'reconfigure'): sys.stdout.reconfigure(encoding='utf-8', line_buffering=True)if sys.stderr and hasattr(sys.stderr, 'reconfigure'): sys.stderr.reconfigure(encoding='utf-8', line_buffering=True)
socket.setdefaulttimeout(60)
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))TRAINING_DIR = os.path.dirname(SCRIPT_DIR)PROJECT_ROOT = os.path.dirname(TRAINING_DIR)sys.path.insert(0, SCRIPT_DIR)
from kaggle_auth import init_kaggle_auth
def get_api(): init_kaggle_auth() api = KaggleApi() api.authenticate() return api
def stream_logs_worker(api, kernel_id, log_file_path, stop_event): """Lắng nghe luồng SSE log trực tiếp từ Kaggle và lưu file đồng thời phân tích sự kiện.""" consecutive_empty = 0 while not stop_event.is_set(): try: with open(log_file_path, 'a', encoding='utf-8') as f_log: for event in api.kernels_logs_stream(kernel_id): if stop_event.is_set(): break data = event.get('data', '') if data: consecutive_empty = 0 f_log.write(data) f_log.flush() # In các dòng tiến độ quan trọng ra console for line in data.splitlines(): line_str = line.strip() if any(k in line_str for k in [ 'epoch: [', 'best metric', 'cur metric', 'save best model', 'save model in', 'loss:', 'ips:', 'lr:', 'Detected GPU Count', 'Place(gpu', 'train dataloader has', 'Hoàn thành', 'HOÀN TẤT', 'Error', 'Exception', 'RuntimeError', 'ImportError', 'Traceback', 'LAUNCH', 'Train Progress', 'Val Progress', 'Weight Surgery', 'PHẪU THUẬT', 'PREFLIGHT', 'unknown_chars', 'Paddle Version', 'PADDLE ENVIRONMENT', 'NumPy Version', 'OpenCV Version', 'ImgAug Version' ]) and not 'MB/s' in line_str and not 'â”' in line_str: print(f"🔥 [KAGGLE V25] {line_str}") else: consecutive_empty += 1 except Exception as e: time.sleep(3)
if not stop_event.is_set(): time.sleep(5)
import requestsfrom kaggle.api.kaggle_api_extended import KaggleApi, ApiListKernelSessionOutputRequest
def download_chunked_file(url, target_path, chunk_size=1024*1024*8, max_retries=10): """Tải file theo từng chunk có hỗ trợ resume và tự động retry nếu ngắt mạng.""" for attempt in range(max_retries): try: existing_bytes = os.path.getsize(target_path) if os.path.exists(target_path) else 0 headers = {} if existing_bytes > 0: headers["Range"] = f"bytes={existing_bytes}-" print(f"🔄 Lần thử {attempt + 1}/{max_retries}: Tiếp tục tải từ byte {existing_bytes} ({existing_bytes / (1024*1024):.2f} MB)...", flush=True) else: print(f"📥 Bắt đầu tải mới về: {target_path}...", flush=True)
resp = requests.get(url, headers=headers, stream=True, timeout=60) if resp.status_code == 416: print("✅ File đã được tải đầy đủ!", flush=True) return target_path
if resp.status_code not in (200, 206): resp.raise_for_status()
total_bytes = existing_bytes + int(resp.headers.get("content-length", 0)) remaining_mb = (total_bytes - existing_bytes) / (1024*1024) print(f"📊 Còn lại: {remaining_mb:.2f} MB / Tổng: {total_bytes / (1024*1024):.2f} MB", flush=True)
mode = "ab" if existing_bytes > 0 and resp.status_code == 206 else "wb" downloaded = existing_bytes start_time = time.time() last_print = start_time
with open(target_path, mode) as f: for chunk in resp.iter_content(chunk_size=chunk_size): if chunk: f.write(chunk) downloaded += len(chunk) now = time.time() if now - last_print >= 5: speed = (downloaded - existing_bytes) / (now - start_time) / (1024*1024) if (now - start_time) > 0 else 0 percent = (downloaded / total_bytes * 100) if total_bytes > 0 else 0 print(f"⚡ Đã tải: {downloaded / (1024*1024):.1f} MB / {total_bytes / (1024*1024):.1f} MB ({percent:.1f}%) | Tốc độ: {speed:.2f} MB/s", flush=True) last_print = now
if os.path.exists(target_path) and os.path.getsize(target_path) >= total_bytes: print(f"\n✅ Tải hoàn tất 100%! Tổng dung lượng: {os.path.getsize(target_path) / (1024*1024):.2f} MB", flush=True) return target_path except Exception as e: print(f"⚠️ Mạng gián đoạn: {e}. Đang tự động kết nối lại sau 3 giây...", flush=True) time.sleep(3)
raise RuntimeError(f"❌ Không thể tải file sau {max_retries} lần thử!")
def download_outputs(api, kernel_id, output_dir): """Tải và giải nén an toàn toàn bộ checkpoint output từ Kaggle bằng chunked streaming.""" try: socket.setdefaulttimeout(600) print(f"📥 Đang truy vấn URL output từ Kaggle ({kernel_id})...", flush=True) owner, slug, _ = api.parse_kernel_string(kernel_id) req = ApiListKernelSessionOutputRequest() req.user_name = owner req.kernel_slug = slug
client = api.build_kaggle_client() res = client.kernels.kernels_api_client.list_kernel_session_output(req)
if not res.files: print("⚠️ Không tìm thấy file output nào trên Kaggle qua session output API, fallback sang api.kernels_output...", flush=True) api.kernels_output(kernel_id, path=output_dir) return True
for f_info in res.files: target_path = os.path.join(output_dir, f_info.file_name) print(f"📦 Tìm thấy output: {f_info.file_name} -> {target_path}", flush=True) download_chunked_file(f_info.url, target_path)
# Giải nén nếu là file zip if target_path.endswith(".zip"): print(f"📂 Đang kiểm tra nội dung ZIP: {target_path}...", flush=True) with zipfile.ZipFile(target_path, 'r') as z: namelist = z.namelist() # Tìm file checkpoint zip con hoặc các file trọng yếu target_files = [n for n in namelist if 'checkpoint.zip' in n or 'best_accuracy' in n or 'cham_dict_v25.txt' in n or 'latest' in n] extract_dir = os.path.join(output_dir, "extracted") os.makedirs(extract_dir, exist_ok=True) for tf in target_files: z.extract(tf, extract_dir) print(f" ✅ Đã trích xuất: {tf}", flush=True)
# Nếu có file checkpoint zip con (như rec_cham_v25_stageX_checkpoint.zip) sub_zips = [os.path.join(extract_dir, f) for f in os.listdir(extract_dir) if f.endswith('checkpoint.zip')] for szp in sub_zips: final_ckpt_dir = os.path.join(output_dir, "final_checkpoint") os.makedirs(final_ckpt_dir, exist_ok=True) with zipfile.ZipFile(szp, 'r') as subz: subz.extractall(final_ckpt_dir) print(f"🎉 ĐÃ GIẢI NÉN TOÀN BỘ CHECKPOINT VÀO: {final_ckpt_dir}", flush=True)
return True except Exception as e: print(f"❌ Lỗi tải output: {e}", flush=True) return False
def run_watchdog(user="gustavnguyen", slug="paddleocr-cham-v25-stage1", output_dir=None, poll_interval=30): kernel_id = f"{user}/{slug}" if output_dir is None: output_dir = os.path.join(TRAINING_DIR, "output", "v25_stage1") os.makedirs(output_dir, exist_ok=True) live_log_path = os.path.join(output_dir, "live_training.log") if os.path.exists(live_log_path) and os.path.getsize(live_log_path) > 0: backup_path = os.path.join(output_dir, f"live_training_prev_{int(time.time())}.log") try: shutil.move(live_log_path, backup_path) print(f"📦 Đã lưu nhật ký phiên trước sang: {backup_path}") except Exception: pass
print("=" * 80) print("🛡️ ACTIVE WATCHDOG V25 - SSE LIVE STREAM & LOG MONITOR") print(f"🎯 Kernel Mục Tiêu : {kernel_id}") print(f"📂 Nhật Ký Ghi Vào : {live_log_path}") print(f"⏱️ Nhịp Heartbeat : {poll_interval} giây / chu kỳ") print("=" * 80)
api = get_api()
# Khởi chạy luồng SSE Live Stream stop_stream_event = threading.Event() stream_thread = threading.Thread( target=stream_logs_worker, args=(api, kernel_id, live_log_path, stop_stream_event), daemon=True ) stream_thread.start() print("📡 Kênh SSE Live Stream đã mở. Sẵn sàng nhận logs...\n")
start_time = time.time() last_status = None fail_count = 0 seen_log_offset = 0
while True: try: res = api.kernels_status(kernel_id) if hasattr(res, 'status') and hasattr(res.status, 'name'): status = res.status.name.lower() elif hasattr(res, 'status'): status = str(res.status).split('.')[-1].lower() else: status = 'unknown'
elapsed_sec = int(time.time() - start_time) elapsed_min = elapsed_sec // 60
if status != last_status or elapsed_sec % 60 < poll_interval: print(f"⏱️ [Heartbeat {elapsed_min:02d}m{elapsed_sec%60:02d}s] Trạng thái: {status.upper()}", flush=True) last_status = status
# Bổ sung kiểm tra log trực tiếp từ REST API để phòng ngừa gián đoạn SSE try: raw_logs = api.kernels_logs(kernel_id) if isinstance(raw_logs, str) and len(raw_logs) > seen_log_offset: new_chunk = raw_logs[seen_log_offset:] seen_log_offset = len(raw_logs) with open(live_log_path, 'a', encoding='utf-8') as f_log: f_log.write(new_chunk) f_log.flush() for line in new_chunk.splitlines(): line_str = line.strip() if line_str and not 'MB/s' in line_str and not 'â”' in line_str: print(f"🔥 [LOG] {line_str}", flush=True) except Exception: pass
# 1. Trạng thái HOÀN TẤT if 'complete' in status: stop_stream_event.set() print("\n" + "=" * 80, flush=True) print(f"🎉 KERNEL V25 ĐÃ HOÀN TẤT THÀNH CÔNG TRONG {elapsed_min} PHÚT!", flush=True) print("📥 Bắt đầu tải và đồng bộ checkpoint kết quả...", flush=True) print("=" * 80, flush=True) download_outputs(api, kernel_id, output_dir) return True
# 2. Trạng thái LỖI elif any(k in status for k in ['error', 'cancel', 'abort', 'fail']): stop_stream_event.set() print("\n" + "!" * 80, flush=True) print(f"🚨 BÁO ĐỘNG: KERNEL V25 BỊ DỪNG HOẶC GẶP LỖI: {status.upper()}!", flush=True) print(f"⏱️ Thời gian chạy: {elapsed_min} phút {elapsed_sec%60} giây.", flush=True) print("!" * 80, flush=True) return False
fail_count = 0
except Exception as e: fail_count += 1 if fail_count >= 5: print(f"⚠️ Mất kết nối kiểm tra Kaggle API ({fail_count}/5): {e}", flush=True)
time.sleep(poll_interval)
def main(): parser = argparse.ArgumentParser(description="Active Watchdog for Cham-OCR V25 Training") parser.add_argument("--kernel", type=str, default="paddleocr-cham-v25-stage1", help="Slug của kernel") parser.add_argument("--user", type=str, default="gustavnguyen", help="Kaggle username") parser.add_argument("--poll-interval", type=int, default=30, help="Chu kỳ heartbeat (giây)") parser.add_argument("--output-dir", type=str, default=None, help="Thư mục xuất logs & checkpoint") args = parser.parse_args()
run_watchdog( user=args.user, slug=args.kernel, output_dir=args.output_dir, poll_interval=args.poll_interval )
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141#!/usr/bin/env python3# -*- coding: utf-8 -*-"""Dedicated Real-Time Monitor for Cham-OCR V25 Kaggle Kernels.Streams live training logs (Epoch, Step, Loss, Acc, ETA) directly from Kaggle stream API."""
import osimport sysimport timeimport jsonimport socket
if sys.stdout and hasattr(sys.stdout, 'reconfigure'): sys.stdout.reconfigure(encoding='utf-8')
socket.setdefaulttimeout(30)
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))sys.path.insert(0, SCRIPT_DIR)
from kaggle_auth import init_kaggle_authinit_kaggle_auth()
from kaggle_ops import get_authenticated_apifrom kagglesdk.kernels.types.kernels_api_service import ApiGetKernelSessionLogsStreamRequest
def fetch_stream_lines(api, user_name, kernel_slug, timeout_sec=6): clean_lines = [] try: with api.build_kaggle_client() as kaggle: client = kaggle.kernels.kernels_api_client req = ApiGetKernelSessionLogsStreamRequest() req.user_name = user_name req.kernel_slug = kernel_slug res = client.get_kernel_session_logs_stream(req) t0 = time.time() for line in res.iter_lines(decode_unicode=True): if line and line.startswith('data: '): try: item = json.loads(line[6:]) text = item.get('data', '') for d in text.splitlines(): if d.strip(): clean_lines.append(d.strip()) except Exception: pass if time.time() - t0 > timeout_sec: break except Exception as e: pass return clean_lines
def monitor(kernel_id, poll_seconds=60): api = get_authenticated_api() if not api: print("❌ Lỗi: Không thể xác thực Kaggle API.") return 1
parts = kernel_id.split('/') user_name = parts[0] kernel_slug = parts[1] if len(parts) > 1 else parts[0]
print("=" * 75) print(f"🛰️ BẮT ĐẦU GIÁM SÁT REAL-TIME STREAMING KERNEL: {kernel_id}") print(f" • Tần suất kiểm tra : {poll_seconds} giây / lần") print(f" • Thời gian bắt đầu : {time.strftime('%Y-%m-%d %H:%M:%S')}") print("=" * 75) sys.stdout.flush()
start_t = time.time() last_status = None last_count = 0 poll_count = 0
while True: poll_count += 1 elapsed_min = int((time.time() - start_t) / 60) try: st_obj = api.kernels_status(kernel_id) status = getattr(st_obj, 'status', None) if hasattr(status, 'name'): status_str = status.name.lower() elif isinstance(status, str): status_str = status.lower() else: status_str = str(status).lower()
failure_msg = getattr(st_obj, 'failure_message', None) or getattr(st_obj, 'failureMessage', None)
# Lấy các dòng log trực tiếp từ Live Stream API lines = fetch_stream_lines(api, user_name, kernel_slug, timeout_sec=6) current_count = len(lines)
if current_count > last_count: new_lines = lines[last_count:] # Lọc các dòng có ý nghĩa huấn luyện quan trọng key_lines = [l for l in new_lines if any(k in l for k in ['ppocr INFO:', 'epoch:', 'cur metric', 'best metric', 'assert', 'Error', 'STAGE EXIT', '🎉'])] if not key_lines: key_lines = new_lines[-10:] # in 10 dòng mới nhất nếu không có dòng quan trọng print(f"\n📡 [Sau {elapsed_min}m | Status: {status_str.upper()} | Tổng {current_count:,} dòng]:") for l in key_lines[-15:]: print(f" | {l}") last_count = current_count sys.stdout.flush() elif status_str != last_status or poll_count % 5 == 0: print(f"⏱️ [Sau {elapsed_min}m] Trạng thái: {status_str.upper()} (Đã nhận {current_count:,} dòng log)...") sys.stdout.flush()
last_status = status_str
if status_str in ('complete', 'completed'): print("\n" + "=" * 75) print(f"🎉 KERNEL {kernel_id} ĐÃ HOÀN TẤT THÀNH CÔNG sau {elapsed_min} phút!") print("=" * 75) sys.stdout.flush() return 0 elif status_str in ('error', 'cancel', 'cancelled', 'aborted'): print("\n" + "=" * 75) print(f"❌ KERNEL {kernel_id} GẶP LỖI ({status_str.upper()}) sau {elapsed_min} phút!") if failure_msg: print(f" • Failure Message: {failure_msg}") if lines: print(" • 25 DÒNG LOG CUỐI CÙNG TRƯỚC KHI CRASH:") for l in lines[-25:]: print(f" ! {l}") print("=" * 75) sys.stdout.flush() return 1
except Exception as e: print(f"⚠️ [Lỗi API tại {elapsed_min}m]: {e}") sys.stdout.flush()
time.sleep(poll_seconds)
if __name__ == '__main__': kernel = sys.argv[1] if len(sys.argv) > 1 else 'gustavnguyen/paddleocr-cham-v25-stage1' interval = int(sys.argv[2]) if len(sys.argv) > 2 else 60 sys.exit(monitor(kernel, interval))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309#!/usr/bin/env python3# -*- coding: utf-8 -*-"""End-to-End Autonomous Orchestrator for Cham-OCR Model V25 on Lightning Cloud.Runs entirely on Lightning Cloud (CloudProvider.LIGHTNING - lightning-baremetal cluster):1. Stage 1 (Data Prep): 32-core CPU machine (Machine.DATA_PREP, 128GB RAM, 1.98 cr/hr on Lightning Cloud) synthesizes 250,000 train + 25,000 val line images across 4 core pillars in ~70s (~0.03 credits).2. Stage 2 (GPU Training): Switches machine to NVIDIA H100 (80GB SXM5, 8.5 cr/hr on Lightning Cloud) to: - Populate RAM Disk (/dev/shm) to achieve 100% GPU compute utilization. - Train 40 epochs with AMP FP16 and batch size 256 in ~35-40 mins (~5.5 credits). - Export lightweight inference model (~11MB) and package rec_cham_v25_infer.zip. - Download zip to local workspace and extract to ocr-studio/data/output/rec_cham_inference_v25/. - Immediately STOP Studio in finally block to guarantee zero leaked credits."""
import osimport sysimport timeimport base64import zipfileimport pathlibfrom lightning_sdk import Studio, Machinefrom lightning_sdk.machine import CloudProvider
if sys.stdout and hasattr(sys.stdout, 'reconfigure'): try: sys.stdout.reconfigure(encoding='utf-8') except Exception: passif sys.stderr and hasattr(sys.stderr, 'reconfigure'): try: sys.stderr.reconfigure(encoding='utf-8') except Exception: pass
def log(msg): timestamp = time.strftime("%H:%M:%S") print(f"[{timestamp}] {msg}", flush=True)
def send_file(studio, local_path, remote_path): """Transfers a local file to remote Studio using chunked base64 payload.""" log(f"📦 Đang đẩy {os.path.basename(local_path)} sang {remote_path}...") with open(local_path, "rb") as f: content = f.read()
b64_str = base64.b64encode(content).decode("ascii") chunk_size = 64 * 1024 # 64 KB per chunk chunks = [b64_str[i:i + chunk_size] for i in range(0, len(b64_str), chunk_size)] # Initialize remote empty file studio.run(f"python3 -c \"import pathlib; p = pathlib.Path('{remote_path}'); p.parent.mkdir(parents=True, exist_ok=True); p.write_text('')\"") for chunk in chunks: cmd = f"python3 -c \"import pathlib; p = pathlib.Path('{remote_path}'); open('{remote_path}.b64', 'a').write('{chunk}')\"" studio.run(cmd) # Decode remote b64 to destination decode_cmd = f"python3 -c \"import base64, pathlib; data = base64.b64decode(pathlib.Path('{remote_path}.b64').read_text()); pathlib.Path('{remote_path}').write_bytes(data); pathlib.Path('{remote_path}.b64').unlink()\"" studio.run(decode_cmd) size_out = studio.run(f"ls -lh '{remote_path}'").strip() log(f" ✅ Đã đẩy thành công: {size_out}")
def main(): root_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) log("==========================================================================") log("🚀 KHỞI ĐỘNG HỆ THỐNG ĐIỀU PHỐI CHAM-OCR V25 TRÊN LIGHTNING CLOUD (BAREMETAL)") log("==========================================================================") log(f"Thư mục gốc cục bộ: {root_dir}")
# Khởi tạo Studio trên Lightning Cloud (lightning-baremetal) studio = Studio( name="cham-ocr-v25", teamspace="phucsd", org="phucsd-org", cloud_provider=CloudProvider.LIGHTNING, create_ok=True ) studio.show_progress = False # Tránh nghẽn terminal khi chạy ngầm log(f"Studio: {studio.name} | Cluster: {studio.cluster} | Trạng thái: {studio.status}")
try: # ====================================================================== # GIAI ĐOẠN 1: SINH DỮ LIỆU TRÊN MÁY DATA_PREP (32 VCPU, 128GB RAM - 1.98 CR/H) # ====================================================================== log("\n" + "="*70) log("⚡ [GIAI ĐOẠN 1/2] CHUẨN BỊ MÁY DATA_PREP (32 CPU, 128GB RAM) TRÊN LIGHTNING CLOUD") log("="*70)
# 1.1 Kiểm tra trạng thái Studio: Đợi nếu đang Stopping while str(studio.status).lower() in ["stopping", "transitioning"]: log(f"Studio đang ở trạng thái '{studio.status}', đợi 5 giây...") time.sleep(5)
target_gpu = Machine.H100 if str(studio.status).lower() != "running": log(f"Khởi động Studio trực tiếp trên {target_gpu} (80GB VRAM SXM5 trên Lightning Cloud)...") studio.start(machine=target_gpu) elif studio.machine != target_gpu: log(f"Studio đang chạy trên {studio.machine}, chuyển sang {target_gpu}...") studio.switch_machine(target_gpu)
log(f"✅ Studio đã HOẠT ĐỘNG! Trạng thái: {studio.status} | Machine: {studio.machine}")
# Thiết lập thư mục cơ sở trên Studio remote_base = "/teamspace/studios/this_studio/Cham-OCR/ocr-training" studio.run(f"mkdir -p {remote_base}/scripts {remote_base}/data/fonts {remote_base}/configs {remote_base}/PaddleOCR")
# Kiểm tra bộ dữ liệu V25 hiện có data_count = studio.run(f"test -f {remote_base}/data/cham_synthetic_v25/train_label.txt && wc -l {remote_base}/data/cham_synthetic_v25/train_label.txt || echo 0").strip() num_lines = int(data_count.split()[0]) if data_count and data_count.split()[0].isdigit() else 0 log(f"Số lượng mẫu huấn luyện hiện có trên đĩa: {num_lines:,} mẫu")
if num_lines < 250000: log("Chuyển sang Machine.DATA_PREP để sinh 275,000 ảnh...") studio.switch_machine(Machine.DATA_PREP) studio.run("pip install -q pillow opencv-python 'numpy<2.0' tqdm") studio.run(f"wget -q -nc -O {remote_base}/data/fonts/NotoSansCham-Regular.ttf https://raw.githubusercontent.com/googlefonts/noto-fonts/main/hinted/ttf/NotoSansCham/NotoSansCham-Regular.ttf || true") studio.run(f"wget -q -nc -O {remote_base}/data/fonts/NotoSansCham-Bold.ttf https://raw.githubusercontent.com/googlefonts/noto-fonts/main/hinted/ttf/NotoSansCham/NotoSansCham-Bold.ttf || true") local_gen = os.path.join(root_dir, "ocr-training", "scripts", "generate_data_v25.py") send_file(studio, local_gen, f"{remote_base}/scripts/generate_data_v25.py") studio.run(f"cd {remote_base} && python3 scripts/generate_data_v25.py --num_train 250000 --num_val 25000 --output_dir ./data/cham_synthetic_v25 --workers 32") studio.switch_machine(target_gpu) else: log("✅ Tập dữ liệu 275,000 mẫu V25 đã có sẵn đầy đủ từ Giai đoạn 1! Bỏ qua bước sinh dữ liệu.")
# Đồng bộ các tệp V25 mới nhất lên Studio log("🔄 Đang đồng bộ các tệp mã nguồn và cấu hình V25 lên Studio...") local_dict = os.path.join(root_dir, "ocr-training", "data", "cham_dict_v25.txt") local_cfg = os.path.join(root_dir, "ocr-training", "configs", "rec_cham_v25_lightning.yml") local_sh = os.path.join(root_dir, "ocr-training", "run_lightning_v25.sh")
send_file(studio, local_dict, f"{remote_base}/data/cham_dict_v25.txt") send_file(studio, local_cfg, f"{remote_base}/configs/rec_cham_v25_lightning.yml") send_file(studio, local_sh, f"{remote_base}/run_lightning_v25.sh") studio.run(f"chmod +x {remote_base}/run_lightning_v25.sh")
# ====================================================================== # GIAI ĐOẠN 2: HUẤN LUYỆN TRÊN NVIDIA H100 (LIGHTNING CLOUD) # ====================================================================== log("\n" + "="*70) log("🔥 [GIAI ĐOẠN 2/2] HUẤN LUYỆN TRÊN NVIDIA H100 TRÊN LIGHTNING CLOUD") log("="*70)
# 2.1 Kiểm tra GPU H100 gpu_info = studio.run("nvidia-smi --query-gpu=name,memory.total,driver_version --format=csv,noheader").strip() log(f"🔥 Phần cứng GPU: {gpu_info}")
# 2.2 Đảm bảo PaddleOCR repo và dependencies với cu126 log("📦 Cài đặt PaddlePaddle GPU chuẩn CUDA 12.6 (cu126) cho kiến trúc Hopper H100 (sm_90)...") studio.run(f"cd {remote_base} && if [ ! -d 'PaddleOCR' ] || [ ! -f 'PaddleOCR/tools/train.py' ]; then rm -rf PaddleOCR && git clone -b release/2.7 https://github.com/PaddlePaddle/PaddleOCR.git; fi") # Cài đặt bản cu126 chính thức studio.run("pip uninstall -y paddlepaddle paddlepaddle-gpu || true") studio.run("pip install -q paddlepaddle-gpu==3.3.1 -i https://www.paddlepaddle.org.cn/packages/stable/cu126/") studio.run("pip install -q rapidfuzz visualdl pyclipper shapely imgaug lmdb 'numpy<2.0' attrdict pyyaml") # Kiểm tra xác thực CUDA kernel trên H100 verify_cmd = """python3 -c "import paddleprint('Paddle Version:', paddle.__version__, '| GPU Device:', paddle.device.get_device())paddle.utils.run_check()print('PADDLE_H100_VERIFIED_SUCCESS')" """ verify_out = studio.run(verify_cmd).strip() log(f"✅ Kết quả kiểm thử kernel H100:\n{verify_out}")
# 2.3 Sao chép cấu hình và từ điển vào PaddleOCR (đọc trực tiếp từ persistent disk, 0 giây delay) log("⚡ Cấu hình đọc trực tiếp từ bộ dữ liệu gốc (không tốn thời gian copy RAM disk)...") paddle_dir = f"{remote_base}/PaddleOCR" studio.run(f"mkdir -p {paddle_dir}/data {paddle_dir}/configs") studio.run(f"cp {remote_base}/data/cham_dict_v25.txt {paddle_dir}/data/cham_dict_v25.txt") studio.run(f"cp {remote_base}/configs/rec_cham_v25_lightning.yml {paddle_dir}/configs/rec_cham_v25_lightning.yml")
# 2.4 Khởi chạy huấn luyện nền log("🚀 Bắt đầu huấn luyện Model V25 (Single-GPU A100, batch 256, 40 epochs)...") studio.run(f"cd {paddle_dir} && pkill -9 -f tools/train.py || true") train_cmd = f"cd {paddle_dir} && nohup python3 -u tools/train.py -c configs/rec_cham_v25_lightning.yml > train.log 2>&1 &" studio.run(train_cmd) log("✅ Tiến trình huấn luyện đã kích hoạt chạy ngầm (background) trên A100!")
# 2.6 Vòng lặp giám sát liên tục (Monitoring Loop / Watchdog) log("\n📊 Bắt đầu theo dõi chỉ số loss và epoch liên tục...") start_train = time.time() prev_tail = ""
while True: time.sleep(15) # Kiểm tra tiến trình train.py ps_out = studio.run("ps aux | grep tools/train.py | grep -v grep | wc -l").strip() is_running = int(ps_out or "0") > 0
# Đọc 8 dòng cuối file log try: log_tail = studio.run(f"cd {paddle_dir} && tail -n 8 train.log").strip() if log_tail and log_tail != prev_tail: prev_tail = log_tail log("--- [WATCHDOG LIVE TRAIN LOG] ---") for line in log_tail.splitlines()[-4:]: log(f" {line}") except Exception as e: log(f"Lưu ý khi đọc log: {e}")
if not is_running: train_duration = (time.time() - start_train) / 60 if train_duration < 3.0: err_dump = studio.run(f"cd {paddle_dir} && cat train.log").strip() log(f"❌ Tiến trình huấn luyện bị dừng đột ngột sau {train_duration:.1f} phút!\n{err_dump}") raise RuntimeError("Training process crashed early. Check log dump above.") else: log(f"\n🎉 TIẾN TRÌNH HUẤN LUYỆN HOÀN TẤT SAU {train_duration:.1f} PHÚT!") break
# 2.7 Xuất mô hình Inference siêu nhẹ (~11MB) log("\n📦 Xuất mô hình Inference V25 (export_model.py)...") export_cmd = f""" cd {paddle_dir} BEST_MODEL="" if [ -f "output/rec_cham_v25/best_accuracy.pdparams" ]; then BEST_MODEL="output/rec_cham_v25/best_accuracy" elif [ -f "output/rec_cham_v25/latest.pdparams" ]; then BEST_MODEL="output/rec_cham_v25/latest" else LATEST_PARAM=$(ls -t output/rec_cham_v25/*.pdparams 2>/dev/null | head -n 1) if [ -n "$LATEST_PARAM" ]; then BEST_MODEL="${{LATEST_PARAM%.pdparams}}" fi fi if [ -z "$BEST_MODEL" ]; then echo "❌ Không tìm thấy checkpoint .pdparams trong output/rec_cham_v25!" exit 1 fi echo "Exporting model using weights: ${{BEST_MODEL}}" python3 tools/export_model.py \ -c configs/rec_cham_v25_lightning.yml \ -o Global.pretrained_model=${{BEST_MODEL}} \ Global.save_inference_dir=output/rec_cham_v25_infer cd output zip -r ../rec_cham_v25_infer.zip rec_cham_v25_infer/ cd .. cp rec_cham_v25_infer.zip {remote_base}/rec_cham_v25_infer.zip 2>/dev/null || true ls -lh rec_cham_v25_infer.zip """ export_out = studio.run(export_cmd).strip() log(f"Kết quả xuất mô hình:\n{export_out}")
# 2.8 Tải mô hình về máy cục bộ local_output_dir = os.path.join(root_dir, "ocr-studio", "data", "output") os.makedirs(local_output_dir, exist_ok=True) local_zip = os.path.join(local_output_dir, "rec_cham_v25_infer.zip") log(f"⬇️ Đang tải tệp mô hình về local: {local_zip}...") download_success = False try: studio.download_file("Cham-OCR/ocr-training/PaddleOCR/rec_cham_v25_infer.zip", local_zip) if os.path.exists(local_zip) and os.path.getsize(local_zip) > 1024 * 1024: download_success = True except Exception as dl_err: log(f"Lưu ý khi dùng studio.download_file: {dl_err}")
if not download_success: log("🔄 Sử dụng cơ chế tải tệp phân đoạn Base64 để đảm bảo an toàn 100%...") b64_zip = studio.run(f"cd {paddle_dir} && python3 -c \"import base64, pathlib; print(base64.b64encode(pathlib.Path('rec_cham_v25_infer.zip').read_bytes()).decode('ascii'))\"").strip() with open(local_zip, "wb") as f: f.write(base64.b64decode(b64_zip)) log(f"✅ Đã tải về thành công! Kích thước: {os.path.getsize(local_zip)/(1024*1024):.2f} MB")
# 2.9 Giải nén mô hình vào ocr-studio extract_dir = os.path.join(local_output_dir, "rec_cham_inference_v25") os.makedirs(extract_dir, exist_ok=True) with zipfile.ZipFile(local_zip, 'r') as zip_ref: for member in zip_ref.namelist(): filename = os.path.basename(member) if not filename: continue source = zip_ref.open(member) target = open(os.path.join(extract_dir, filename), "wb") with source, target: target.write(source.read()) log(f"🎉 Đã giải nén mô hình thành công vào: {extract_dir}") for item in os.listdir(extract_dir): sz = os.path.getsize(os.path.join(extract_dir, item)) log(f" • {item}: {sz/(1024*1024):.2f} MB")
log("\n" + "="*70) log("🎊 TOÀN BỘ QUY TRÌNH HUẤN LUYỆN V25 TRÊN H100 ĐÃ HOÀN THÀNH XUẤT SẮC!") log("="*70)
except Exception as e: log(f"❌ XẢY RA LỖI TRONG QUÁ TRÌNH THỰC THI: {e}") raise finally: # TỰ ĐỘNG DỪNG STUDIO NGAY LẬP TỨC ĐỂ BẢO VỆ CREDIT try: if str(studio.status).lower() == "running": log("\n🛑 [AN TOÀN BẢN QUYỀN CREDIT] Đang dừng Studio trên Lightning AI...") studio.stop() log(f"✅ Studio đã DỪNG (Status: {studio.status})! 0 credit bị tiêu tốn thêm.") else: log(f"Studio hiện tại ở trạng thái '{studio.status}', không cần gửi lệnh dừng.") except Exception as stop_err: log(f"⚠️ Cảnh báo khi dừng Studio: {stop_err}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644#!/usr/bin/env python3# -*- coding: utf-8 -*-"""Chuẩn bị gói Kaggle Benchmark Notebook V2 chuyên biệt cho Cham-OCR V24 trên Dual GPU Tesla T4x2.Đo lường độ chính xác cao: Loại bỏ warm-up (Steady-State measurement), thống kê Median/Mean/Std IPS,khảo sát chi tiết miền khả thi của 640 Tensor Cores (AMP O1), tối ưu hóa NCCL và Worker."""
import osimport sysimport json
if sys.stdout and hasattr(sys.stdout, 'reconfigure'): sys.stdout.reconfigure(encoding='utf-8')
def read_file(path): with open(path, 'r', encoding='utf-8') as f: return f.read()
def main(): print("📦 Bắt đầu đóng gói Kaggle Benchmark Notebook V2 (High-Precision T4x2)...") dict_extension_code = read_file('ocr-training/scripts/dict_extension_v24.py') generate_data_v24_code = read_file('ocr-training/scripts/generate_data_v24.py') config_v24_code = read_file('ocr-training/configs/rec_cham_v24.yml') cells = [] def add_md(text): cells.append({ "cell_type": "markdown", "metadata": {}, "source": [line + '\n' for line in text.splitlines()] }) def add_code(code_str): cells.append({ "cell_type": "code", "execution_count": None, "metadata": {}, "outputs": [], "source": [line + '\n' for line in code_str.splitlines()] })
# Tiêu đề add_md("""# 🚀 Benchmark V2 Chuẩn Xác Cao Trên Kaggle Dual GPU Tesla T4x2**Mô hình khảo sát**: Cham-OCR Recognition V24 (`PP-OCRv4 SVTR_LCNet` + `NRTRHead`)**Mục tiêu & Phương pháp chuẩn mực**:1. **Đo đạc Steady-State**: Bỏ qua 15 bước khởi động (Warm-up), chỉ lấy mẫu đo ở trạng thái ổn định.2. **Độ tin cậy thống kê cao**: Tính toán `Median IPS`, `Mean IPS`, độ biến thiên `Std Dev / CoV (%)`.3. **So sánh 1:1 trực diện**: Đối sánh FP32 vs AMP O1 ở cùng mức mốc chuẩn `BS = 64/GPU` (Global 128).4. **Quét tìm điểm ngọt Tensor Cores**: Khảo sát `BS = 48, 64, 72, 80, 96` trong chế độ AMP FP16.5. **Kiểm tra tính ổn định số học (Loss Sanity)**: Giám sát CTC & NRTR Loss qua từng bước trong AMP FP16.6. **Tối ưu hóa giao tiếp DDP qua PCIe**: Đánh giá tham số `NCCL_BUFFSIZE=16M` và số lượng CPU Workers.""")
# Cell 1: Cài đặt thư viện & Kiểm tra GPU add_md("## 1. Cài đặt môi trường & Xác thực Dual GPU T4x2") add_code("""# 1. Cài đặt PaddlePaddle GPU và dependencies!pip install --quiet "paddlepaddle-gpu>=2.6.0" "albumentations>=1.4.0" fonttools pyyaml opencv-python Pillow tabulate
# 2. Kiểm tra GPUimport osimport sysimport paddle
print("="*60)print("PADDLE ENVIRONMENT STATUS:")print("Paddle Version:", paddle.__version__)print("Compiled with CUDA:", paddle.is_compiled_with_cuda())gpu_count = paddle.device.cuda.device_count()print(f"Detected GPU Count: {gpu_count}")print("="*60)
if gpu_count < 2: print("⚠️ CẢNH BÁO: Không phát hiện đủ 2 GPU T4! Vui lòng chọn Accelerator = GPU T4 x2 trong Settings.")for i in range(gpu_count): print(f" - GPU {i}: {paddle.device.cuda.get_device_name(i)}")""")
# Cell 2: Setup Workspace & PaddleOCR add_md("## 2. Thiết lập thư mục & Sao chép Assets") add_code("""import osimport shutil
os.makedirs('/kaggle/working/data/fonts', exist_ok=True)os.makedirs('/kaggle/working/configs', exist_ok=True)os.makedirs('/kaggle/working/scripts', exist_ok=True)os.makedirs('/kaggle/working/benchmark_output', exist_ok=True)
candidate_asset_dirs = [ "/kaggle/input/cham-ocr-v5-assets", "/kaggle/input/datasets/gustavnguyen/cham-ocr-v5-assets"]ASSETS_DIR = Nonefor d in candidate_asset_dirs: if os.path.exists(d): ASSETS_DIR = d break
if not ASSETS_DIR and os.path.exists('/kaggle/input'): for root, dirs, files in os.walk('/kaggle/input'): if 'v23_checkpoint' in dirs or 'fonts' in dirs: ASSETS_DIR = root break
if not ASSETS_DIR: raise FileNotFoundError("❌ LỖI: Không tìm thấy thư mục Assets trong /kaggle/input")
print(f"✅ Đã tìm thấy Assets Input tại: {ASSETS_DIR}")
# Copy fontsfonts_src = os.path.join(ASSETS_DIR, "fonts", "fonts")if not os.path.exists(fonts_src): fonts_src = os.path.join(ASSETS_DIR, "fonts")
for f in os.listdir(fonts_src): if f.endswith(('.ttf', '.otf')): shutil.copy2(os.path.join(fonts_src, f), os.path.join('/kaggle/working/data/fonts', f))
print("✅ Đã sao chép fonts:", os.listdir('/kaggle/working/data/fonts'))
# Clone PaddleOCRif not os.path.exists('/kaggle/working/PaddleOCR'): print("⏳ Đang clone PaddleOCR...") !git clone --depth 1 https://github.com/PaddlePaddle/PaddleOCR.git /kaggle/working/PaddleOCR !pip install --quiet -r /kaggle/working/PaddleOCR/requirements.txtelse: print("✅ PaddleOCR đã tồn tại sẵn.")""")
# Cell 3: Nạp kịch bản từ điển & Sinh 12,000 mẫu dữ liệu thực nghiệm add_md("## 3. Nạp kịch bản từ điển & Sinh 12,000 mẫu dữ liệu thực nghiệm V24") add_code(f"%%writefile /kaggle/working/scripts/dict_extension_v24.py\n{dict_extension_code}") add_code(f"%%writefile /kaggle/working/scripts/generate_data_v24.py\n{generate_data_v24_code}") add_code(f"%%writefile /kaggle/working/configs/rec_cham_v24.yml\n{config_v24_code}")
# Cell 4: Sinh từ điển & dữ liệu add_code("""import os, time%cd /kaggle/working
print("=== BƯỚC 1: TẠO TỪ ĐIỂN V24 ===")!python3 scripts/dict_extension_v24.py
print("\\n=== BƯỚC 2: SINH 12,000 MẪU DỮ LIỆU BENCHMARK THỰC TẾ ===")t0 = time.time()!python3 scripts/generate_data_v24.py --output-dir /kaggle/working/data/cham_synthetic_benchmark --fonts-dir /kaggle/working/data/fonts --num-train 11000 --num-val 1000 --num-workers 4print(f"🎉 Hoàn thành sinh dữ liệu trong {(time.time()-t0):.2f} giây!")""")
# Cell 5: Viết Runner Benchmark V2 Chuẩn Xác Cao add_md("## 4. Tạo Runner Benchmark V2 Đo Lường Steady-State Đa GPU Chuẩn Xác") benchmark_runner_code = r'''import osimport sysimport timeimport jsonimport reimport mathimport statisticsimport yamlimport subprocessimport shutil
# Ma trận thử nghiệm tập trung khảo sát điểm ngọt hiệu năngTRIALS = [ # Nhóm 1: Mốc chuẩn tham chiếu (Baseline) {"name": "T1 (Baseline FP32 BS64)", "bs": 64, "workers": 2, "amp": False, "amp_level": "O1", "nccl_tune": False, "epochs": 1, "desc": "Mốc chuẩn đối sánh FP32 (BS 64/card = 128 Global, Workers 2)"}, # Nhóm 2: Đối sánh 1:1 trực tiếp với Baseline tại cùng BS 64 {"name": "T2 (Tensor Cores BS64)", "bs": 64, "workers": 2, "amp": True, "amp_level": "O1", "nccl_tune": False, "epochs": 1, "desc": "Kích hoạt 640 Tensor Cores (BS 64/card = 128, AMP O1)"}, # Nhóm 3: Quét tìm điểm ngọt Batch Size với AMP O1 {"name": "T3 (AMP BS48)", "bs": 48, "workers": 2, "amp": True, "amp_level": "O1", "nccl_tune": False, "epochs": 1, "desc": "Đo độ trễ batch nhỏ hơn (BS 48/card = 96, AMP O1)"}, {"name": "T4 (AMP BS72)", "bs": 72, "workers": 2, "amp": True, "amp_level": "O1", "nccl_tune": False, "epochs": 1, "desc": "Thăm dò tăng 12.5% batch (BS 72/card = 144, AMP O1)"}, {"name": "T5 (AMP BS80)", "bs": 80, "workers": 2, "amp": True, "amp_level": "O1", "nccl_tune": False, "epochs": 1, "desc": "Thăm dò tăng 25% batch (BS 80/card = 160, AMP O1)"}, {"name": "T6 (AMP BS96)", "bs": 96, "workers": 2, "amp": True, "amp_level": "O1", "nccl_tune": False, "epochs": 1, "desc": "Kiểm tra giới hạn trên VRAM (BS 96/card = 192, AMP O1)"}, # Nhóm 4: Tối ưu hóa DDP Communication & CPU Workers {"name": "T7 (NCCL Tuned BS64)", "bs": 64, "workers": 2, "amp": True, "amp_level": "O1", "nccl_tune": True, "epochs": 1, "desc": "Tối ưu hóa bus PCIe (NCCL_BUFFSIZE=16M, NCCL_P2P_DISABLE=0)"}, {"name": "T8 (Workers 3 BS64)", "bs": 64, "workers": 3, "amp": True, "amp_level": "O1", "nccl_tune": False, "epochs": 1, "desc": "Tận dụng 4 vCPU với 3 workers/card (Tổng 6 workers)"},]
WARMUP_STEPS = 15 # Loại bỏ 15 bước đầu tiên để loại trừ nhiễu khởi tạo CUDA / Allocator / NCCL
def get_vram_usage(): try: res = subprocess.run( ["nvidia-smi", "--query-gpu=memory.used,memory.total", "--format=csv,noheader,nounits"], capture_output=True, text=True, timeout=2.0 ) if res.returncode == 0 and res.stdout.strip(): lines = res.stdout.strip().split("\n") vrams = [] for l in lines: parts = [float(x.strip()) for x in l.split(",")] vrams.append({"used_mb": parts[0], "total_mb": parts[1], "pct": round(parts[0]/parts[1]*100, 1)}) return vrams except Exception: pass return []
def run_trial(trial_cfg, base_config_path, data_dir, dict_path, log_dir): name = trial_cfg["name"] bs = trial_cfg["bs"] workers = trial_cfg["workers"] amp = trial_cfg["amp"] amp_level = trial_cfg["amp_level"] epochs = trial_cfg["epochs"] nccl_tune = trial_cfg.get("nccl_tune", False) desc = trial_cfg.get("desc", "") print("\n" + "="*90) print(f"🔥 BẮT ĐẦU: {name}") print(f" Tham số: BS/card={bs} (Global BS={bs*2}) | Workers={workers} | AMP={amp} ({amp_level}) | NCCL_Tune={nccl_tune}") print(f" Mục tiêu: {desc}") print("="*90, flush=True) out_temp = os.path.join(log_dir, f"run_{name.replace(' ', '_').replace('(', '').replace(')', '').replace(':', '')}") os.makedirs(out_temp, exist_ok=True) log_file = os.path.join(out_temp, "train.log") # 1. Tạo tệp cấu hình YAML riêng with open(base_config_path, 'r', encoding='utf-8') as f: cfg = yaml.safe_load(f) cfg['Global']['save_model_dir'] = out_temp cfg['Global']['save_res_path'] = os.path.join(out_temp, "predicts.txt") cfg['Global']['character_dict_path'] = dict_path cfg['Global']['checkpoints'] = None cfg['Global']['pretrained_model'] = None cfg['Global']['epoch_num'] = epochs cfg['Global']['print_batch_step'] = 5 # Báo cáo mỗi 5 bước để thu thập nhiều điểm dữ liệu ổn định cfg['Global']['save_epoch_step'] = 999 cfg['Global']['eval_batch_step'] = [0, 99999] cfg['Global']['cal_metric_during_train'] = False cfg['Global']['use_visualdl'] = False cfg['Global']['use_amp'] = amp cfg['Global']['amp_level'] = amp_level cfg['Train']['dataset']['data_dir'] = data_dir cfg['Train']['dataset']['label_file_list'] = [os.path.join(data_dir, "train_label.txt")] cfg['Train']['loader']['batch_size_per_card'] = bs cfg['Train']['loader']['num_workers'] = workers if 'Eval' in cfg and cfg['Eval'] and 'dataset' in cfg['Eval']: cfg['Eval']['dataset']['data_dir'] = data_dir cfg['Eval']['dataset']['label_file_list'] = [os.path.join(data_dir, "val_label.txt")] cfg['Eval']['loader']['batch_size_per_card'] = min(64, bs) cfg['Eval']['loader']['num_workers'] = min(2, workers) trial_yaml_path = os.path.join(out_temp, "config_trial.yml") with open(trial_yaml_path, 'w', encoding='utf-8') as f: yaml.dump(cfg, f) cmd = [ "python3", "-m", "paddle.distributed.launch", "--gpus", "0,1", "tools/train.py", "-c", trial_yaml_path ] # Thiết lập biến môi trường NCCL nếu có cờ nccl_tune proc_env = os.environ.copy() proc_env["PYTHONUTF8"] = "1" if nccl_tune: proc_env["NCCL_BUFFSIZE"] = "16777216" proc_env["NCCL_P2P_DISABLE"] = "0" t_start = time.time() try: with open(log_file, "w", encoding="utf-8") as f_out: proc = subprocess.Popen( cmd, cwd="/kaggle/working/PaddleOCR", stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1, env=proc_env ) warmup_ips = [] steady_ips = [] steady_rc = [] steady_bc = [] steady_loss = [] steady_ctc = [] steady_nrtr = [] steady_mem_alloc = [] steady_mem_res = [] recent_lines = [] for line in proc.stdout: f_out.write(line) f_out.flush() recent_lines.append(line) if len(recent_lines) > 25: recent_lines.pop(0) # Bắt log chi tiết từ PaddleOCR if "ips:" in line and "avg_batch_cost:" in line: m_step = re.search(r"global_step:\s*(\d+)", line) m_ips = re.search(r"ips:\s*([0-9.]+)\s*samples/s", line) m_rc = re.search(r"avg_reader_cost:\s*([0-9.]+)\s*s", line) m_bc = re.search(r"avg_batch_cost:\s*([0-9.]+)\s*s", line) m_loss = re.search(r"loss:\s*([0-9.]+)", line) m_ctc = re.search(r"CTCLoss:\s*([0-9.]+)", line) m_nrtr = re.search(r"NRTRLoss:\s*([0-9.]+)", line) m_mem_res = re.search(r"max_mem_reserved:\s*(\d+)\s*MB", line) m_mem_alloc = re.search(r"max_mem_allocated:\s*(\d+)\s*MB", line) cur_step = int(m_step.group(1)) if m_step else 0 cur_ips = (float(m_ips.group(1)) * 2.0) if m_ips else 0.0 # Dual GPU = 2 * per-card cur_rc = float(m_rc.group(1)) if m_rc else 0.0 cur_bc = float(m_bc.group(1)) if m_bc else 0.0 cur_loss = float(m_loss.group(1)) if m_loss else 0.0 cur_ctc = float(m_ctc.group(1)) if m_ctc else 0.0 cur_nrtr = float(m_nrtr.group(1)) if m_nrtr else 0.0 cur_alloc = int(m_mem_alloc.group(1)) if m_mem_alloc else 0 cur_res = int(m_mem_res.group(1)) if m_mem_res else 0 if cur_step <= WARMUP_STEPS: warmup_ips.append(cur_ips) sys.stdout.write(f" [Warmup Step {cur_step:02d}] Dual IPS: {cur_ips:5.1f} s/s | Cost: {cur_bc:.3f}s | VRAM: {cur_alloc} MB\n") else: steady_ips.append(cur_ips) steady_rc.append(cur_rc) steady_bc.append(cur_bc) steady_loss.append(cur_loss) steady_ctc.append(cur_ctc) steady_nrtr.append(cur_nrtr) if cur_alloc > 0: steady_mem_alloc.append(cur_alloc) if cur_res > 0: steady_mem_res.append(cur_res) sys.stdout.write(f" ⚡ [Steady Step {cur_step:02d}] Dual IPS: {cur_ips:5.1f} s/s | Cost: {cur_bc:.3f}s (Reader: {cur_rc:.4f}s) | Loss: {cur_loss:6.2f} | VRAM: {cur_alloc} MB\n") sys.stdout.flush() proc.wait() elapsed = time.time() - t_start vram_stats = get_vram_usage() if proc.returncode != 0: with open(log_file, "r", encoding="utf-8", errors="ignore") as f: content = f.read().lower() if "out of memory" in content or "bad_alloc" in content or "cudabadalloc" in content: status = "OOM" err_msg = "CUDA Out Of Memory" else: status = "ERROR" err_msg = f"Exit code {proc.returncode}" print(f"❌ {name} THẤT BẠI: {status} ({err_msg})") print("--- Ghi chú lỗi gần nhất ---") for r_l in recent_lines[-8:]: print(" " + r_l.strip()) print("----------------------------") return { "name": name, "batch_size_per_card": bs, "global_batch_size": bs * 2, "num_workers": workers, "amp": amp, "amp_level": amp_level, "nccl_tune": nccl_tune, "status": status, "median_ips": 0.0, "mean_ips": 0.0, "std_ips": 0.0, "cov_pct": 0.0, "avg_batch_cost": 0.0, "avg_reader_cost": 0.0, "compute_cost": 0.0, "reader_ratio": 0.0, "peak_alloc_mb": 0, "peak_res_mb": 0, "loss_initial": 0.0, "loss_final": 0.0, "loss_status": "N/A", "vram": vram_stats, "error": err_msg, "elapsed_sec": round(elapsed, 2) } # Tính toán thống kê chuẩn xác trên các bước Steady-State if steady_ips: med_ips = statistics.median(steady_ips) avg_ips = statistics.mean(steady_ips) sd_ips = statistics.stdev(steady_ips) if len(steady_ips) > 1 else 0.0 cov = (sd_ips / avg_ips * 100.0) if avg_ips > 0 else 0.0 avg_rc = statistics.mean(steady_rc) avg_bc = statistics.mean(steady_bc) avg_compute = avg_bc - avg_rc rr = (avg_rc / avg_bc) if avg_bc > 0 else 0.0 p_alloc = max(steady_mem_alloc) if steady_mem_alloc else 0 p_res = max(steady_mem_res) if steady_mem_res else 0 l_init = steady_loss[0] if steady_loss else 0.0 l_end = steady_loss[-1] if steady_loss else 0.0 l_stat = "HEALTHY" if (not math.isnan(l_end) and not math.isinf(l_end)) else "UNSTABLE" else: # Trường hợp không đủ step sau warmup all_ips = warmup_ips med_ips = statistics.median(all_ips) if all_ips else 0.0 avg_ips = med_ips sd_ips, cov, avg_rc, avg_bc, avg_compute, rr = 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 p_alloc, p_res, l_init, l_end, l_stat = 0, 0, 0.0, 0.0, "SHORT_RUN" print(f"✅ {name} HOÀN THÀNH: Median Dual IPS = {med_ips:.1f} s/s (±{cov:.1f}%) | BatchCost = {avg_bc:.4f}s (Compute: {avg_compute:.4f}s, Reader: {rr*100:.1f}%) | Peak VRAM: {p_alloc} MB ({p_alloc/15360*100:.1f}%) | Loss: {l_init:.2f} -> {l_end:.2f} ({l_stat})") return { "name": name, "batch_size_per_card": bs, "global_batch_size": bs * 2, "num_workers": workers, "amp": amp, "amp_level": amp_level, "nccl_tune": nccl_tune, "status": "SUCCESS", "median_ips": round(med_ips, 1), "mean_ips": round(avg_ips, 1), "std_ips": round(sd_ips, 2), "cov_pct": round(cov, 1), "avg_batch_cost": round(avg_bc, 4), "avg_reader_cost": round(avg_rc, 4), "compute_cost": round(avg_compute, 4), "reader_ratio": round(rr, 3), "peak_alloc_mb": p_alloc, "peak_res_mb": p_res, "loss_initial": round(l_init, 2), "loss_final": round(l_end, 2), "loss_status": l_stat, "vram": vram_stats, "error": None, "elapsed_sec": round(elapsed, 2) } except Exception as e: print(f"❌ Exception in trial {name}: {e}") return { "name": name, "batch_size_per_card": bs, "global_batch_size": bs * 2, "num_workers": workers, "amp": amp, "amp_level": amp_level, "nccl_tune": nccl_tune, "status": "CRASH", "median_ips": 0.0, "mean_ips": 0.0, "error": str(e), "elapsed_sec": round(time.time() - t_start, 2) }
def main(): base_cfg = "/kaggle/working/configs/rec_cham_v24.yml" data_dir = "/kaggle/working/data/cham_synthetic_benchmark" dict_path = "/kaggle/working/data/cham_dict_v24.txt" log_dir = "/kaggle/working/benchmark_output" results = [] print("="*90) print("🚀 BẮT ĐẦU CHẠY BENCHMARK V2 CHUẨN XÁC CAO TRÊN DUAL TESLA T4x2") print(f"Tổng số trials tập trung: {len(TRIALS)}") print("="*90, flush=True) for trial_cfg in TRIALS: res = run_trial(trial_cfg, base_cfg, data_dir, dict_path, log_dir) results.append(res) time.sleep(3) # Thu hồi tài nguyên và để GPU hạ nhiệt # Baseline Median IPS (Trial 1) baseline_ips = results[0]["median_ips"] if results and results[0]["status"] == "SUCCESS" else 1.0 # Tính toán Speedup và thời gian 40 epochs (10M mẫu) for r in results: if r["status"] == "SUCCESS" and r["median_ips"] > 0: r["speedup_pct"] = round(((r["median_ips"] - baseline_ips) / baseline_ips) * 100, 1) # 250,000 mẫu x 40 epochs = 10,000,000 mẫu est_hours = 10000000.0 / (r["median_ips"] * 3600.0) r["est_40_epoch_hours"] = round(est_hours, 2) else: r["speedup_pct"] = 0.0 r["est_40_epoch_hours"] = 0.0
# Xuất JSON report_json = "/kaggle/working/benchmark_t4_report.json" with open(report_json, "w", encoding="utf-8") as f: json.dump(results, f, indent=2, ensure_ascii=False) # In bảng Markdown chuẩn mực print("\n" + "="*110) print("📊 BẢNG TỔNG KẾT BENCHMARK V2 DUAL GPU TESLA T4x2 (STEADY-STATE)") print("="*110) header = f"{'Trial Name':<24} | {'BS/GPU':<7} | {'TotalBS':<7} | {'W':<3} | {'Mode':<7} | {'Median IPS':<11} | {'Speedup':<8} | {'BatchCost':<10} | {'Compute':<9} | {'Peak VRAM':<10} | {'Status'}" print(header) print("-" * len(header)) md_table = [ "| Thí nghiệm | BS/GPU | Tổng BS | Workers | Chế độ | Median Dual IPS (mẫu/s) | Tăng tốc (%) | Batch Cost (s) | GPU Compute (s) | Peak VRAM | Trạng thái |", "| :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- | :--- |" ] for r in results: mode = f"AMP-{r.get('amp_level', 'O1')}" if r.get('amp') else "FP32" if r.get("nccl_tune"): mode += "+NCCL" v_ips = f"{r['median_ips']:.1f}" if r['status'] == "SUCCESS" else "N/A" v_speedup = f"+{r['speedup_pct']}%" if r['status'] == "SUCCESS" else "N/A" v_bc = f"{r['avg_batch_cost']:.4f}s" if r['status'] == "SUCCESS" else "N/A" v_cmp = f"{r.get('compute_cost', 0):.4f}s" if r['status'] == "SUCCESS" else "N/A" v_vram = f"{r.get('peak_alloc_mb', 0)} MB ({r.get('peak_alloc_mb', 0)/15360*100:.1f}%)" if r['status'] == "SUCCESS" else "N/A" row_str = f"{r['name']:<24} | {r['batch_size_per_card']:<7} | {r['global_batch_size']:<7} | {r['num_workers']:<3} | {mode:<7} | {v_ips:<11} | {v_speedup:<8} | {v_bc:<10} | {v_cmp:<9} | {v_vram:<10} | {r['status']}" print(row_str) md_table.append(f"| {r['name']} | {r['batch_size_per_card']} | {r['global_batch_size']} | {r['num_workers']} | {mode} | **{v_ips}** | **{v_speedup}** | {v_bc} | {v_cmp} | {v_vram} | {r['status']} |") print("="*110) # Tìm cấu hình quán quân successful_trials = [r for r in results if r["status"] == "SUCCESS"] if successful_trials: best_trial = max(successful_trials, key=lambda x: x["median_ips"]) print(f"\n🏆 CẤU HÌNH TỐI ƯU NHẤT: {best_trial['name']}") print(f"🔥 Max Steady-State Dual IPS: {best_trial['median_ips']} mẫu/giây (Tăng tốc +{best_trial['speedup_pct']}% so với Baseline)") print(f"⚡ Thời gian hoàn thành 40 epochs: {best_trial['est_40_epoch_hours']} giờ (so với Baseline {results[0].get('est_40_epoch_hours', 'N/A')} giờ)") print(f"💾 Peak Memory tiêu thụ: {best_trial.get('peak_alloc_mb', 0)} MB / 15,360 MB ({best_trial.get('peak_alloc_mb', 0)/15360*100:.1f}%)") print(f"📈 Tính ổn định Loss: {best_trial.get('loss_initial', 0)} -> {best_trial.get('loss_final', 0)} ({best_trial.get('loss_status', 'N/A')})") md_summary = f"""\n\n## 🏆 Kết luận Cấu hình Tối ưu Tuyệt đối trên Dual GPU T4x2- **Tên cấu hình**: `{best_trial['name']}`- **Batch Size mỗi card**: `{best_trial['batch_size_per_card']}` (Tổng Global Batch Size: `{best_trial['global_batch_size']}`)- **Số Workers**: `{best_trial['num_workers']}`- **Chế độ tính toán**: `{'AMP ' + best_trial['amp_level'] if best_trial['amp'] else 'FP32'}`- **Throughput Steady-State Dual IPS**: **`{best_trial['median_ips']} mẫu/s`** (Tăng **`+{best_trial['speedup_pct']}%`**)- **Thời gian hoàn thành 40 epochs (10M mẫu)**: **`{best_trial['est_40_epoch_hours']} giờ`** (Tiết kiệm **`{results[0].get('est_40_epoch_hours', 0) - best_trial['est_40_epoch_hours']:.2f} giờ`**)- **Mức tiêu thụ VRAM đỉnh**: **`{best_trial.get('peak_alloc_mb', 0)} MB`** (**`{best_trial.get('peak_alloc_mb', 0)/15360*100:.1f}%`** VRAM)- **Kiểm định Loss**: `{best_trial.get('loss_initial', 0)}` -> `{best_trial.get('loss_final', 0)}` (`{best_trial.get('loss_status', 'N/A')}`)""" else: md_summary = "\n\n❌ Không có trial nào thành công."
md_report = "# Báo Cáo Benchmark V2 Chuẩn Xác Cao Trên Kaggle Dual GPU Tesla T4x2 (Cham-OCR V24)\n\n" + "\n".join(md_table) + md_summary with open("/kaggle/working/benchmark_t4_summary.md", "w", encoding="utf-8") as f: f.write(md_report) print(f"\n✅ Đã lưu kết quả tại: {report_json}") print(f"✅ Đã lưu tóm tắt tại: /kaggle/working/benchmark_t4_summary.md")
if __name__ == '__main__': main()''' add_code(f"%%writefile /kaggle/working/scripts/benchmark_runner.py\n{benchmark_runner_code}")
# Cell 6: Thực thi Benchmark add_md("## 5. Khởi chạy toàn bộ quy trình Benchmark V2") add_code("""import os, time%cd /kaggle/working
t_start = time.time()!python3 scripts/benchmark_runner.pyprint(f"\\n🎉 Toàn bộ Benchmark V2 hoàn tất sau {(time.time()-t_start)/60:.2f} phút!")""")
# Cell 7: Đóng gói kết quả & Dọn dẹp để Kaggle Output tải nhanh add_md("## 6. Đóng gói kết quả ZIP & Dọn dẹp PaddleOCR thư mục làm việc") add_code("""import os, zipfile, shutil
zip_path = "/kaggle/working/benchmark_t4_results.zip"print(f"📦 Đang nén kết quả vào {zip_path}...")
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf: for f in ["benchmark_t4_report.json", "benchmark_t4_summary.md"]: p = os.path.join("/kaggle/working", f) if os.path.exists(p): zipf.write(p, f) # Nén các log file log_dir = "/kaggle/working/benchmark_output" if os.path.exists(log_dir): for root, dirs, files in os.walk(log_dir): for file in files: if file.endswith('.log') or file.endswith('.yml'): full_p = os.path.join(root, file) rel_p = os.path.relpath(full_p, "/kaggle/working") zipf.write(full_p, rel_p)
print(f"✅ Hoàn tất đóng gói! Kích thước file: {os.path.getsize(zip_path)/(1024*1024):.2f} MB")
# Dọn dẹp thư mục PaddleOCR và data trong /kaggle/working để Kaggle Output không bị phình toprint("🧹 Đang dọn dẹp các tệp tạm để giải phóng Output Kaggle...")if os.path.exists('/kaggle/working/PaddleOCR'): shutil.rmtree('/kaggle/working/PaddleOCR', ignore_errors=True)if os.path.exists('/kaggle/working/data'): shutil.rmtree('/kaggle/working/data', ignore_errors=True)print("✅ Dọn dẹp hoàn tất. Output chỉ giữ lại file báo cáo và file ZIP.")""")
notebook_dict = { "cells": cells, "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.10.12" } }, "nbformat": 4, "nbformat_minor": 4 } submission_dir = 'ocr-training/output/kaggle_benchmark_submission' os.makedirs(submission_dir, exist_ok=True) nb_path = os.path.join(submission_dir, 'kaggle_t4_benchmark.ipynb') with open(nb_path, 'w', encoding='utf-8') as f: json.dump(notebook_dict, f, indent=1, ensure_ascii=False) meta_path = os.path.join(submission_dir, 'kernel-metadata.json') metadata = { "id": "gustavnguyen/cham-ocr-t4-benchmark", "title": "cham-ocr-t4-benchmark", "code_file": "kaggle_t4_benchmark.ipynb", "language": "python", "kernel_type": "notebook", "is_private": "true", "enable_gpu": "true", "enable_tpu": "false", "enable_internet": "true", "dataset_sources": [ "gustavnguyen/cham-ocr-v5-assets" ], "competition_sources": [], "kernel_sources": [], "model_sources": [], "machine_shape": "NvidiaTeslaT4" } with open(meta_path, 'w', encoding='utf-8') as f: json.dump(metadata, f, indent=2) print(f"✅ Đã tạo thành công Notebook tại: {nb_path}") print(f"✅ Đã tạo kernel-metadata tại: {meta_path}") return nb_path, meta_path
if __name__ == '__main__': main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039#!/usr/bin/env python3# -*- coding: utf-8 -*-"""Master Kaggle Dispatcher for Cham-OCR V25 Multi-Stage Training.Prepares, validates, and dispatches Stage 1, 2, or 3 training kernels to Kaggle Dual T4x2.
Core Invariants Enforced: 1. Global.epoch_num = 40 locked across all stages (T_max = 87,480 steps, 2187 steps/epoch). 2. Linear warmup runs exactly once (Epochs 1-2 = 4,374 steps). 3. Decoupled Stage Exit via tools/program.py hook: - Stage 1 stops at Epoch 12 (global_step 26,244) - Stage 2 stops at Epoch 22 (global_step 48,114) - Stage 3 stops at Epoch 40 (global_step 87,480) 4. Validation freeze: 10,000 samples and canonical 162-token NFC dictionary frozen bitwise. 5. Dataset distribution verified with manifest & statistics assertions. 6. Resumes via Global.checkpoints (loading weights, optimizer, lr_scheduler, states). 7. Strict deterministic archive paths; zero os.walk('/kaggle') wildcard scanning. 8. Kaggle account: "gustavnguyen", Accelerator: NvidiaTeslaT4 (Dual T4x2)."""
import osimport sysimport jsonimport timeimport shutilimport argparse
if sys.stdout and hasattr(sys.stdout, 'reconfigure'): sys.stdout.reconfigure(encoding='utf-8')
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))TRAINING_DIR = os.path.dirname(SCRIPT_DIR)PROJECT_ROOT = os.path.dirname(TRAINING_DIR)sys.path.insert(0, SCRIPT_DIR)
from kaggle_auth import init_kaggle_authinit_kaggle_auth()
from kaggle_ops import get_authenticated_api, monitor_kernel
def read_file(path): with open(path, 'r', encoding='utf-8') as f: return f.read()
def build_v25_notebook(stage=1, epoch_num=12, prev_epochs=0): """Xây dựng Jupyter Notebook hoàn chỉnh, tự chứa mọi thành phần cho V25 trên Kaggle.""" stage_end_epoch = prev_epochs + epoch_num global_total_epochs = 40 print(f"📦 Đang đóng gói mã nguồn và cấu hình V25 Chặng {stage}:") print(f" • Epochs chặng này : Epoch {prev_epochs + 1} -> {stage_end_epoch} (tổng {epoch_num} epochs)") print(f" • Toàn cầu epoch_num : {global_total_epochs} (T_max = 87,480 steps)") print(f" • Stage exit epoch : {stage_end_epoch}")
manifest_code = read_file(os.path.join(TRAINING_DIR, "configs", "v25_dataset_manifest.json")) generate_data_code = read_file(os.path.join(TRAINING_DIR, "scripts", "generate_data_v25.py")) build_dict_code = read_file(os.path.join(TRAINING_DIR, "scripts", "build_dict_v25.py")) surgery_weights_code = read_file(os.path.join(TRAINING_DIR, "scripts", "surgery_v25_weights.py")) config_v25_code = read_file(os.path.join(TRAINING_DIR, "configs", "rec_cham_v25.yml")) dict_v25_code = read_file(os.path.join(TRAINING_DIR, "data", "cham_dict_v25.txt"))
cells = []
def add_md(text): cells.append({ "cell_type": "markdown", "metadata": {}, "source": [line + '\n' for line in text.splitlines()] })
def add_code(code_str): cells.append({ "cell_type": "code", "execution_count": None, "metadata": {}, "outputs": [], "source": [line + '\n' for line in code_str.splitlines()] })
# Header add_md(f"""# Huấn Luyện Mô Hình Nhận Diện Chữ Chăm PP-OCRv4 V25 (Chặng {stage})## Phần cứng: Kaggle Dual GPU Tesla T4x2 (`--accelerator NvidiaTeslaT4`)
### Kiến Trúc Đa Chặng Chuẩn Hóa (Multi-Stage Invariants):- **Toàn bộ tiến trình**: Cố định `Global.epoch_num = 40` ($T_{{max}} = 87,480$ bước, 2,187 steps/epoch).- **Phân chặng**: - Chặng 1: Epochs 1 -> 12 (global_step: 0 -> 26,244, Warmup 2 epochs đầu). - Chặng 2: Epochs 13 -> 22 (global_step: 26,244 -> 48,114, Cosine tiếp tục liên tục). - Chặng 3: Epochs 23 -> 40 (global_step: 48,114 -> 87,480, hội tụ cực đại).- **Chặng hiện tại ({stage})**: Huấn luyện từ **Epoch {prev_epochs + 1}** đến **Epoch {stage_end_epoch}**.- **Đóng băng Validation**: Tập Validation (10,000 mẫu) và Từ điển NFC (162 tokens) đóng băng tuyệt đối giữa 3 chặng.- **Dữ liệu huấn luyện**: 140,000 mẫu Train/chặng tuân thủ nghiêm ngặt phân bố Manifest.""")
# Phase 1: Environment & GPU Verification add_md("## Phase 1: Môi Trường & Xác Minh Dual GPU Tesla T4x2") add_code("""# 1. Khóa cứng NumPy 1.26.4 và OpenCV 4.9.0.80 để đồng bộ C-ABI (0x1000009)!pip install --quiet "numpy==1.26.4" "opencv-python==4.9.0.80" "opencv-python-headless==4.9.0.80" "imgaug<=0.4.0" pyclipper shapely lmdb attrdict fonttools pyyaml Pillow rapidfuzz scikit-image lxml openpyxl visualdl!pip install --quiet "paddlepaddle-gpu>=2.6.0" -i https://www.paddlepaddle.org.cn/packages/stable/cu118/
# 2. Cấu hình sitecustomize.py toàn cục để mọi tiến trình Python con (kể cả rank workers) đều có monkeypatch tương thíchimport osimport sys
sitecustomize_content = '''import sysimport osos.environ["FLAGS_allocator_strategy"] = "auto_growth"os.environ["FLAGS_fraction_of_gpu_memory_to_use"] = "0.80"
import numpy as npif not hasattr(np, 'sctypes'): np.sctypes = {'int': [np.int8, np.int16, np.int32, np.int64], 'uint': [np.uint8, np.uint16, np.uint32, np.uint64], 'float': [np.float16, np.float32, np.float64], 'complex': [np.complex64, np.complex128], 'others': [bool, object, bytes, str]}if not hasattr(np, 'bool'): np.bool = boolif not hasattr(np, 'int'): np.int = intif not hasattr(np, 'float'): np.float = floatif not hasattr(np, 'typeDict'): np.typeDict = {}
# Fallback mock cho visualdl để tránh ModuleNotFoundError khi tools/program.py import VDLLoggertry: import visualdlexcept Exception: import types vdl = types.ModuleType('visualdl') class DummyLogWriter: def __init__(self, *args, **kwargs): pass def add_scalar(self, *args, **kwargs): pass def close(self): pass vdl.LogWriter = DummyLogWriter sys.modules['visualdl'] = vdl'''
for p in sys.path: if 'site-packages' in p or 'dist-packages' in p: try: with open(os.path.join(p, 'sitecustomize.py'), 'w', encoding='utf-8') as f: f.write(sitecustomize_content) except Exception: pass
with open('/kaggle/working/sitecustomize.py', 'w', encoding='utf-8') as f: f.write(sitecustomize_content)
# 3. Sanity check: Xác minh trực tiếp các thư viện trọng yếu trên subprocess (môi trường thực thi của training)print("=" * 60)print("🔍 SUBPROCESS ENVIRONMENT CHECK:")!python3 -c "import numpy as np; print('NumPy Version :', np.__version__); assert np.__version__.startswith('1.'), 'NumPy must be 1.x'; import cv2; print('OpenCV Version :', cv2.__version__); import imgaug; print('ImgAug Version :', imgaug.__version__); import paddle; print('Paddle Version :', paddle.__version__); import rapidfuzz; from rapidfuzz.distance import Levenshtein; print('RapidFuzz Version :', rapidfuzz.__version__); import visualdl; from visualdl import LogWriter; print('VisualDL Version :', visualdl.__version__ if hasattr(visualdl, '__version__') else 'mocked')"print("=" * 60)
# 4. Kiểm tra GPUimport paddleprint("🚀 PADDLE GPU STATUS:")print("Paddle Version :", paddle.__version__)print("Compiled with CUDA :", paddle.is_compiled_with_cuda())gpu_count = paddle.device.cuda.device_count()print(f"Detected GPU Count : {gpu_count}")print("=" * 60)
assert gpu_count == 2, f"❌ LỖI: Bắt buộc cấu hình Dual GPU Tesla T4x2 (2 cards) nhưng chỉ phát hiện {gpu_count} GPU! Vui lòng chọn Accelerator = GPU T4 x2."for i in range(gpu_count): dev_name = paddle.device.cuda.get_device_name(i) print(f" - GPU {i}: {dev_name}") assert "T4" in dev_name, f"❌ LỖI: GPU {i} là {dev_name}, không phải Tesla T4!"""")
# Phase 2: Workspace Setup, Fonts, Base Weights & PaddleOCR Patch add_md("## Phase 2: Thiết Lập Thư Mục, Fonts & Vá Hook Stage-End Cho PaddleOCR") v24_extract_code = """# 2. Định vị checkpoint V24 từ dataset gustavnguyen/cham-ocr-v24-checkpointv24_extracted_dir = "/kaggle/working/data/v24_extracted"os.makedirs(v24_extracted_dir, exist_ok=True)
# Kiểm tra thư mục dataset được mount trực tiếpv24_dataset_dir = "/kaggle/input/cham-ocr-v24-checkpoint"if os.path.exists(v24_dataset_dir): print("📦 Tìm thấy dataset V24 tại:", v24_dataset_dir) for item in os.listdir(v24_dataset_dir): s = os.path.join(v24_dataset_dir, item) d = os.path.join(v24_extracted_dir, item) if os.path.isdir(s): shutil.copytree(s, d, dirs_exist_ok=True) else: shutil.copy2(s, d)
# Kiểm tra các archive zip dự phòng nếu cófor zpath in [ "/kaggle/input/cham-ocr-v24-checkpoint/rec_cham_v24_best.zip", "/kaggle/input/paddleocr-cham-finetune/rec_cham_v24_best.zip", "/kaggle/input/cham-ocr-v5-assets/rec_cham_v24_best.zip"]: if os.path.exists(zpath): print(f"📦 Giải nén bổ sung archive V24 từ: {zpath}") with zipfile.ZipFile(zpath, 'r') as zf: zf.extractall(v24_extracted_dir) break
print("✅ Thư mục V24 giải nén:", os.listdir(v24_extracted_dir) if os.path.exists(v24_extracted_dir) else "N/A")""" if stage == 1 else ""
phase2_template = """import osimport shutilimport zipfile
os.makedirs('/kaggle/working/data/fonts', exist_ok=True)os.makedirs('/kaggle/working/data/cham_synthetic_v25', exist_ok=True)os.makedirs('/kaggle/working/configs', exist_ok=True)os.makedirs('/kaggle/working/scripts', exist_ok=True)os.makedirs('/kaggle/working/output/rec_cham_v25', exist_ok=True)os.makedirs('/kaggle/working/output/rec_cham_v25_init', exist_ok=True)
# 1. Tìm và sao chép fontsfont_found = Falsefor search_dir in ['/kaggle/input/cham-ocr-v5-assets', '/kaggle/input']: if os.path.exists(search_dir): for root, dirs, files in os.walk(search_dir): if 'v5-assets' in root or root == search_dir: for f in files: if f.endswith(('.ttf', '.otf')) and 'Cham' in f: shutil.copy2(os.path.join(root, f), os.path.join('/kaggle/working/data/fonts', f)) font_found = True
# Tải font dự phòng nếu chưa cóif not font_found: print("⏳ Tải NotoSansCham fonts từ Google Fonts...") import urllib.request urllib.request.urlretrieve("https://raw.githubusercontent.com/googlefonts/noto-fonts/main/hinted/ttf/NotoSansCham/NotoSansCham-Regular.ttf", "/kaggle/working/data/fonts/NotoSansCham-Regular.ttf") urllib.request.urlretrieve("https://raw.githubusercontent.com/googlefonts/noto-fonts/main/hinted/ttf/NotoSansCham/NotoSansCham-Bold.ttf", "/kaggle/working/data/fonts/NotoSansCham-Bold.ttf")
print("✅ Thư mục fonts:", os.listdir('/kaggle/working/data/fonts'))__V24_EXTRACT_CODE__# 3. Clone PaddleOCR nếu chưa cóif not os.path.exists('/kaggle/working/PaddleOCR'): print("⏳ Đang clone PaddleOCR release/2.7...") !git clone -b release/2.7 --depth 1 https://github.com/PaddlePaddle/PaddleOCR.git /kaggle/working/PaddleOCR shutil.copy2('/kaggle/working/sitecustomize.py', '/kaggle/working/PaddleOCR/sitecustomize.py')else: print("✅ PaddleOCR đã tồn tại sẵn.")
# 4. Patch tools/program.py chèn hook stage_end_epoch để ngắt chặng an toàn (Decoupled Stage Exit)program_py = '/kaggle/working/PaddleOCR/tools/program.py'with open(program_py, 'r', encoding='utf-8') as f: content = f.read()
stage_hook = ''' # [CHAM-OCR V25] Decoupled Stage Exit Hook stage_end_epoch = config.get("Global", {}).get("stage_end_epoch", None) if stage_end_epoch is not None and epoch >= int(stage_end_epoch): logger.info("🛑 [STAGE EXIT] Dat moc stage_end_epoch {}. Dung chang an toan sau khi luu xong Epoch {} (global_step {}).".format(stage_end_epoch, epoch, global_step)) break'''
if "stage_end_epoch" not in content: target = " best_str = 'best metric, {}'" if target in content: parts = content.rsplit(target, 1) content = parts[0] + stage_hook + "\\n" + target + parts[1] with open(program_py, 'w', encoding='utf-8') as f: f.write(content) print("✅ Đã vá thành công hook 'stage_end_epoch' (sau save_model) vào PaddleOCR/tools/program.py!")else: print("✅ PaddleOCR/tools/program.py đã chứa hook 'stage_end_epoch'.")
# 5. Xác minh trực tiếp toàn bộ module của PaddleOCR (program, metrics, dataloader)%cd /kaggle/working/PaddleOCR!python3 -c "import tools.program as program; from ppocr.metrics import build_metric; from ppocr.data import build_dataloader; print('✅ PaddleOCR core modules (program, metrics, dataloader) verified!')"%cd /kaggle/working""" add_code(phase2_template.replace("__V24_EXTRACT_CODE__", v24_extract_code))
# Phase 3: Embed Source Scripts & Configs add_md("## Phase 3: Nạp Toàn Bộ Mã Nguồn & Cấu Hình Chuẩn Hóa V25") add_code(f"%%writefile /kaggle/working/configs/v25_dataset_manifest.json\n{manifest_code}") add_code(f"%%writefile /kaggle/working/scripts/generate_data_v25.py\n{generate_data_code}") add_code(f"%%writefile /kaggle/working/scripts/build_dict_v25.py\n{build_dict_code}") add_code(f"%%writefile /kaggle/working/scripts/surgery_v25_weights.py\n{surgery_weights_code}") add_code(f"%%writefile /kaggle/working/configs/rec_cham_v25.yml\n{config_v25_code}") add_code(f"%%writefile /kaggle/working/data/cham_dict_v25.txt\n{dict_v25_code}")
# Phase 4: Data Preparation & Validation Freeze if stage == 1: add_md("## Phase 4: Sinh Dữ Liệu V25 Sạch (140,000 Train + 10,000 Val) & Đóng Băng Val") add_code("""import timeimport osimport hashlibimport jsonimport unicodedatafrom collections import Counter%cd /kaggle/working
print("⚡ Khởi chạy sinh 140,000 mẫu Train + 10,000 mẫu Val V25 sạch theo Manifest...")t_gen_start = time.time()!python3 scripts/generate_data_v25.py \\ --manifest configs/v25_dataset_manifest.json \\ --output_dir /kaggle/working/data/cham_synthetic_v25 \\ --num_train 140000 \\ --num_val 10000 \\ --workers 4
print(f"🎉 Hoàn thành sinh dữ liệu trong {(time.time() - t_gen_start)/60:.2f} phút!")
# 1. Kiểm tra số lượng và phân bố thống kê theo Manifesttrain_label_path = "/kaggle/working/data/cham_synthetic_v25/train_label.txt"val_label_path = "/kaggle/working/data/cham_synthetic_v25/val_label.txt"
with open(train_label_path, 'r', encoding='utf-8') as f: train_lines = [line.strip() for line in f if line.strip()]with open(val_label_path, 'r', encoding='utf-8') as f: val_lines = [line.strip() for line in f if line.strip()]
print("=" * 70)print("📊 KIỂM TRA PHÂN BỐ DỮ LIỆU HUẤN LUYỆN (DATASET DISTRIBUTION AUDIT):")print(f" • Số mẫu Train : {len(train_lines):,} (yêu cầu đúng 140,000)")print(f" • Số mẫu Val : {len(val_lines):,} (yêu cầu đúng 10,000)")assert len(train_lines) == 140000, f"❌ LỖI: Số mẫu Train ({len(train_lines)}) không khớp 140,000!"assert len(val_lines) == 10000, f"❌ LỖI: Số mẫu Val ({len(val_lines)}) không khớp 10,000!"
# Thống kê đặc trưng các trụ cộtcham_digits = set("꩐꩑꩒꩓꩔꩕꩖꩗꩘꩙")has_digit = 0has_au_o = 0has_double_danda = 0has_latin = 0max_len = 0
for line in train_lines: parts = line.split('\\t', 1) text = parts[1] if len(parts) > 1 else parts[0] max_len = max(max_len, len(text)) if any(c in cham_digits for c in text): has_digit += 1 if ('ꨲ' in text) or ('ꨶ' in text): has_au_o += 1 if '꩝꩝' in text: has_double_danda += 1 if any(('a' <= c.lower() <= 'z') for c in text): has_latin += 1
print(f" • Dòng chứa số/khổ thơ Chăm (꩑꩞..): {has_digit:,} ({has_digit/len(train_lines):.2%})")print(f" • Dòng chứa cặp đối kháng ꨲ/ꨶ : {has_au_o:,} ({has_au_o/len(train_lines):.2%})")print(f" • Dòng chứa Double Danda ꩝꩝ : {has_double_danda:,} ({has_double_danda/len(train_lines):.2%})")print(f" • Dòng song ngữ/chữ Latin : {has_latin:,} ({has_latin/len(train_lines):.2%})")print(f" • Max length thực tế : {max_len} (giới hạn an toàn <= 80)")assert max_len <= 80, f"❌ LỖI: Phát hiện nhãn dài {max_len} > 80!"print("=" * 70)
# 2. Tạo manifest đóng băng Validation (SHA256 Hash Invariant)def file_sha256(p): h = hashlib.sha256() with open(p, 'rb') as f: while True: chunk = f.read(65536) if not chunk: break h.update(chunk) return h.hexdigest()
val_hash = file_sha256(val_label_path)dict_hash = file_sha256("/kaggle/working/data/cham_dict_v25.txt")val_freeze_manifest = { "val_samples": len(val_lines), "val_label_sha256": val_hash, "dict_sha256": dict_hash, "timestamp": time.time()}freeze_manifest_path = "/kaggle/working/data/cham_synthetic_v25/val_freeze_manifest.json"with open(freeze_manifest_path, 'w', encoding='utf-8') as f: json.dump(val_freeze_manifest, f, indent=2)
print(f"🔒 ĐÃ KHÓA ĐÓNG BĂNG TẬP VALIDATION (SHA256: {val_hash})")""") else: prev_stage = stage - 1 add_md(f"## Phase 4: Kế Thừa Validation Đóng Băng & Sinh 140,000 Mẫu Train Mới (Chặng {stage})") phase4_template = """import osimport sysimport timeimport shutilimport zipfileimport hashlibimport json
%cd /kaggle/working
print("❄️ ĐANG TRÍCH XUẤT VÀ XÁC MINH TẬP VALIDATION ĐÓNG BĂNG...")
target_val_dir = "/kaggle/working/data/cham_synthetic_v25"os.makedirs(target_val_dir, exist_ok=True)val_label_path = os.path.join(target_val_dir, "val_label.txt")
# 1. Kiểm tra xem thư mục Validation đã giải nén sẵn trong Kaggle Dataset khôngval_dir_candidates = [ "/kaggle/input/cham-ocr-v25-stage1-checkpoint/cham_v25_val_freeze", "/kaggle/input/datasets/gustavnguyen/cham-ocr-v25-stage1-checkpoint/cham_v25_val_freeze", "/kaggle/input/cham-ocr-v25-stage__PREV_STAGE__-checkpoint/cham_v25_val_freeze", "/kaggle/input/datasets/gustavnguyen/cham-ocr-v25-stage__PREV_STAGE__-checkpoint/cham_v25_val_freeze", "/kaggle/input/paddleocr-cham-v25-stage__PREV_STAGE__/cham_v25_val_freeze", "/kaggle/input/paddleocr-cham-v25-stage1/cham_v25_val_freeze"]
for cand_dir in val_dir_candidates: cand_label = os.path.join(cand_dir, "val_label.txt") if os.path.exists(cand_label): print(f"📦 Tìm thấy thư mục Val đóng băng sẵn tại: {cand_dir}") for item in os.listdir(cand_dir): s = os.path.join(cand_dir, item) d = os.path.join(target_val_dir, item) if os.path.isdir(s): if not os.path.exists(d): shutil.copytree(s, d, dirs_exist_ok=True) else: if not os.path.exists(d): shutil.copy2(s, d) break
# 2. Nếu chưa có thư mục, tìm tệp zip validation đóng băngif not os.path.exists(val_label_path): freeze_zip_candidates = [ "/kaggle/input/cham-ocr-v25-stage1-checkpoint/cham_v25_val_freeze.zip", "/kaggle/input/datasets/gustavnguyen/cham-ocr-v25-stage1-checkpoint/cham_v25_val_freeze.zip", "/kaggle/input/datasets/gustavnguyen/cham-ocr-v25-stage__PREV_STAGE__-checkpoint/cham_v25_val_freeze.zip", "/kaggle/input/paddleocr-cham-v25-stage__PREV_STAGE__/cham_v25_val_freeze.zip", "/kaggle/input/paddleocr-cham-v25-stage1/cham_v25_val_freeze.zip", "/kaggle/working/cham_v25_val_freeze.zip" ] freeze_zip_path = None for cand in freeze_zip_candidates: if os.path.exists(cand): freeze_zip_path = cand break
if not freeze_zip_path and os.path.exists('/kaggle/input'): print("🔍 Đang tìm kiếm tệp Val đóng băng trong /kaggle/input...") for root, dirs, files in os.walk('/kaggle/input'): if 'cham_v25_val_freeze.zip' in files: freeze_zip_path = os.path.join(root, 'cham_v25_val_freeze.zip') break elif '_output_.zip' in files: try: oz_p = os.path.join(root, '_output_.zip') with zipfile.ZipFile(oz_p, 'r') as oz: for name in oz.namelist(): if 'cham_v25_val_freeze.zip' in name: oz.extract(name, '/kaggle/working') freeze_zip_path = '/kaggle/working/cham_v25_val_freeze.zip' break except Exception as e: print(f"⚠️ Lỗi đọc {root}/_output_.zip: {e}") if freeze_zip_path: break
if freeze_zip_path and os.path.exists(freeze_zip_path): print(f"📦 Đang giải nén tập Val đóng băng từ: {freeze_zip_path}...") with zipfile.ZipFile(freeze_zip_path, 'r') as zf: zf.extractall(target_val_dir)
assert os.path.exists(val_label_path), f"❌ LỖI: Không tìm thấy val_label.txt sau khi nạp tập Val đóng băng Chặng __PREV_STAGE__!"
# 2. Xác minh hash tính toàn vẹn của Validationdef file_sha256(p): h = hashlib.sha256() with open(p, 'rb') as f: while True: chunk = f.read(65536) if not chunk: break h.update(chunk) return h.hexdigest()
val_label_path = "/kaggle/working/data/cham_synthetic_v25/val_label.txt"freeze_manifest_path = "/kaggle/working/data/cham_synthetic_v25/val_freeze_manifest.json"
assert os.path.exists(val_label_path), "❌ Không tìm thấy val_label.txt sau khi giải nén!"current_val_hash = file_sha256(val_label_path)
if os.path.exists(freeze_manifest_path): with open(freeze_manifest_path, 'r', encoding='utf-8') as f: fmanifest = json.load(f) expected_hash = fmanifest.get('val_label_sha256') print(f"🔍 Expected Val SHA256 : {expected_hash}") print(f"🔍 Current Val SHA256 : {current_val_hash}") assert current_val_hash == expected_hash, "❌ LỖI: Mã băm tập Val bị sai lệch so với bản đóng băng Chặng 1!" print("✅ VALIDATION FREEZE AUDIT: SHA256 MATCHES 100%! Tập Val giữ nguyên hoàn hảo.")
with open(val_label_path, 'r', encoding='utf-8') as f: val_lines = [l.strip() for l in f if l.strip()]assert len(val_lines) == 10000, f"❌ LỖI: Số dòng val là {len(val_lines)} != 10,000!"
# 3. Sinh 140,000 mẫu Train mới cho Chặng __STAGE__ (refresh data)print("⚡ Khởi chạy sinh 140,000 mẫu Train mới cho Chặng __STAGE__ (bỏ qua sinh Val)...")t_gen_start = time.time()!python3 scripts/generate_data_v25.py \\ --manifest configs/v25_dataset_manifest.json \\ --output_dir /kaggle/working/data/cham_synthetic_v25 \\ --num_train 140000 \\ --num_val 0 \\ --workers 4
print(f"🎉 Hoàn thành sinh tập Train mới trong {(time.time() - t_gen_start)/60:.2f} phút!")
# 4. Kiểm tra phân bổ Train mớitrain_label_path = "/kaggle/working/data/cham_synthetic_v25/train_label.txt"with open(train_label_path, 'r', encoding='utf-8') as f: train_lines = [l.strip() for l in f if l.strip()]
assert len(train_lines) == 140000, f"❌ LỖI: Số mẫu Train Chặng __STAGE__ ({len(train_lines)}) không đúng 140,000!"print(f"✅ Đã kiểm tra {len(train_lines):,} mẫu Train Chặng __STAGE__ (Khớp đúng 2,187 steps/epoch).")""" add_code(phase4_template.replace("__PREV_STAGE__", str(prev_stage)).replace("__STAGE__", str(stage)))
# Phase 5: Dictionary & Preflight Checks add_md("## Phase 5: Xác Minh Từ Điển Động NFC & Kiểm Tra Preflight Toàn Bộ Nhãn") add_code("""%cd /kaggle/workingimport osimport unicodedataimport json
dict_path = "/kaggle/working/data/cham_dict_v25.txt"assert os.path.exists(dict_path), f"❌ Không tìm thấy từ điển {dict_path}!"
with open(dict_path, 'r', encoding='utf-8') as f: tokens = [line.rstrip('\\r\\n') for line in f if line.rstrip('\\r\\n')]
token_set = set(tokens)print(f"📖 Từ điển V25 hiện hữu: {len(tokens)} tokens.")assert len(tokens) == 162, f"❌ LỖI: Từ điển V25 bắt buộc phải có đúng 162 tokens chuẩn NFC, phát hiện {len(tokens)}!"
# Quét kiểm định toàn diện trên cả Train và Valunknown_chars = set()invalid_unicode_chars = set()over_len_count = 0total_checked = 0
label_files = [ "/kaggle/working/data/cham_synthetic_v25/train_label.txt", "/kaggle/working/data/cham_synthetic_v25/val_label.txt"]
for lf in label_files: if not os.path.exists(lf): continue with open(lf, 'r', encoding='utf-8') as f: for line in f: line = line.strip() if not line: continue total_checked += 1 parts = line.split('\\t', 1) text = unicodedata.normalize('NFC', parts[1] if len(parts) > 1 else parts[0]) if len(text) > 80: over_len_count += 1 for c in text: if unicodedata.category(c) in ('Cs',): invalid_unicode_chars.add(c) elif c != ' ' and c not in token_set: unknown_chars.add(c)
print("=" * 65)print(f"📋 PREFLIGHT SANITY AUDIT ({total_checked:,} DÒNG NHÃN):")print(f" • Unknown Chars : {len(unknown_chars)} {list(unknown_chars)[:10] if unknown_chars else ''}")print(f" • Invalid Unicode : {len(invalid_unicode_chars)}")print(f" • Over max-len (>80) : {over_len_count}")print("=" * 65)
assert len(unknown_chars) == 0, f"❌ LỖI PREFLIGHT: Có {len(unknown_chars)} ký tự lạ: {unknown_chars}"assert len(invalid_unicode_chars) == 0, "❌ LỖI PREFLIGHT: Có ký tự Unicode không hợp lệ!"assert over_len_count == 0, f"❌ LỖI PREFLIGHT: Có {over_len_count} dòng nhãn vượt quá 80 ký tự!"print("🎉 PREFLIGHT VALIDATION: 100% PASS! Toàn bộ nhãn khớp chính xác 162 tokens.")""")
# Phase 6: Weight Surgery / Resume Checkpoint Verification if stage == 1: add_md("## Phase 6: Phẫu Thuật Trọng Số Kế Thừa V24 -> V25 (Khởi Điểm Chặng 1)") add_code("""%cd /kaggle/working
# 1. Định vị trọng số V24 trong thư mục giải nén hoặc datasetsrc_model_param = Nonecandidates = [ "/kaggle/working/data/v24_extracted/best_checkpoint/best_accuracy", "/kaggle/input/cham-ocr-v24-checkpoint/best_checkpoint/best_accuracy", "/kaggle/working/data/v24_extracted/best_accuracy", "/kaggle/input/cham-ocr-v24-checkpoint/best_accuracy", "/kaggle/working/data/v24_extracted/output/rec_cham_v24/best_accuracy", "/kaggle/working/data/v24_extracted/iter_epoch_200"]for c in candidates: if os.path.exists(c + '.pdparams') or os.path.exists(c): src_model_param = c break
if not src_model_param: for search_dir in ['/kaggle/working/data/v24_extracted', '/kaggle/input/cham-ocr-v24-checkpoint']: if os.path.exists(search_dir): for root, dirs, files in os.walk(search_dir): for f in files: if f.endswith('.pdparams'): src_model_param = os.path.join(root, f[:-9] if f.endswith('.pdparams') else f) break if src_model_param: break
# 2. Định vị từ điển V24v24_dict_path = Nonev24_dict_cands = [ "/kaggle/working/data/v24_extracted/cham_dict_v24.txt", "/kaggle/input/cham-ocr-v24-checkpoint/cham_dict_v24.txt", "/kaggle/working/data/v24_extracted/cham_dict.txt"]for c in v24_dict_cands: if os.path.exists(c): v24_dict_path = c break
if not v24_dict_path: for search_dir in ['/kaggle/working/data/v24_extracted', '/kaggle/input/cham-ocr-v24-checkpoint']: if os.path.exists(search_dir): for root, dirs, files in os.walk(search_dir): for f in files: if f.endswith('.txt') and 'dict' in f.lower(): v24_dict_path = os.path.join(root, f) break if v24_dict_path: break
print(f"🔬 Trọng số gốc V24 : {src_model_param}")print(f"📖 Từ điển gốc V24 : {v24_dict_path}")assert src_model_param, "❌ Không tìm thấy trọng số V24 để phẫu thuật!"
# 3. Tiến hành phẫu thuật ma trận FC!python3 scripts/surgery_v25_weights.py \\ --src_model "{src_model_param}" \\ --dst_model /kaggle/working/output/rec_cham_v25_init/init_weights.pdparams \\ --v24_dict "{v24_dict_path if v24_dict_path else '/kaggle/working/data/cham_dict_v25.txt'}" \\ --v25_dict /kaggle/working/data/cham_dict_v25.txt
init_weights_file = "/kaggle/working/output/rec_cham_v25_init/init_weights.pdparams"assert os.path.exists(init_weights_file), f"❌ Không tìm thấy {init_weights_file} sau phẫu thuật!"assert os.path.getsize(init_weights_file) > 5000000, "❌ File init_weights quá nhỏ!"print(f"🎉 Khởi tạo trọng số V25 thành công ({os.path.getsize(init_weights_file)/(1024*1024):.2f} MB). Sẵn sàng cho Chặng 1!")""") else: prev_stage = stage - 1 expected_prev_epoch = prev_epochs expected_prev_step = prev_epochs * 2187 add_md(f"## Phase 6: Trích Xuất & Xác Minh Trạng Thái Checkpoint Resume (Chặng {prev_stage} -> {stage})") phase6_template = """import osimport sysimport shutilimport zipfileimport pickle
%cd /kaggle/working
print("🔍 Đang nạp checkpoint từ Chặng __PREV_STAGE__...")target_ckpt_dir = "/kaggle/working/output/rec_cham_v25"os.makedirs(target_ckpt_dir, exist_ok=True)resume_ckpt = "/kaggle/working/output/rec_cham_v25/latest"
# 1. Kiểm tra xem checkpoint đã giải nén sẵn trong Kaggle Dataset khôngckpt_dir_candidates = [ "/kaggle/input/cham-ocr-v25-stage1-checkpoint/output/rec_cham_v25", "/kaggle/input/cham-ocr-v25-stage1-checkpoint", "/kaggle/input/datasets/gustavnguyen/cham-ocr-v25-stage1-checkpoint/output/rec_cham_v25", "/kaggle/input/datasets/gustavnguyen/cham-ocr-v25-stage1-checkpoint", "/kaggle/input/cham-ocr-v25-stage__PREV_STAGE__-checkpoint/output/rec_cham_v25", "/kaggle/input/cham-ocr-v25-stage__PREV_STAGE__-checkpoint", "/kaggle/input/datasets/gustavnguyen/cham-ocr-v25-stage__PREV_STAGE__-checkpoint/output/rec_cham_v25", "/kaggle/input/datasets/gustavnguyen/cham-ocr-v25-stage__PREV_STAGE__-checkpoint"]
for cand_dir in ckpt_dir_candidates: if os.path.exists(os.path.join(cand_dir, "latest.pdparams")): print(f"📦 Tìm thấy checkpoint đã giải nén tại: {cand_dir}") for item in os.listdir(cand_dir): s = os.path.join(cand_dir, item) d = os.path.join(target_ckpt_dir, item) if not os.path.isdir(s) and not os.path.exists(d): shutil.copy2(s, d) break
# 2. Nếu chưa có, tìm tệp zip checkpointif not os.path.exists(resume_ckpt + ".pdparams"): ckpt_zip_candidates = [ "/kaggle/input/cham-ocr-v25-stage1-checkpoint/rec_cham_v25_stage1_checkpoint.zip", "/kaggle/input/datasets/gustavnguyen/cham-ocr-v25-stage1-checkpoint/rec_cham_v25_stage1_checkpoint.zip", "/kaggle/input/datasets/gustavnguyen/cham-ocr-v25-stage__PREV_STAGE__-checkpoint/rec_cham_v25_stage__PREV_STAGE___checkpoint.zip", "/kaggle/input/paddleocr-cham-v25-stage__PREV_STAGE__/rec_cham_v25_stage__PREV_STAGE___checkpoint.zip", "/kaggle/input/paddleocr-cham-v25-stage__PREV_STAGE__/paddleocr_cham_v25_stage__PREV_STAGE___checkpoint.zip", "/kaggle/working/rec_cham_v25_stage__PREV_STAGE___checkpoint.zip", "/kaggle/working/rec_cham_v25_stage1_checkpoint.zip" ] ckpt_zip_path = None for cand in ckpt_zip_candidates: if os.path.exists(cand): ckpt_zip_path = cand break
if not ckpt_zip_path and os.path.exists('/kaggle/input'): print("🔍 Đang tìm kiếm checkpoint zip trong /kaggle/input...") for root, dirs, files in os.walk('/kaggle/input'): if any(f.endswith('.zip') and 'checkpoint' in f.lower() for f in files): for f in files: if f.endswith('.zip') and 'checkpoint' in f.lower(): ckpt_zip_path = os.path.join(root, f) break if ckpt_zip_path: break elif '_output_.zip' in files: try: oz_p = os.path.join(root, '_output_.zip') with zipfile.ZipFile(oz_p, 'r') as oz: for name in oz.namelist(): if 'checkpoint' in name.lower() and name.endswith('.zip'): oz.extract(name, '/kaggle/working') ckpt_zip_path = os.path.join('/kaggle/working', name) break except Exception as e: print(f"⚠️ Lỗi đọc {root}/_output_.zip: {e}") if ckpt_zip_path: break
if ckpt_zip_path and os.path.exists(ckpt_zip_path): print(f"📦 Đang giải nén checkpoint: {ckpt_zip_path}...") with zipfile.ZipFile(ckpt_zip_path, 'r') as zf: zf.extractall('/kaggle/working')
assert os.path.exists(resume_ckpt + ".pdparams"), f"❌ LỖI: Không tìm thấy {resume_ckpt}.pdparams!"assert os.path.exists(resume_ckpt + ".pdopt"), f"❌ LỖI: Không tìm thấy {resume_ckpt}.pdopt!"assert os.path.exists(resume_ckpt + ".states"), f"❌ LỖI: Không tìm thấy {resume_ckpt}.states!"
# 2. Đọc và xác minh trạng thái stateswith open(resume_ckpt + ".states", "rb") as f: st = pickle.load(f)
saved_epoch = st.get('epoch', 'N/A')saved_step = st.get('global_step', 'N/A')best_d = st.get('best_model_dict', {})
print("=" * 65)print("🎯 XÁC MINH TRẠNG THÁI CHECKPOINT RESUME (STAGE __STAGE__):")print(f" • Epoch đã hoàn thành : {saved_epoch} (kỳ vọng: __EXPECTED_PREV_EPOCH__)")print(f" • Global step hiện tại: {saved_step} (kỳ vọng: __EXPECTED_PREV_STEP__)")print(f" • Best Accuracy : {best_d.get('acc', 'N/A'):.4%}")print(f" • Best Edit Distance : {best_d.get('norm_edit_dis', 'N/A'):.4%}")print(f" • Best Epoch : {best_d.get('best_epoch', 'N/A')}")print("=" * 65)
assert saved_epoch == __EXPECTED_PREV_EPOCH__, f"❌ LỖI: Epoch đã lưu ({saved_epoch}) không khớp kỳ vọng __EXPECTED_PREV_EPOCH__!"assert saved_step in [__EXPECTED_PREV_STEP__, 24057, __EXPECTED_PREV_EPOCH__ * 2187], f"❌ LỖI: Global step ({saved_step}) không khớp kỳ vọng (__EXPECTED_PREV_STEP__ hoặc 24057)!"print(f"🚀 XÁC MINH HOÀN TOÀN HỢP LỆ! Sẵn sàng tiếp tục huấn luyện Epoch {saved_epoch + 1} -> __STAGE_END_EPOCH__!")""" add_code(phase6_template .replace("__PREV_STAGE__", str(prev_stage)) .replace("__STAGE__", str(stage)) .replace("__EXPECTED_PREV_EPOCH__", str(expected_prev_epoch)) .replace("__EXPECTED_PREV_STEP__", str(expected_prev_step)) .replace("__STAGE_END_EPOCH__", str(stage_end_epoch)))
# Phase 7: Distributed Training add_md(f"## Phase 7: Huấn Luyện Phân Tán Song Song Trên Dual GPU Tesla T4x2 (Epochs {prev_epochs + 1} -> {stage_end_epoch})") if stage == 1: train_args = f"""-c {{config_path}} \\ -o Global.epoch_num={global_total_epochs} \\ Global.stage_end_epoch={stage_end_epoch} \\ Global.save_epoch_step=1 \\ Global.eval_batch_step=[0,1000] \\ Global.pretrained_model={{init_weights}}""" else: train_args = f"""-c {{config_path}} \\ -o Global.epoch_num={global_total_epochs} \\ Global.stage_end_epoch={stage_end_epoch} \\ Global.save_epoch_step=1 \\ Global.eval_batch_step=[0,1000] \\ Global.checkpoints={{resume_ckpt}}"""
phase7_template = """import osimport paddle
gpu_count = paddle.device.cuda.device_count()print(f"🔥 Khởi chạy huấn luyện phân tán V25 Chặng __STAGE__ với {gpu_count} GPU...")
os.environ["PYTHONUNBUFFERED"] = "1"os.environ["FLAGS_allocator_strategy"] = "auto_growth"os.environ["FLAGS_fraction_of_gpu_memory_to_use"] = "0.80"os.environ["PYTHONPATH"] = f"/kaggle/working:/kaggle/working/PaddleOCR:{os.environ.get('PYTHONPATH', '')}"
%cd /kaggle/working/PaddleOCR
init_weights = "/kaggle/working/output/rec_cham_v25_init/init_weights"resume_ckpt = "/kaggle/working/output/rec_cham_v25/latest"config_path = "/kaggle/working/configs/rec_cham_v25.yml"
print("=" * 75)print("🚀 LỆNH THỰC THI HUẤN LUYỆN CHÍNH THỨC:")print(" paddle.distributed.launch --gpus '0,1' tools/train.py")print(" -o Global.epoch_num=__GLOBAL_TOTAL_EPOCHS__ Global.stage_end_epoch=__STAGE_END_EPOCH__")print("=" * 75)
if gpu_count > 1: print("🚀 Sử dụng lệnh phân tán song song đa GPU (paddle.distributed.launch --gpus '0,1'):") !FLAGS_allocator_strategy=auto_growth FLAGS_fraction_of_gpu_memory_to_use=0.80 python3 -m paddle.distributed.launch --gpus '0,1' tools/train.py \\ __TRAIN_ARGS__else: print("⚡ Huấn luyện trên Single GPU:") !FLAGS_allocator_strategy=auto_growth FLAGS_fraction_of_gpu_memory_to_use=0.80 python3 tools/train.py \\ __TRAIN_ARGS__
# Kiểm tra xem checkpoint có được tạo thành công khôngckpt_dir = "/kaggle/working/output/rec_cham_v25"assert os.path.exists(os.path.join(ckpt_dir, "latest.pdparams")), "❌ LỖI: latest.pdparams không tồn tại sau khi huấn luyện!"assert os.path.exists(os.path.join(ckpt_dir, "latest.pdopt")), "❌ LỖI: latest.pdopt không tồn tại sau khi huấn luyện!"assert os.path.exists(os.path.join(ckpt_dir, "latest.states")), "❌ LỖI: latest.states không tồn tại sau khi huấn luyện!"print(f"🎉 HOÀN THÀNH HUẤN LUYỆN CHẶNG __STAGE__! Checkpoint đầy đủ đã được lưu tại {ckpt_dir}.")""" add_code(phase7_template .replace("__STAGE__", str(stage)) .replace("__GLOBAL_TOTAL_EPOCHS__", str(global_total_epochs)) .replace("__STAGE_END_EPOCH__", str(stage_end_epoch)) .replace("__TRAIN_ARGS__", train_args))
# Phase 8: Archive Checkpoint & Export if stage == 1: val_freeze_archive_code = """val_freeze_zip = "/kaggle/working/cham_v25_val_freeze.zip"print(f"🔒 Đang đóng gói Validation Đóng Băng vào {val_freeze_zip}...")with zipfile.ZipFile(val_freeze_zip, 'w', zipfile.ZIP_DEFLATED) as vz: val_dir = "/kaggle/working/data/cham_synthetic_v25" # Thêm val_images val_img_dir = os.path.join(val_dir, "val_images") if os.path.exists(val_img_dir): for root, dirs, files in os.walk(val_img_dir): for f in files: full_p = os.path.join(root, f) rel_p = os.path.relpath(full_p, val_dir) vz.write(full_p, rel_p) # Thêm val_label và freeze manifest for extra_f in ["val_label.txt", "val_freeze_manifest.json"]: ep = os.path.join(val_dir, extra_f) if os.path.exists(ep): vz.write(ep, extra_f) # Thêm từ điển chuẩn if os.path.exists('/kaggle/working/data/cham_dict_v25.txt'): vz.write('/kaggle/working/data/cham_dict_v25.txt', 'cham_dict_v25.txt')
print(f"✅ Đã tạo Archive Val Đóng Băng: {os.path.getsize(val_freeze_zip)/(1024*1024):.2f} MB")""" elif stage == 2: val_freeze_archive_code = """# Chuyển tiếp cham_v25_val_freeze.zip để Chặng 3 sử dụng trực tiếpval_freeze_zip = "/kaggle/working/cham_v25_val_freeze.zip"if not os.path.exists(val_freeze_zip): freeze_cands = [ "/kaggle/input/paddleocr-cham-v25-stage1/cham_v25_val_freeze.zip", "/kaggle/input/cham-ocr-v25-stage1-checkpoint/cham_v25_val_freeze.zip" ] for fc in freeze_cands: if os.path.exists(fc): shutil.copy2(fc, val_freeze_zip) print(f"📋 Đã sao chép chuyển tiếp Validation freeze sang: {val_freeze_zip}") break
if not os.path.exists(val_freeze_zip) and os.path.exists("/kaggle/working/data/cham_synthetic_v25/val_label.txt"): print(f"🔒 Đang đóng gói Validation Đóng Băng vào {val_freeze_zip}...") with zipfile.ZipFile(val_freeze_zip, 'w', zipfile.ZIP_DEFLATED) as vz: val_dir = "/kaggle/working/data/cham_synthetic_v25" val_img_dir = os.path.join(val_dir, "val_images") if os.path.exists(val_img_dir): for root, dirs, files in os.walk(val_img_dir): for f in files: full_p = os.path.join(root, f) rel_p = os.path.relpath(full_p, val_dir) vz.write(full_p, rel_p) for extra_f in ["val_label.txt", "val_freeze_manifest.json", "cham_dict_v25.txt"]: ep = os.path.join(val_dir, extra_f) if os.path.exists(ep): vz.write(ep, extra_f) print(f"✅ Đã tạo chuyển tiếp Val freeze archive: {os.path.getsize(val_freeze_zip)/(1024*1024):.2f} MB")""" else: val_freeze_archive_code = ""
add_md(f"## Phase 8: Đóng Gói Checkpoint Chặng {stage} & Dữ Liệu Đóng Băng") phase8_template = """import osimport shutilimport zipfile
%cd /kaggle/working
latest_ckpt = "/kaggle/working/output/rec_cham_v25/latest"best_ckpt = "/kaggle/working/output/rec_cham_v25/best_accuracy"target_ckpt = best_ckpt if os.path.exists(best_ckpt + ".pdparams") else latest_ckpt
print(f"🎯 Checkpoint chính : {target_ckpt}")assert os.path.exists(latest_ckpt + ".pdparams"), "❌ LỖI: Thiếu latest.pdparams!"
zip_path = "/kaggle/working/rec_cham_v25_stage__STAGE___checkpoint.zip"print(f"📦 Đang nén toàn bộ checkpoint Chặng __STAGE__ vào {zip_path}...")
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf: for root, dirs, files in os.walk("/kaggle/working/output/rec_cham_v25"): for f in files: full_p = os.path.join(root, f) rel_p = os.path.relpath(full_p, "/kaggle/working") zipf.write(full_p, rel_p) if os.path.exists('/kaggle/working/data/cham_dict_v25.txt'): zipf.write('/kaggle/working/data/cham_dict_v25.txt', 'cham_dict_v25.txt')
print(f"🎉 HOÀN TẤT ĐÓNG GÓI CHECKPOINT CHẶNG __STAGE__!")print(f" • File Checkpoint : {zip_path} ({os.path.getsize(zip_path)/(1024*1024):.2f} MB)")
__VAL_FREEZE_ARCHIVE_CODE__""" add_code(phase8_template .replace("__STAGE__", str(stage)) .replace("__VAL_FREEZE_ARCHIVE_CODE__", val_freeze_archive_code))
notebook_dict = { "cells": cells, "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.10.12" } }, "nbformat": 4, "nbformat_minor": 4 } return notebook_dict
def main(): parser = argparse.ArgumentParser(description="Prepare and Push Cham OCR V25 Training to Kaggle") parser.add_argument("--stage", type=int, default=1, help="Giai đoạn huấn luyện: 1, 2, hoặc 3 (mặc định: 1)") parser.add_argument("--epochs", type=int, default=None, help="Số epochs cho chặng này") parser.add_argument("--prev-epochs", type=int, default=None, help="Số epochs đã hoàn thành ở chặng trước") parser.add_argument("--push", action="store_true", default=False, help="Tự động đẩy lên Kaggle và chạy") parser.add_argument("--no-push", dest="push", action="store_false", help="Chỉ tạo file không push") args = parser.parse_args()
# Chuẩn hóa cấu hình phân chặng theo 5 invariants if args.stage == 1: if args.epochs is None: args.epochs = 12 if args.prev_epochs is None: args.prev_epochs = 0 elif args.stage == 2: if args.epochs is None: args.epochs = 11 if args.prev_epochs is None: args.prev_epochs = 11 elif args.stage == 3: if args.epochs is None: args.epochs = 18 if args.prev_epochs is None: args.prev_epochs = 22 else: raise ValueError(f"Stage {args.stage} không hợp lệ! Chỉ hỗ trợ stage 1, 2, 3.")
stage_end = args.prev_epochs + args.epochs
print("=" * 80) print("🚀 MASTER KAGGLE DISPATCHER - CHAM-OCR V25 MULTI-STAGE TRAINING") print(f" • Chặng huấn luyện : Chặng {args.stage}") print(f" • Số Epochs chặng : {args.epochs} epochs (từ Epoch {args.prev_epochs + 1} đến {stage_end})") print(f" • Global.epoch_num : 40 epochs (T_max = 87,480 steps khóa cứng)") print(f" • Global.stage_end : {stage_end} (hook dừng an toàn)") print(f" • Dự kiến thời gian : ~{args.epochs * 0.58:.1f} giờ máy (an toàn trong giới hạn 12h)") print(f" • Bộ tăng tốc : NvidiaTeslaT4 (Dual GPU T4x2)") print(f" • Tài khoản Kaggle : gustavnguyen") print("=" * 80)
submission_dir = os.path.join(TRAINING_DIR, "output", f"kaggle_v25_stage{args.stage}_submission") os.makedirs(submission_dir, exist_ok=True)
kernel_slug = f"paddleocr-cham-v25-stage{args.stage}" nb_name = f"paddleocr_cham_v25_stage{args.stage}.ipynb" nb_path = os.path.join(submission_dir, nb_name)
nb_dict = build_v25_notebook(stage=args.stage, epoch_num=args.epochs, prev_epochs=args.prev_epochs) with open(nb_path, 'w', encoding='utf-8') as f: json.dump(nb_dict, f, indent=1, ensure_ascii=False) print(f"✅ Đã tạo thành công Notebook tại: {nb_path}")
meta_path = os.path.join(submission_dir, 'kernel-metadata.json') meta = { "id": f"gustavnguyen/{kernel_slug}", "title": f"paddleocr-cham-v25-stage{args.stage}", "code_file": nb_name, "language": "python", "kernel_type": "notebook", "is_private": "true", "enable_gpu": "true", "enable_tpu": "false", "enable_internet": "true", "machine_shape": "NvidiaTeslaT4", "accelerator": "NvidiaTeslaT4", "dataset_sources": [ "gustavnguyen/cham-ocr-v24-checkpoint", "gustavnguyen/cham-ocr-v5-assets" ] if args.stage == 1 else [ "gustavnguyen/cham-ocr-v5-assets", f"gustavnguyen/cham-ocr-v25-stage{args.stage - 1}-checkpoint" ], "kernel_sources": [] if args.stage == 1 else [ f"gustavnguyen/paddleocr-cham-v25-stage{args.stage - 1}" ], "competition_sources": [], "model_sources": [] } with open(meta_path, 'w', encoding='utf-8') as f: json.dump(meta, f, indent=2) print(f"✅ Đã tạo kernel-metadata tại: {meta_path}")
if args.push: api = get_authenticated_api() if not api: print("❌ Lỗi: Không thể xác thực với Kaggle API.") return 1 print(f"\n🚀 Đang đẩy Kernel '{meta['id']}' lên Kaggle với cấu hình NvidiaTeslaT4 (Dual T4x2)...") # Monkeypatch builtins.open để ép UTF-8 trên Windows khi Kaggle client đọc notebook chứa ký tự Chăm import builtins _orig_open = builtins.open def _safe_open(*a, **kw): mode = a[1] if len(a) > 1 else kw.get('mode', 'r') if 'b' not in mode and 'encoding' not in kw: kw['encoding'] = 'utf-8' return _orig_open(*a, **kw) builtins.open = _safe_open try: api.kernels_push(submission_dir, acc="NvidiaTeslaT4") finally: builtins.open = _orig_open print(f"🎉 ĐÃ KHỞI CHẠY THÀNH CÔNG TÁC VỤ HUẤN LUYỆN V25 CHẶNG {args.stage} TRÊN KAGGLE DUAL T4x2!") print(f"👉 Đường dẫn Kernel: https://www.kaggle.com/code/{meta['id']}") # Giám sát trạng thái khởi động ban đầu print("\n⏳ Đang kiểm tra trạng thái khởi tạo kernel...") time.sleep(5) status = api.kernels_status(meta['id']) print(f"📡 Trạng thái hiện tại: {status}") else: print("\n💡 Ghi chú: Chế độ --no-push đang bật. Chưa đẩy kernel lên Kaggle.")
return 0
if __name__ == '__main__': sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252#!/usr/bin/env python3# -*- coding: utf-8 -*-"""Cloud Benchmark Runner for Cham-OCR.Runs benchmark orchestrator on Lightning Cloud (A100, L4, L40S) with:- Detached execution (nohup) resilient to network disconnects- Real-time log streaming- Automatic result download- Guaranteed auto-shutdown in finally: studio.stop() (Zero Credit Leakage)."""
import osimport sysimport timeimport jsonimport base64import argparsefrom lightning_sdk import Studio, Machine
if sys.stdout and hasattr(sys.stdout, 'reconfigure'): try: sys.stdout.reconfigure(encoding='utf-8') except Exception: passif sys.stderr and hasattr(sys.stderr, 'reconfigure'): try: sys.stderr.reconfigure(encoding='utf-8') except Exception: pass
MACHINE_CONFIGS = { "A100": { "studio_name": "cham-ocr-v25-a100", "machine": Machine.A100, "cost_per_hour": 2.19, "gpu_display": "NVIDIA A100 (40GB SXM4)", }, "L4": { "studio_name": "cham-det-h100", "machine": Machine.L4, "cost_per_hour": 0.79, "gpu_display": "NVIDIA L4 (24GB)", }, "L40S": { "studio_name": "cham-det-h100", "machine": Machine.L40S, "cost_per_hour": 2.14, "gpu_display": "NVIDIA L40S (48GB)", }}
def log(msg): timestamp = time.strftime("%H:%M:%S") print(f"[{timestamp}] {msg}", flush=True)
def push_file(studio, local_path, remote_path): log(f"📦 Đẩy file: {os.path.basename(local_path)} -> {remote_path}") with open(local_path, "rb") as f: content = f.read()
b64_str = base64.b64encode(content).decode("ascii") chunk_size = 64 * 1024 chunks = [b64_str[i:i + chunk_size] for i in range(0, len(b64_str), chunk_size)]
studio.run(f"python3 -c \"import pathlib; p = pathlib.Path('{remote_path}'); p.parent.mkdir(parents=True, exist_ok=True); p.write_text('')\"") for chunk in chunks: cmd = f"python3 -c \"import pathlib; p = pathlib.Path('{remote_path}'); open('{remote_path}.b64', 'a').write('{chunk}')\"" studio.run(cmd)
decode_cmd = f"python3 -c \"import base64, pathlib; data = base64.b64decode(pathlib.Path('{remote_path}.b64').read_text()); pathlib.Path('{remote_path}').write_bytes(data); pathlib.Path('{remote_path}.b64').unlink()\"" studio.run(decode_cmd)
def pull_file(studio, remote_path, local_path): log(f"📥 Tải file: {remote_path} -> {local_path}") os.makedirs(os.path.dirname(os.path.abspath(local_path)), exist_ok=True) res = studio.run(f"test -f '{remote_path}' && base64 '{remote_path}' || echo 'NOT_FOUND'").strip() if not res or res == "NOT_FOUND": log(f"⚠️ Remote file {remote_path} không tồn tại!") return False
b64_data = "".join(res.split()) data = base64.b64decode(b64_data) with open(local_path, "wb") as f: f.write(data) log(f" ✅ Đã tải thành công ({len(data):,} bytes)") return True
def setup_studio_environment(studio, remote_base): log("🔧 Kiểm tra môi trường thực thi trên Studio...") check_py_gpu = studio.run("test -x /teamspace/studios/this_studio/py_gpu && echo 'EXISTS' || echo 'MISSING'").strip() if "MISSING" in check_py_gpu: log("⚙️ Tạo launcher py_gpu cho Studio...") script = """ cat << 'EOF' > /teamspace/studios/this_studio/py_gpu#!/usr/bin/env bashif [ -d /teamspace/studios/this_studio/py310/lib/python3.10/site-packages/nvidia ]; then SITE_PKG=/teamspace/studios/this_studio/py310/lib/python3.10/site-packages NVIDIA_PATHS=$(find $SITE_PKG/nvidia -name "lib" -type d 2>/dev/null | tr '\n' ':' | sed 's/:$//') export LD_LIBRARY_PATH=$NVIDIA_PATHS:$LD_LIBRARY_PATH exec /teamspace/studios/this_studio/py310/bin/python "$@"else exec python3 "$@"fiEOF chmod +x /teamspace/studios/this_studio/py_gpu """ studio.run(script) studio.run("pip install -q psutil pyyaml tqdm") log("✅ Môi trường Python GPU đã sẵn sàng!")
def run_benchmark_on_target(target_name, warmup_steps=100, measure_steps=300): if target_name not in MACHINE_CONFIGS: raise ValueError(f"Target '{target_name}' không hợp lệ. Chọn một trong: {list(MACHINE_CONFIGS.keys())}")
cfg = MACHINE_CONFIGS[target_name] log("=" * 75) log(f"🚀 BẮT ĐẦU BENCHMARK TRÊN {cfg['gpu_display']} (${cfg['cost_per_hour']}/h)") log(f"Studio: {cfg['studio_name']} | Machine: {cfg['machine'].name}") log("=" * 75)
studio = Studio(cfg["studio_name"], teamspace="phucsd", org="phucsd-org") studio.show_progress = False
try: while str(studio.status).lower() in ["stopping", "transitioning"]: log(f"Studio đang ở trạng thái '{studio.status}', đợi 5 giây...") time.sleep(5)
target_machine = cfg["machine"] if str(studio.status).lower() != "running": log(f"Khởi động Studio trên {target_machine.name}...") studio.start(machine=target_machine) elif studio.machine != target_machine: log(f"Studio đang chạy trên {studio.machine.name}, chuyển sang {target_machine.name}...") studio.switch_machine(target_machine)
log(f"✅ Studio đã chạy! Trạng thái: {studio.status} | Machine: {studio.machine}")
remote_base = "/teamspace/studios/this_studio/Cham-OCR/ocr-training" setup_studio_environment(studio, remote_base)
repo_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) local_worker = os.path.join(repo_root, "ocr-training", "scripts", "benchmark_worker.py") local_orch = os.path.join(repo_root, "ocr-training", "scripts", "benchmark_orchestrator.py") local_yml = os.path.join(repo_root, "ocr-training", "configs", "rec_cham_v25_lightning.yml")
# Sync code push_file(studio, local_worker, f"{remote_base}/scripts/benchmark_worker.py") push_file(studio, local_orch, f"{remote_base}/scripts/benchmark_orchestrator.py") push_file(studio, local_yml, f"{remote_base}/configs/rec_cham_v25_lightning.yml")
# Ensure dataset is present data_check = studio.run(f"test -f {remote_base}/data/cham_synthetic_v25/train_label.txt && echo 'EXISTS' || echo 'MISSING'").strip() if "MISSING" in data_check: log("📦 Dữ liệu chưa có trên Studio, đang giải nén từ /teamspace/lightning_storage/v25_shared_data/ocr_training.tar...") studio.run(f"mkdir -p /teamspace/studios/this_studio/Cham-OCR && cd /teamspace/studios/this_studio/Cham-OCR && tar -xf /teamspace/lightning_storage/v25_shared_data/ocr_training.tar") log("✅ Đã giải nén xong dữ liệu huấn luyện!")
# Ensure PaddleOCR repo is present pocr_check = studio.run(f"test -d {remote_base}/PaddleOCR && echo 'EXISTS' || echo 'MISSING'").strip() if "MISSING" in pocr_check: log("📦 Clone PaddleOCR repository...") studio.run(f"cd {remote_base} && git clone -b release/2.7 https://github.com/PaddlePaddle/PaddleOCR.git") log("✅ Đã clone PaddleOCR repository!")
# Launch detached benchmark process log("🔥 Khởi chạy benchmark ngầm (nohup) với giám sát thời gian thực...") studio.run(f"pkill -f 'benchmark_orchestrator.py' 2>/dev/null || true") studio.run(f"pkill -f 'benchmark_worker.py' 2>/dev/null || true") studio.run(f"rm -f {remote_base}/benchmark_running.pid {remote_base}/benchmark_done.flag")
launch_cmd = f""" cat << 'EOF' > {remote_base}/run_bench.sh#!/usr/bin/env bashcd {remote_base}/teamspace/studios/this_studio/py_gpu scripts/benchmark_orchestrator.py \\ -c configs/rec_cham_v25_lightning.yml \\ --gpu_name "{target_name}" \\ --cost_per_hour {cfg['cost_per_hour']} \\ --python_bin /teamspace/studios/this_studio/py_gpu \\ --warmup_steps {warmup_steps} \\ --measure_steps {measure_steps} \\ -o benchmark_results > {remote_base}/benchmark.log 2>&1echo \\$? > {remote_base}/benchmark_done.flagEOF chmod +x {remote_base}/run_bench.sh nohup {remote_base}/run_bench.sh >/dev/null 2>&1 & echo \\$! > {remote_base}/benchmark_running.pid """ studio.run(launch_cmd) log("✅ Tiến trình benchmark đã khởi chạy thành công!")
# Monitoring loop seen_lines = 0 poll_interval = 15 start_time = time.time() max_benchmark_time = 45 * 60 # 45 minutes safety timeout
while time.time() - start_time < max_benchmark_time: time.sleep(poll_interval) # Check done flag done_check = studio.run(f"test -f {remote_base}/benchmark_done.flag && cat {remote_base}/benchmark_done.flag || echo 'RUNNING'").strip() # Stream recent logs log_tail = studio.run(f"tail -n 15 {remote_base}/benchmark.log 2>/dev/null || true").strip() if log_tail: log(f"--- [Log Update ({int(time.time() - start_time)}s elapsed)] ---\n{log_tail}")
if done_check != "RUNNING": exit_code = int(done_check) if done_check.isdigit() else -1 log(f"🏁 Benchmark đã hoàn thành với exit code: {exit_code}") break
# Pull results local_results_dir = os.path.join(repo_root, "ocr-training", "benchmark_results") os.makedirs(local_results_dir, exist_ok=True)
pull_file(studio, f"{remote_base}/benchmark_results/benchmark_{target_name}.json", os.path.join(local_results_dir, f"benchmark_{target_name}.json")) pull_file(studio, f"{remote_base}/benchmark_results/benchmark_{target_name}.md", os.path.join(local_results_dir, f"benchmark_{target_name}.md")) pull_file(studio, f"{remote_base}/benchmark.log", os.path.join(local_results_dir, f"benchmark_{target_name}.log"))
log(f"🎉 Hoàn thành benchmark cho {target_name}!")
finally: log("🛑 [BẢO TOÀN CREDIT] Đang chuyển Studio sang STOPPED...") try: studio.stop() log("✅ Studio đã STOPPED thành công! Zero rò rỉ credit.") except Exception as e: log(f"Lỗi khi dừng studio: {e}")
def main(): parser = argparse.ArgumentParser(description="Multi-GPU Benchmark Runner on Lightning Cloud") parser.add_argument("--target", type=str, default="A100", choices=["A100", "L4", "L40S", "ALL"], help="Target GPU machine") parser.add_argument("--warmup_steps", type=int, default=100, help="Warmup steps per trial") parser.add_argument("--measure_steps", type=int, default=300, help="Measure steps per trial") args = parser.parse_args()
targets = ["A100", "L4", "L40S"] if args.target == "ALL" else [args.target] for t in targets: run_benchmark_on_target(t, warmup_steps=args.warmup_steps, measure_steps=args.measure_steps)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177#!/usr/bin/env python3# -*- coding: utf-8 -*-"""Điều phối tự động bài Benchmark Cham-OCR Recognition V24 trên Kaggle Dual GPU Tesla T4x2:1. Đóng gói Kaggle Notebook2. Đẩy lên Kaggle với bộ tăng tốc bắt buộc NvidiaTeslaT4 (T4x2 phân tán)3. Giám sát thời gian thực luồng log SSE và trạng thái Kernel4. Tự động tải file benchmark_t4_results.zip và hiển thị bảng kết quả phân tích."""
import osimport sysimport timeimport jsonimport zipfileimport socketimport threadingimport subprocess
if sys.stdout and hasattr(sys.stdout, 'reconfigure'): sys.stdout.reconfigure(encoding='utf-8')
# Thiết lập timeout cho socketsocket.setdefaulttimeout(60)
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))if SCRIPT_DIR not in sys.path: sys.path.insert(0, SCRIPT_DIR)
from kaggle_auth import init_kaggle_authinit_kaggle_auth()
from kaggle.api.kaggle_api_extended import KaggleApi
KERNEL_USER = "gustavnguyen"KERNEL_SLUG = "cham-ocr-t4-benchmark"KERNEL_ID = f"{KERNEL_USER}/{KERNEL_SLUG}"SUBMISSION_DIR = os.path.abspath("ocr-training/output/kaggle_benchmark_submission")OUTPUT_DIR = os.path.abspath("ocr-training/benchmark_results/kaggle_t4")
def get_api(): api = KaggleApi() api.authenticate() return api
def stream_logs_worker(api, kernel_id, log_file_path, stop_event): """Lắng nghe luồng SSE log trực tiếp từ Kaggle và in các sự kiện quan trọng""" while not stop_event.is_set(): try: with open(log_file_path, 'a', encoding='utf-8') as f_log: for event in api.kernels_logs_stream(kernel_id): if stop_event.is_set(): break data = event.get('data', '') if data: f_log.write(data) f_log.flush() for line in data.splitlines(): line_str = line.strip() if any(k in line_str for k in [ '🔥 BẮT ĐẦU:', 'HOÀN THÀNH:', 'THẤT BẠI', 'Steady Step', 'BẢNG TỔNG KẾT', 'CẤU HÌNH TỐI ƯU NHẤT', 'Detected GPU Count', 'Place(gpu', 'Hoàn thành sinh dữ liệu', 'OOM', 'Exception', 'Error', 'Max Steady-State', 'Thời gian hoàn thành' ]) or ('|' in line_str and any(t in line_str for t in ['T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'T8', 'Trial Name', 'Thí nghiệm'])): print(f"⚡ [KAGGLE T4x2] {line_str}", flush=True) except Exception: pass if not stop_event.is_set(): time.sleep(3)
def main(): skip_push = "--monitor-only" in sys.argv or "--skip-push" in sys.argv print("="*80) print("🚀 ĐIỀU PHỐI BENCHMARK DUAL GPU TESLA T4x2 TRÊN KAGGLE") print(f"🎯 Kernel Target: {KERNEL_ID}") print(f"⚙️ Accelerator: NvidiaTeslaT4 (Dual GPU T4x2)") print("="*80) api = get_api() print("✅ Xác thực thành công tài khoản:", os.environ["KAGGLE_USERNAME"])
if not skip_push: # 1. Sinh notebook mới nhất print("\n📦 Bước 1: Chuẩn bị Kaggle Benchmark Notebook...") import prepare_benchmark_notebook prepare_benchmark_notebook.main() # 2. Đẩy Kernel lên Kaggle print("\n📤 Bước 2: Đẩy Notebook lên Kaggle với cờ --accelerator NvidiaTeslaT4...") push_cmd = f"kaggle kernels push -p \"{SUBMISSION_DIR}\" --accelerator NvidiaTeslaT4" env = os.environ.copy() env["PYTHONUTF8"] = "1" res = subprocess.run(push_cmd, shell=True, capture_output=True, text=True, encoding='utf-8', errors='replace', env=env) if res.returncode != 0: print(f"❌ Lỗi khi đẩy kernel: {res.stderr}") sys.exit(1) print("✅ Đã đẩy kernel thành công!") print(res.stdout.strip()) else: print("ℹ️ Chế độ Monitor-Only: Bỏ qua bước sinh notebook và push, kết nối trực tiếp vào Kernel đang chạy.") # 3. Giám sát & Stream Live Log print("\n📡 Bước 3: Giám sát Kernel & Lắng nghe luồng SSE Live Log...") os.makedirs(OUTPUT_DIR, exist_ok=True) live_log = os.path.join(OUTPUT_DIR, "live_benchmark.log") if os.path.exists(live_log): os.remove(live_log) stop_event = threading.Event() stream_t = threading.Thread(target=stream_logs_worker, args=(api, KERNEL_ID, live_log, stop_event), daemon=True) stream_t.start() start_time = time.time() last_status = None while True: try: status_obj = api.kernels_status(KERNEL_ID) status = getattr(status_obj, 'status', None) if hasattr(status, 'name'): status_name = status.name.lower() elif isinstance(status, str): status_name = status.lower() else: status_name = str(status).lower() elapsed = int(time.time() - start_time) if status_name != last_status: print(f"⏱️ [{elapsed//60}m {elapsed%60}s] Trạng thái Kernel: {status_name.upper()}", flush=True) last_status = status_name if status_name in ['complete']: print("\n🎉 Kernel đã hoàn thành toàn bộ quá trình chạy!") break elif status_name in ['error', 'cancel', 'aborted']: print(f"\n❌ Kernel kết thúc bất thường với trạng thái: {status_name.upper()}") stop_event.set() sys.exit(1) except Exception as e: print(f"⚠️ Cảnh báo kiểm tra trạng thái: {e}") time.sleep(15) stop_event.set() # 5. Tải file kết quả ZIP print("\n📥 Bước 5: Tải tệp kết quả benchmark_t4_results.zip về máy cục bộ...") time.sleep(5) try: api.kernels_output(KERNEL_ID, path=OUTPUT_DIR) print("✅ Tải kết quả hoàn tất!") # Giải nén kết quả zip_files = [f for f in os.listdir(OUTPUT_DIR) if f.endswith('.zip')] for z in zip_files: z_path = os.path.join(OUTPUT_DIR, z) print(f"📦 Đang giải nén: {z}...") with zipfile.ZipFile(z_path, 'r') as zipf: zipf.extractall(OUTPUT_DIR) print("✅ Giải nén xong!") # Hiển thị tóm tắt nếu có summary_md = os.path.join(OUTPUT_DIR, "benchmark_t4_summary.md") if os.path.exists(summary_md): print("\n" + "="*80) print("📄 KẾT QUẢ BÁO CÁO BENCHMARK T4x2:") print("="*80) with open(summary_md, "r", encoding="utf-8") as f: print(f.read()) except Exception as e: print(f"❌ Lỗi khi tải hoặc đọc kết quả: {e}")
if __name__ == '__main__': main()37 unmodified lines3839404142434437 unmodified linessetup_cmds = [# 1. Clone or Pull Cham-OCR"if [ ! -d 'Cham-OCR' ]; then git clone https://github.com/phucsd1/Cham-OCR.git; else cd Cham-OCR && git pull origin main && cd ..; fi",# 2. Clone PaddleOCR inside Cham-OCR/ocr-training if not exists"cd /teamspace/studios/this_studio/Cham-OCR/ocr-training && if [ ! -d 'PaddleOCR' ]; then git clone -b release/2.7 https://github.com/PaddlePaddle/PaddleOCR.git; fi",# 3. Download fonts37 unmodified lines3839404142434437 unmodified linessetup_cmds = [# 1. Clone or Pull Cham-OCR"if [ ! -d 'Cham-OCR' ]; then git clone https://github.com/phucsd/Cham-OCR.git; else cd Cham-OCR && git pull origin main && cd ..; fi",# 2. Clone PaddleOCR inside Cham-OCR/ocr-training if not exists"cd /teamspace/studios/this_studio/Cham-OCR/ocr-training && if [ ! -d 'PaddleOCR' ]; then git clone -b release/2.7 https://github.com/PaddlePaddle/PaddleOCR.git; fi",# 3. Download fonts
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234#!/usr/bin/env python3# -*- coding: utf-8 -*-"""Kịch bản Phẫu Thuật Trọng Số V24 -> V25 (Character-Mapped Weight Surgery):1. Nạp checkpoint V24 (pdparams)2. Đọc từ điển cham_dict_v24.txt và cham_dict_v25.txt3. Tạo bảng ánh xạ Ký Tự (Character Mapping): char -> old_idx, char -> new_idx4. Mở rộng kích thước ma trận cho toàn bộ các layer phụ thuộc vocabulary: - CTCHead: * ctc_head.fc.weight [hidden_dim, num_classes] * ctc_head.fc.bias [num_classes] - NRTRHead: * nrtr_head.item_embedding.weight [num_classes, hidden_dim] * nrtr_head.fc.weight [hidden_dim, num_classes] * nrtr_head.fc.bias [num_classes]5. Kế thừa 100% trọng số của ký tự cũ theo Ký tự (không map mù theo index).6. Khởi tạo ký tự mới (tiếng Việt, ký hiệu) bằng phân phối Gauss nhỏ N(0, 0.02) để bảo toàn không gian đặc trưng cũ.7. Lưu checkpoint sẵn sàng cho V25 huấn luyện kế thừa."""
import osimport sysimport numpy as nptry: import paddle PADDLE_AVAILABLE = Trueexcept ImportError: PADDLE_AVAILABLE = False
if sys.stdout and hasattr(sys.stdout, 'reconfigure'): sys.stdout.reconfigure(encoding='utf-8')
# Monkeypatch NumPy 2.x nếu cầnif not hasattr(np, 'sctypes'): np.sctypes = {'int': [np.int8, np.int16, np.int32, np.int64], 'uint': [np.uint8, np.uint16, np.uint32, np.uint64], 'float': [np.float16, np.float32, np.float64], 'complex': [np.complex64, np.complex128], 'others': [bool, object, bytes, str]}if not hasattr(np, 'bool'): np.bool = boolif not hasattr(np, 'int'): np.int = intif not hasattr(np, 'float'): np.float = float
def load_dict(path): tokens = [] with open(path, 'r', encoding='utf-8') as f: for line in f: t = line.rstrip('\r\n') if t: tokens.append(t) return tokens
def perform_weight_surgery(v24_model_path, v24_dict_path, v25_dict_path, output_model_path): print("=" * 80) print("🔬 BẮT ĐẦU PHẪU THUẬT TRỌNG SỐ (WEIGHT SURGERY) V24 -> V25") print(f" • Checkpoint nguồn V24: {v24_model_path}") print(f" • Từ điển V24: {v24_dict_path}") print(f" • Từ điển V25: {v25_dict_path}") print(f" • Checkpoint xuất V25: {output_model_path}") print("=" * 80)
# 1. Nạp từ điển v24_chars = load_dict(v24_dict_path) v25_chars = load_dict(v25_dict_path) print(f"✅ V24 Tokens: {len(v24_chars)}") print(f"✅ V25 Tokens: {len(v25_chars)}") # PaddleOCR quy ước số class: # Với CTC: num_classes = len(dict) + 1 (blank token tại index 0) # Với NRTR: num_classes = len(dict) + 4 (các token đặc biệt: blank, unk, bos, eos) old_char2idx = {c: i for i, c in enumerate(v24_chars)} new_char2idx = {c: i for i, c in enumerate(v25_chars)}
if not PADDLE_AVAILABLE: raise RuntimeError("❌ Cần môi trường có thư viện 'paddlepaddle' (ví dụ trên Kaggle/Linux/GPU) để nạp và lưu tệp trọng số .pdparams.")
# 2. Nạp weights V24 if v24_model_path.endswith('.pdparams'): v24_weights = paddle.load(v24_model_path) else: # Đường dẫn thư mục hoặc prefix param_file = v24_model_path + '.pdparams' if not v24_model_path.endswith('.pdparams') else v24_model_path if os.path.exists(param_file): v24_weights = paddle.load(param_file) else: raise FileNotFoundError(f"Không tìm thấy checkpoint tại: {v24_model_path}")
v25_weights = {} surgered_layers = []
for k, v in v24_weights.items(): val = v.numpy() if hasattr(v, 'numpy') else v # A. Xử lý CTC Head FC: Shape [hidden_dim, num_classes] hoặc [num_classes] cho bias if "ctc_head.fc.weight" in k: hidden_dim, old_classes = val.shape # Số class = len(dict) + 1 (blank ở vị trí 0) offset = old_classes - len(v24_chars) new_classes = len(v25_chars) + offset print(f"🛠️ Phẫu thuật {k}: [{hidden_dim}, {old_classes}] -> [{hidden_dim}, {new_classes}]") # Khởi tạo ma trận mới với phân phối ngẫu nhiên nhỏ N(0, 0.02) new_val = np.random.normal(0.0, 0.02, size=(hidden_dim, new_classes)).astype(val.dtype) # Copy blank token (thường ở index 0) for b in range(offset): new_val[:, b] = val[:, b] # Copy trọng số theo từng ký tự chính xác (character mapping) mapped_count = 0 for c, old_i in old_char2idx.items(): if c in new_char2idx: new_i = new_char2idx[c] new_val[:, new_i + offset] = val[:, old_i + offset] mapped_count += 1 print(f" -> Đã sao chép chính xác {mapped_count} vectors trọng số ký tự Chăm cũ.") v25_weights[k] = paddle.to_tensor(new_val) surgered_layers.append(k)
elif "ctc_head.fc.bias" in k: old_classes = val.shape[0] offset = old_classes - len(v24_chars) new_classes = len(v25_chars) + offset print(f"🛠️ Phẫu thuật {k}: [{old_classes}] -> [{new_classes}]") new_val = np.zeros(shape=(new_classes,), dtype=val.dtype) for b in range(offset): new_val[b] = val[b] for c, old_i in old_char2idx.items(): if c in new_char2idx: new_i = new_char2idx[c] new_val[new_i + offset] = val[old_i + offset] v25_weights[k] = paddle.to_tensor(new_val) surgered_layers.append(k)
# B. Xử lý NRTR Head Item Embedding: Shape [num_classes, hidden_dim] elif "nrtr_head.item_embedding.weight" in k: old_classes, hidden_dim = val.shape offset = old_classes - len(v24_chars) new_classes = len(v25_chars) + offset print(f"🛠️ Phẫu thuật {k}: [{old_classes}, {hidden_dim}] -> [{new_classes}, {hidden_dim}]") new_val = np.random.normal(0.0, 0.02, size=(new_classes, hidden_dim)).astype(val.dtype) for b in range(offset): new_val[b, :] = val[b, :] for c, old_i in old_char2idx.items(): if c in new_char2idx: new_i = new_char2idx[c] new_val[new_i + offset, :] = val[old_i + offset, :] v25_weights[k] = paddle.to_tensor(new_val) surgered_layers.append(k)
# C. Xử lý NRTR Head FC: Shape [hidden_dim, num_classes] hoặc [num_classes] elif "nrtr_head.fc.weight" in k: hidden_dim, old_classes = val.shape offset = old_classes - len(v24_chars) new_classes = len(v25_chars) + offset print(f"🛠️ Phẫu thuật {k}: [{hidden_dim}, {old_classes}] -> [{hidden_dim}, {new_classes}]") new_val = np.random.normal(0.0, 0.02, size=(hidden_dim, new_classes)).astype(val.dtype) for b in range(offset): new_val[:, b] = val[:, b] for c, old_i in old_char2idx.items(): if c in new_char2idx: new_i = new_char2idx[c] new_val[:, new_i + offset] = val[:, old_i + offset] v25_weights[k] = paddle.to_tensor(new_val) surgered_layers.append(k)
elif "nrtr_head.fc.bias" in k: old_classes = val.shape[0] offset = old_classes - len(v24_chars) new_classes = len(v25_chars) + offset print(f"🛠️ Phẫu thuật {k}: [{old_classes}] -> [{new_classes}]") new_val = np.zeros(shape=(new_classes,), dtype=val.dtype) for b in range(offset): new_val[b] = val[b] for c, old_i in old_char2idx.items(): if c in new_char2idx: new_i = new_char2idx[c] new_val[new_i + offset] = val[old_i + offset] v25_weights[k] = paddle.to_tensor(new_val) surgered_layers.append(k)
# D. Tất cả các layer Backbone / SVTR Transformer không phụ thuộc vocab: Giữ nguyên 100% else: v25_weights[k] = v
# 3. Lưu checkpoint đã phẫu thuật os.makedirs(os.path.dirname(os.path.abspath(output_model_path)), exist_ok=True) save_target = output_model_path if output_model_path.endswith('.pdparams') else output_model_path + '.pdparams' paddle.save(v25_weights, save_target) print("\n" + "=" * 80) print("🎉 HOÀN TẤT PHẪU THUẬT TRỌNG SỐ THÀNH CÔNG!") print(f" • Tổng số layer trong mô hình: {len(v25_weights)}") print(f" • Các layer đã được phẫu thuật ánh xạ ký tự: {len(surgered_layers)}") for l in surgered_layers: print(f" - {l}") print(f" • Checkpoint phẫu thuật V25 đã lưu tại: {save_target}") print("=" * 80) return save_target
if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description="Character-Mapped Weight Surgery V24 -> V25") parser.add_argument("--src_model", type=str, default=None, help="Đường dẫn file trọng số V24 (.pdparams)") parser.add_argument("--dst_model", type=str, default="/kaggle/working/output/rec_cham_v25_init/init_weights.pdparams", help="Đường dẫn lưu trọng số V25") parser.add_argument("--v24_dict", type=str, default="/kaggle/working/data/cham_dict_v24.txt", help="Đường dẫn từ điển V24") parser.add_argument("--v25_dict", type=str, default="/kaggle/working/data/cham_dict_v25.txt", help="Đường dẫn từ điển V25") args = parser.parse_args()
# Tự động tìm kiếm checkpoint V24 nếu không chỉ định rõ src_model = args.src_model if not src_model: candidates = [ "/kaggle/working/data/v24_checkpoint/best_accuracy", "/kaggle/working/output/rec_cham_v24_best/best_checkpoint/best_accuracy", "/kaggle/input/paddleocr-cham-finetune/rec_cham_v24_best/best_checkpoint/best_accuracy", "ocr-training/output/v24/extracted_v24/best_checkpoint/best_accuracy", "ocr-training/data/output_v24_temp/rec_cham_best_model/iter_epoch_200" ] for c in candidates: if os.path.exists(c + '.pdparams') or os.path.exists(c): src_model = c break
if src_model and (os.path.exists(src_model + '.pdparams') or os.path.exists(src_model)): perform_weight_surgery(src_model, args.v24_dict, args.v25_dict, args.dst_model) else: print(f"ℹ️ Không tìm thấy checkpoint V24 tại '{src_model}'. Kịch bản sẵn sàng khi có đường dẫn cụ thể.")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778import osimport sysimport jsonimport time
sys.stdout.reconfigure(encoding='utf-8', errors='replace')sys.stderr.reconfigure(encoding='utf-8', errors='replace')sys.path.insert(0, os.path.dirname(__file__))import kaggle_authkaggle_auth.init_kaggle_auth()from kaggle.api.kaggle_api_extended import KaggleApi
def main(): work_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "output", "test_mount")) os.makedirs(work_dir, exist_ok=True) nb = { 'cells': [{ 'cell_type': 'code', 'execution_count': None, 'metadata': {}, 'outputs': [], 'source': [ "import os\n", "print('=== ROOT /kaggle/input ===')\n", "if os.path.exists('/kaggle/input'):\n", " print('Direct children:', os.listdir('/kaggle/input'))\n", " for root, dirs, files in os.walk('/kaggle/input'):\n", " print('DIR:', root, '| FILES:', files[:10])\n", "else:\n", " print('/kaggle/input does not exist!')\n" ] }], 'metadata': {'kernelspec': {'display_name': 'Python 3', 'language': 'python', 'name': 'python3'}}, 'nbformat': 4, 'nbformat_minor': 4 } with open(os.path.join(work_dir, 'test_mount.ipynb'), 'w', encoding='utf-8') as f: json.dump(nb, f) meta = { 'id': 'gustavnguyen/test-stage1-mount', 'title': 'test-stage1-mount', 'code_file': 'test_mount.ipynb', 'language': 'python', 'kernel_type': 'notebook', 'is_private': 'true', 'enable_gpu': 'false', 'enable_internet': 'true', 'dataset_sources': ['gustavnguyen/cham-ocr-v5-assets'], 'kernel_sources': ['gustavnguyen/paddleocr-cham-v25-stage1'] } with open(os.path.join(work_dir, 'kernel-metadata.json'), 'w', encoding='utf-8') as f: json.dump(meta, f) api = KaggleApi() api.authenticate() print("🚀 Đang đẩy CPU kernel thăm dò lên Kaggle...") api.kernels_push(work_dir) print("✅ Đã đẩy kernel! Đang chờ thực thi và lấy log...") for _ in range(30): time.sleep(5) st = api.kernels_status('gustavnguyen/test-stage1-mount') status = st.get('status') print(f"📡 Trạng thái: {status}") if status in ('COMPLETE', 'ERROR'): logs = api.kernels_logs('gustavnguyen/test-stage1-mount') print("=" * 60) print("📋 LOGS TỪ CPU TEST KERNEL:") print(logs) print("=" * 60) break
if __name__ == '__main__': main()12345678910111213141516171819202122232425262728293031323334353637383940import osimport sysimport time
sys.stdout.reconfigure(encoding='utf-8', errors='replace')sys.stderr.reconfigure(encoding='utf-8', errors='replace')
sys.path.insert(0, os.path.dirname(__file__))import kaggle_authkaggle_auth.init_kaggle_auth()from kaggle.api.kaggle_api_extended import KaggleApi
def main(): ds_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "output", "v25_stage1_dataset")) print(f"📦 Thư mục Dataset: {ds_dir}") print(f"📋 Các tệp bên trong:") total_size = 0 for f in os.listdir(ds_dir): fp = os.path.join(ds_dir, f) sz = os.path.getsize(fp) total_size += sz print(f" • {f} ({sz/(1024*1024):.2f} MB)") print(f"📊 Tổng dung lượng cần tải: {total_size/(1024*1024):.2f} MB")
api = KaggleApi() api.authenticate()
print("\n🚀 Bắt đầu tạo mới Dataset trên Kaggle: gustavnguyen/cham-ocr-v25-stage1-checkpoint...") t0 = time.time() try: res = api.dataset_create_new(ds_dir, public=False, quiet=False, convert_to_csv=False, dir_mode='skip') print(f"🎉 Tải lên hoàn tất trong {(time.time() - t0)/60:.2f} phút!") print("Phản hồi từ Kaggle:", res) except Exception as e: print(f"❌ Lỗi khi tải lên Dataset: {e}") return 1 return 0
if __name__ == '__main__': sys.exit(main())12345678910111213141516171819202122232425262728293031323334353637383940import osimport sysimport time
sys.stdout.reconfigure(encoding='utf-8', errors='replace')sys.stderr.reconfigure(encoding='utf-8', errors='replace')
sys.path.insert(0, os.path.dirname(__file__))import kaggle_authkaggle_auth.init_kaggle_auth()from kaggle.api.kaggle_api_extended import KaggleApi
def main(): ds_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "output", "v25_stage2_dataset")) print(f"📦 Thư mục Dataset Stage 2: {ds_dir}") print(f"📋 Các tệp bên trong:") total_size = 0 for f in os.listdir(ds_dir): fp = os.path.join(ds_dir, f) sz = os.path.getsize(fp) total_size += sz print(f" • {f} ({sz/(1024*1024):.2f} MB)") print(f"📊 Tổng dung lượng cần tải: {total_size/(1024*1024):.2f} MB")
api = KaggleApi() api.authenticate()
print("\n🚀 Bắt đầu tạo mới Dataset trên Kaggle: gustavnguyen/cham-ocr-v25-stage2-checkpoint...") t0 = time.time() try: res = api.dataset_create_new(ds_dir, public=False, quiet=False, convert_to_csv=False, dir_mode='skip') print(f"🎉 Tải lên hoàn tất trong {(time.time() - t0)/60:.2f} phút!") print("Phản hồi từ Kaggle:", res) except Exception as e: print(f"❌ Lỗi khi tải lên Dataset: {e}") return 1 return 0
if __name__ == '__main__': sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147#!/usr/bin/env python3# -*- coding: utf-8 -*-"""Kịch bản tự động thăm dò Kaggle GPU Quota và tự động kích hoạt huấn luyện Cham-OCR V25 Chặng 1.Chạy ngầm để đảm bảo:1. Thăm dò liên tục qua GetAcceleratorQuotaStatistics API.2. Kiểm tra chặt chẽ: chỉ khởi chạy khi Kaggle đã thực sự RESET quota 30 giờ mới (timeUsed < 3600s, remaining >= 28h).3. Tự động dispatch prepare_v25_kaggle.py --stage 1 và theo dõi tiến trình real-time."""
import osimport sysimport timeimport jsonimport socketimport datetimeimport requestsimport re
if sys.stdout and hasattr(sys.stdout, 'reconfigure'): sys.stdout.reconfigure(encoding='utf-8')
socket.setdefaulttimeout(30)
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))sys.path.insert(0, SCRIPT_DIR)
from kaggle_auth import init_kaggle_authfrom kaggle_ops import get_authenticated_api
LOG_FILE = os.path.join(os.path.dirname(SCRIPT_DIR), "v25_quota_watchdog.log")
def log(msg): now_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") line = f"[{now_str}] {msg}" print(line, flush=True) try: with open(LOG_FILE, "a", encoding="utf-8") as f: f.write(line + "\n") except Exception: pass
def check_gpu_quota(): """Truy vấn chính xác số liệu GPU Quota từ Kaggle API.""" user, key = init_kaggle_auth() url = "https://api.kaggle.com/v1/kernels.KernelsApiService/GetAcceleratorQuotaStatistics" try: res = requests.post(url, auth=(user, key), json={}, timeout=15) if res.status_code != 200: log(f"⚠️ Lỗi HTTP {res.status_code} khi gọi GetAcceleratorQuotaStatistics") return None
data = res.json() gpu = data.get("gpuQuota", {}) used_str = gpu.get("timeUsed", "0s") allowed_str = gpu.get("totalTimeAllowed", "108000s") refresh_time = data.get("quotaRefreshTime", "")
used = float(re.sub(r"[^\d.]", "", used_str)) allowed = float(re.sub(r"[^\d.]", "", allowed_str)) remaining = allowed - used
return { "used_sec": used, "allowed_sec": allowed, "remaining_sec": remaining, "used_hours": used / 3600.0, "remaining_hours": remaining / 3600.0, "refresh_time": refresh_time } except Exception as e: log(f"⚠️ Ngoại lệ khi kiểm tra quota: {e}") return None
def main(): log("=" * 70) log("🚀 KHỞI ĐỘNG V25 KAGGLE QUOTA WATCHDOG & AUTO-DISPATCHER") log(" • Mục tiêu: Theo dõi đến khi Kaggle nạp 30h GPU mới -> Tự động chạy V25 Stage 2") log(f" • Tệp nhật ký: {LOG_FILE}") log("=" * 70)
# 1. Kiểm tra trạng thái ban đầu quota = check_gpu_quota() if quota: log(f"📊 Trạng thái hiện tại: Đã dùng {quota['used_hours']:.2f}h / {quota['allowed_sec']/3600:.1f}h | Còn lại: {quota['remaining_hours']:.2f}h | Reset: {quota['refresh_time']}") else: log("⚠️ Không lấy được thông tin quota ban đầu, sẽ thử lại trong vòng lặp.")
# 2. Vòng lặp chờ reset poll_count = 0 while True: poll_count += 1 quota = check_gpu_quota()
if quota: # Điều kiện xác nhận đã reset: còn lại >= 28 giờ HOẶC đã dùng < 1 giờ is_reset = (quota["remaining_hours"] >= 28.0) or (quota["used_hours"] < 1.0) if is_reset: log("🎉🎉🎉 XÁC NHẬN: KAGGLE ĐÃ RESET GPU QUOTA THÀNH CÔNG! 🎉🎉🎉") log(f" • Hạn ngạch mới: {quota['remaining_hours']:.2f} giờ khả dụng (đã dùng: {quota['used_hours']:.2f}h)") break else: log(f"⏳ [Lần {poll_count}] Quota chưa reset (còn {quota['remaining_hours']:.2f}h). Đang chờ mốc reset lúc 07:00 sáng mai (00:00 UTC).") else: log(f"⚠️ [Lần {poll_count}] Không kết nối được Kaggle API, sẽ thử lại.")
now_dt = datetime.datetime.now() target_time = datetime.datetime(2026, 9, 12, 7, 0, 0) time_diff_sec = (target_time - now_dt).total_seconds()
if time_diff_sec > 1800: sleep_time = 900 # 15 phút elif time_diff_sec > 0: sleep_time = 120 # 2 phút else: sleep_time = 60 # 1 phút khi đã qua 07:00 mà đang đợi Kaggle cập nhật
time.sleep(sleep_time)
# 3. Kích hoạt huấn luyện V25 Stage 2 log("🚀 BẮT ĐẦU TỰ ĐỘNG DISPATCH V25 CHẶNG 2 LÊN KAGGLE DUAL GPU T4x2...") import subprocess cmd = [sys.executable, os.path.join(SCRIPT_DIR, "prepare_v25_kaggle.py"), "--stage", "2", "--push"] log(f" • Lệnh: {' '.join(cmd)}") proc = subprocess.Popen(cmd, cwd=os.path.dirname(SCRIPT_DIR), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding="utf-8")
for line in proc.stdout: log(f" | {line.strip()}")
proc.wait() if proc.returncode == 0: log("✅ DISPATCH V25 CHẶNG 2 THÀNH CÔNG!") # Khởi chạy monitor cho Stage 2 monitor_cmd = [sys.executable, os.path.join(SCRIPT_DIR, "monitor_v25_kernel.py"), "gustavnguyen/paddleocr-cham-v25-stage2", "60"] log(f"📡 Khởi chạy monitor Stage 2: {' '.join(monitor_cmd)}") subprocess.Popen(monitor_cmd, cwd=os.path.dirname(SCRIPT_DIR)) else: log(f"❌ DISPATCH THẤT BẠI với mã lỗi {proc.returncode}")
if __name__ == "__main__": main()13 unmodified lines141516171819202122232425262713 unmodified linessys.path.insert(0, PROJECT_ROOT)# Định nghĩa các tập ký tự tiếng ChămPRE_SIGNS = set('ꨰꨯꨴ')diacritics = set(chr(c) for c in range(0xAA29, 0xAA37)) | set(chr(c) for c in range(0xAA40, 0xAA4E))FINAL_SIGNS = set('ꩀꩃꩌꩍꩆꩉꩊꩂꩅ')MEDIAL_SIGNS = set('ꨳ')consonants = set("ꨆꨇꨈꨉꨊꨋꨌꨍꨎꨏꨐꨑꨒꨓꨔꨕꨖꨗꨘꨙꨚꨛꨜꨝꨞꨟꨠꨡꨢꨣꨤꨥꨦꨧꨨꨀꨁꨂꨃꨄꨅ")COMBINING_MARKS = PRE_SIGNS | diacritics | FINAL_SIGNS | MEDIAL_SIGNSHEAL_REGEX = re.compile(r'\s+([ꨰꨯꨴꨳꩀꩃꩌꩍꩆꩉꩊꩂꩅ\uAA29-\uAA36\uAA40-\uAA4D])')# Whitelist các dòng biểu đồ diacritic hoặc ký tự diacritic rời rạc được chấp nhận cho mục đích chẩn đoán/vocabularyWHITELIST_DIAGNOSTIC = {13 unmodified lines141516171819202122232425262713 unmodified linessys.path.insert(0, PROJECT_ROOT)# Định nghĩa các tập ký tự tiếng ChămPRE_SIGNS = set('ꨯꨰ')diacritics = set(chr(c) for c in range(0xAA29, 0xAA37)) | set(chr(c) for c in range(0xAA40, 0xAA4E))FINAL_SIGNS = set('ꩀꩃꩌꩍꩆꩉꩊꩂꩅ')MEDIAL_SIGNS = set('ꨴꨵꨳꨶ')consonants = set("ꨆꨇꨈꨉꨊꨋꨌꨍꨎꨏꨐꨑꨒꨓꨔꨕꨖꨗꨘꨙꨚꨛꨜꨝꨞꨟꨠꨡꨢꨣꨤꨥꨦꨧꨨꨀꨁꨂꨃꨄꨅ")COMBINING_MARKS = PRE_SIGNS | diacritics | FINAL_SIGNS | MEDIAL_SIGNSHEAL_REGEX = re.compile(r'\s+([ꨯꨰꨴꨵꨳꨶꩀꩃꩌꩍꩆꩉꩊꩂꩅ\uAA29-\uAA36\uAA40-\uAA4D])')# Whitelist các dòng biểu đồ diacritic hoặc ký tự diacritic rời rạc được chấp nhận cho mục đích chẩn đoán/vocabularyWHITELIST_DIAGNOSTIC = {
ocr-training/scripts/audit_v25_submissions.pyAdded+111
ocr-training/scripts/benchmark_orchestrator.pyAdded+512
ocr-training/scripts/benchmark_worker.pyAdded+351
ocr-training/scripts/build_dict_v25.pyAdded+234
ocr-training/scripts/dict_extension_v24.py+2
ocr-training/scripts/dict_extension_v25.pyAdded+73
ocr-training/scripts/download_v24_zip.py+2-2
ocr-training/scripts/download_v25_stage1.pyAdded+187
ocr-training/scripts/download_v25_stage2.pyAdded+211
ocr-training/scripts/download_v25_stage3.pyAdded+181
ocr-training/scripts/dry_run_v25_scheduler.pyAdded+155
ocr-training/scripts/eval_stage3_summary.pyAdded+47
ocr-training/scripts/eval_stages_summary.pyAdded+34
ocr-training/scripts/export_v25.pyAdded+58
ocr-training/scripts/generate_comparative_report.pyAdded+142
ocr-training/scripts/generate_data.py+76-24
ocr-training/scripts/generate_detector_data_v2.py+1-1
ocr-training/scripts/get_live_log.py+2-2
ocr-training/scripts/kaggle_auth.pyAdded+44
ocr-training/scripts/kaggle_ops.py+5-5
ocr-training/scripts/kaggle_train_det.py+4-5
ocr-training/scripts/kaggle_train_rec_v25.pyAdded+268
ocr-training/scripts/kaggle_watchdog_v24.py+3-2
ocr-training/scripts/kaggle_watchdog_v25.pyAdded+304
ocr-training/scripts/monitor_v25_kernel.pyAdded+141
ocr-training/scripts/orchestrate_v25_lightning.pyAdded+309
ocr-training/scripts/prepare_benchmark_notebook.pyAdded+644
ocr-training/scripts/prepare_v25_kaggle.pyAdded+1039
ocr-training/scripts/run_benchmark_cloud.pyAdded+252
ocr-training/scripts/run_kaggle_benchmark.pyAdded+177
ocr-training/scripts/run_lightning_remote.py+1-1
ocr-training/scripts/surgery_v25_weights.pyAdded+234
ocr-training/scripts/test_kernel_mount.pyAdded+78
ocr-training/scripts/upload_v25_stage1_dataset.pyAdded+40
ocr-training/scripts/upload_v25_stage2_dataset.pyAdded+40
ocr-training/scripts/v25_quota_watchdog_and_resume.pyAdded+147
ocr-training/scripts/validate_unicode_source_labels.py+3-3