#!/usr/bin/env python3 """ End-to-End Chunked Dataset Preparation + Training Pipeline This script orchestrates the complete workflow: 1. Plans and launches parallel chunk jobs 2. Waits for all chunks to complete 3. Launches merge job 4. Waits for merged dataset 5. Automatically launches training 6. Optionally publishes both LoRA and merged models separately Usage: # Full end-to-end with default settings uv run run_end_to_end_chunked.py \ --hf-username Tonic \ --base-repo android-text-full \ --model-repo l-operator-instruct \ --chunk-size 45 \ --test-ratio 0.07 # With custom training parameters uv run run_end_to_end_chunked.py \ --hf-username Tonic \ --base-repo android-text-full \ --model-repo l-operator-instruct \ --chunk-size 45 \ --max-mobile-actions 9600 \ --android-ratio 0.7 \ --test-ratio 0.07 \ --num-epochs 3 \ --flavor a10g-medium \ --timeout 12h # Publish both LoRA and merged models separately uv run run_end_to_end_chunked.py \ --hf-username Tonic \ --base-repo android-text-full \ --lora-repo l-operator-lora \ --merged-repo l-operator-merged \ --publish-both \ --chunk-size 45 \ --num-epochs 3 # Resume from existing chunks (skip to training) uv run run_end_to_end_chunked.py \ --hf-username Tonic \ --base-repo android-text-full \ --model-repo l-operator-instruct \ --skip-chunks \ --total-chunks 6 """ import argparse import logging import os import subprocess import sys import time from typing import List, Optional, Tuple logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s", ) logger = logging.getLogger(__name__) TOTAL_TRAIN_FILES = 275 def run_command(cmd: List[str], description: str, dry_run: bool = False, extra_env: Optional[dict] = None) -> Tuple[bool, str]: """Run a shell command and return success status and output.""" cmd_str = " ".join(cmd) logger.info(f"\n{'='*70}") logger.info(f"{description}") logger.info(f"{'='*70}") logger.info(f"Command: {cmd_str}") if dry_run: logger.info("[DRY RUN - Command not executed]") return True, "" env = os.environ.copy() env.setdefault("PYTHONIOENCODING", "utf-8") env.setdefault("PYTHONUTF8", "1") if extra_env: env.update(extra_env) try: result = subprocess.run( cmd, capture_output=True, text=True, check=True, env=env, encoding="utf-8", errors="replace", ) logger.info("Success!") return True, result.stdout except subprocess.CalledProcessError as e: logger.error(f"Command failed: {e}") logger.error(f"stderr: {e.stderr[-1000:]}") return False, e.stderr def calculate_chunks(chunk_size: int) -> List[Tuple[int, int, int]]: """Calculate chunk boundaries.""" chunks = [] for start in range(0, TOTAL_TRAIN_FILES, chunk_size): end = min(start + chunk_size, TOTAL_TRAIN_FILES) chunk_idx = start // chunk_size chunks.append((chunk_idx, start, end)) return chunks def launch_chunk_job( hf_username: str, base_repo: str, chunk_index: int, chunk_size: int, flavor: str, timeout: str, max_mobile_actions: Optional[int] = None, android_ratio: float = 0.5, dry_run: bool = False, ) -> bool: """Launch a single chunk processing job.""" # Use HF jobs with script args passed via SCRIPT_ARGS env var script_args = f"--hf-username {hf_username} --base-repo {base_repo} --chunk-index {chunk_index} --chunk-size {chunk_size} --upload" # Add mobile-actions only to chunk 0 if chunk_index == 0 and max_mobile_actions and max_mobile_actions > 0: script_args += f" --max-mobile-actions {max_mobile_actions} --android-ratio {android_ratio}" elif chunk_index == 0: script_args += " --skip-mobile-actions" cmd = [ "hf", "jobs", "uv", "run", "--flavor", flavor, "--secrets", "HF_TOKEN", "--timeout", timeout, "--env", f"SCRIPT_ARGS={script_args}", "--", "bash", "-c", f'python -c "import sys; sys.argv=[\"script.py\"] + \"$SCRIPT_ARGS\".split(); exec(open(\"train/prepare_chunked_dataset.py\").read())"', ] success, _ = run_command( cmd, f"Launch Chunk {chunk_index} (files {chunk_index * chunk_size}-{min((chunk_index + 1) * chunk_size, TOTAL_TRAIN_FILES) - 1})", dry_run, ) return success def launch_merge_job( hf_username: str, base_repo: str, final_repo: str, total_chunks: int, flavor: str, timeout: str, test_ratio: float, dry_run: bool = False, ) -> bool: """Launch the final merge job.""" script_args = f"--hf-username {hf_username} --base-repo {base_repo} --merge-chunks --total-chunks {total_chunks} --final-repo {final_repo} --test-ratio {test_ratio} --upload" cmd = [ "hf", "jobs", "uv", "run", "--flavor", flavor, "--secrets", "HF_TOKEN", "--timeout", timeout, "--env", f"SCRIPT_ARGS={script_args}", "--", "bash", "-c", f'python -c "import sys; sys.argv=[\"script.py\"] + \"$SCRIPT_ARGS\".split(); exec(open(\"train/prepare_chunked_dataset.py\").read())"', ] success, _ = run_command( cmd, f"Launch Final Merge ({total_chunks} chunks -> {final_repo})", dry_run, ) return success def launch_training_job( hf_username: str, dataset_repo: str, model_repo: str, flavor: str, timeout: str, num_epochs: int, eval_split: float, lora_r: int, merge_model: bool = False, dry_run: bool = False, ) -> bool: """Launch training job.""" cmd = [ "hf", "jobs", "uv", "run", "train/sft-lfm2.5.py", "--flavor", flavor, "--secrets", "HF_TOKEN", "--timeout", timeout, "--", "--dataset", f"{hf_username}/{dataset_repo}", "--output-repo", f"{hf_username}/{model_repo}", "--num-epochs", str(num_epochs), "--eval-split", str(eval_split), "--lora-r", str(lora_r), ] if merge_model: cmd.append("--merge-model") model_type = "Merged" if merge_model else "LoRA" success, _ = run_command( cmd, f"Launch Training ({dataset_repo} -> {model_repo}, {model_type})", dry_run, ) return success def launch_lora_extraction_job( hf_username: str, source_repo: str, target_repo: str, flavor: str, timeout: str, dry_run: bool = False, ) -> bool: """Launch a job to extract and copy LoRA adapter to separate repo.""" # Use an inline Python script via hf jobs python_code = ( "import os; import sys; " "from huggingface_hub import HfApi, snapshot_download, upload_folder; " "source = os.environ['SOURCE_REPO']; target = os.environ['TARGET_REPO']; token = os.environ['HF_TOKEN']; " "print(f'Extracting LoRA from {source} to {target}'); " "api = HfApi(token=token); " "local_path = '/tmp/lora_adapter'; os.makedirs(local_path, exist_ok=True); " "snapshot_download(repo_id=source, local_dir=local_path, allow_patterns=['adapter*', '*.json', 'README*'], token=token); " "api.create_repo(repo_id=target, repo_type='model', exist_ok=True, private=True); " "upload_folder(folder_path=local_path, repo_id=target, token=token); " "print(f'LoRA adapter copied to {target}')" ) cmd = [ "hf", "jobs", "uv", "run", "--flavor", flavor, "--secrets", "HF_TOKEN", "--timeout", timeout, "--", "python", "-c", python_code, ] # Set environment variables for the job extra_env = { "SOURCE_REPO": f"{hf_username}/{source_repo}", "TARGET_REPO": f"{hf_username}/{target_repo}", } success, _ = run_command( cmd, f"Extract LoRA ({source_repo} -> {target_repo})", dry_run, extra_env=extra_env, ) return success def check_dataset_exists(repo_id: str, token: str) -> bool: """Check if a dataset exists on HuggingFace Hub.""" try: from huggingface_hub import dataset_info dataset_info(repo_id, token=token) return True except Exception: return False def wait_for_datasets( repo_ids: List[str], token: str, max_wait_minutes: int, poll_interval: int = 30, ) -> bool: """Wait for multiple datasets to be available.""" logger.info(f"\n{'='*70}") logger.info(f"Waiting for {len(repo_ids)} datasets...") logger.info(f"Max wait: {max_wait_minutes} minutes") logger.info(f"{'='*70}") start_time = time.time() max_wait_seconds = max_wait_minutes * 60 pending = set(repo_ids) ready = set() while time.time() - start_time < max_wait_seconds: for repo in list(pending): if check_dataset_exists(repo, token): ready.add(repo) pending.remove(repo) logger.info(f" ✓ Ready: {repo}") if not pending: logger.info(f"\nAll {len(repo_ids)} datasets ready!") return True remaining = len(pending) elapsed = int(time.time() - start_time) logger.info(f" ... {remaining} pending ({elapsed}s elapsed)") time.sleep(poll_interval) logger.error(f"\nTimeout! {len(pending)} datasets not ready:") for repo in pending: logger.error(f" - {repo}") return False def parse_args() -> argparse.Namespace: """Parse command line arguments.""" parser = argparse.ArgumentParser( description="End-to-end chunked dataset + training pipeline", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: # Full end-to-end with defaults uv run run_end_to_end_chunked.py \\ --hf-username Tonic \\ --base-repo android-text-full \\ --model-repo l-operator-instruct \\ --chunk-size 45 \\ --test-ratio 0.07 # With custom training parameters uv run run_end_to_end_chunked.py \\ --hf-username Tonic \\ --base-repo android-text-full \\ --model-repo l-operator-instruct \\ --chunk-size 45 \\ --max-mobile-actions 9600 \\ --android-ratio 0.7 \\ --test-ratio 0.07 \\ --num-epochs 3 \\ --flavor a10g-medium \\ --timeout 12h # Publish both LoRA and merged models to separate repos uv run run_end_to_end_chunked.py \\ --hf-username Tonic \\ --base-repo android-text-full \\ --lora-repo l-operator-lora \\ --merged-repo l-operator-merged \\ --publish-both \\ --chunk-size 45 \\ --num-epochs 3 # Resume from existing chunks (skip chunk processing) uv run run_end_to_end_chunked.py \\ --hf-username Tonic \\ --base-repo android-text-full \\ --model-repo l-operator-instruct \\ --skip-chunks \\ --total-chunks 6 \\ --wait-for-merge # Skip to training only (dataset exists) uv run run_end_to_end_chunked.py \\ --hf-username Tonic \\ --base-repo android-text-full \\ --model-repo l-operator-instruct \\ --skip-chunks \\ --skip-merge \\ --dataset-repo Tonic/android-text-full # Training only with dual model publishing uv run run_end_to_end_chunked.py \\ --hf-username Tonic \\ --base-repo android-text-full \\ --lora-repo l-operator-lora \\ --merged-repo l-operator-merged \\ --publish-both \\ --skip-chunks \\ --skip-merge \\ --dataset-repo Tonic/android-text-full """, ) # Required parser.add_argument("--hf-username", required=True, help="HuggingFace username") parser.add_argument("--base-repo", required=True, help="Base repository name for chunks") parser.add_argument("--model-repo", required=True, help="Model repository name (used when not using --publish-both)") # Dual model publishing parser.add_argument("--lora-repo", default=None, help="LoRA adapter repository name (for --publish-both)") parser.add_argument("--merged-repo", default=None, help="Merged model repository name (for --publish-both)") parser.add_argument("--publish-both", action="store_true", help="Publish both LoRA and merged models to separate repos") # Chunk configuration parser.add_argument("--chunk-size", type=int, default=45, help="Files per chunk (default: 45)") parser.add_argument("--total-chunks", type=int, default=None, help="Total chunks (auto-calculate if not set)") # Data configuration parser.add_argument("--max-mobile-actions", type=int, default=9600, help="Mobile actions for chunk 0") parser.add_argument("--skip-mobile-actions", action="store_true", help="Exclude mobile-actions") parser.add_argument("--android-ratio", type=float, default=0.7, help="Android ratio") parser.add_argument("--test-ratio", type=float, default=0.0, help="Test split ratio") # Training configuration parser.add_argument("--num-epochs", type=int, default=1, help="Training epochs") parser.add_argument("--eval-split", type=float, default=0.2, help="Evaluation split") parser.add_argument("--lora-r", type=int, default=16, help="LoRA rank") parser.add_argument("--dataset-repo", default=None, help="Override final dataset repo (default: base-repo)") # HF Jobs configuration (using cheapest CPU flavors for dataset processing) parser.add_argument("--chunk-flavor", default="cpu-basic", help="Flavor for chunk jobs (default: cpu-basic)") parser.add_argument("--merge-flavor", default="cpu-basic", help="Flavor for merge job (default: cpu-basic)") parser.add_argument("--training-flavor", default="a10g-small", help="Flavor for training") parser.add_argument("--chunk-timeout", default="6h", help="Timeout for chunk jobs") parser.add_argument("--merge-timeout", default="2h", help="Timeout for merge job") parser.add_argument("--training-timeout", default="6h", help="Timeout for training") # Execution control parser.add_argument("--skip-chunks", action="store_true", help="Skip chunk processing (use existing)") parser.add_argument("--skip-merge", action="store_true", help="Skip merge (use existing dataset)") parser.add_argument("--skip-training", action="store_true", help="Skip training (dataset prep only)") parser.add_argument("--wait-for-chunks", action="store_true", default=True, help="Wait for chunks") parser.add_argument("--wait-for-merge", action="store_true", default=True, help="Wait for merge") parser.add_argument("--wait-timeout", type=int, default=90, help="Max wait minutes") parser.add_argument("--dry-run", action="store_true", help="Show commands without executing") parser.add_argument("--public", action="store_true", help="Make repos public") return parser.parse_args() def main(): """Main entry point.""" args = parse_args() # Get token token = os.environ.get("HF_TOKEN") or os.environ.get("hfjob") if not token: logger.error("HF_TOKEN environment variable not set!") sys.exit(1) # Calculate chunks if args.total_chunks: total_chunks = args.total_chunks else: chunks = calculate_chunks(args.chunk_size) total_chunks = len(chunks) final_dataset = args.dataset_repo or args.base_repo # Determine model repos if args.publish_both: if not args.lora_repo or not args.merged_repo: logger.error("--publish-both requires both --lora-repo and --merged-repo") sys.exit(1) lora_repo = args.lora_repo merged_repo = args.merged_repo model_display = f"LoRA: {lora_repo}, Merged: {merged_repo}" else: lora_repo = None merged_repo = args.model_repo model_display = merged_repo # Print configuration print("\n" + "=" * 70) print("END-TO-END CHUNKED PIPELINE") print("=" * 70) print(f"HF Username: {args.hf_username}") print(f"Base Repo: {args.base_repo}") print(f"Final Dataset: {final_dataset}") if args.publish_both: print(f"LoRA Repo: {lora_repo}") print(f"Merged Repo: {merged_repo}") else: print(f"Model Repo: {args.model_repo}") print(f"Chunks: {total_chunks} x ~{args.chunk_size} files") print(f"Mobile Actions: {'EXCLUDED' if args.skip_mobile_actions else args.max_mobile_actions}") print(f"Test Ratio: {args.test_ratio}") print(f"Training: {args.num_epochs} epochs, LoRA r={args.lora_r}") if args.publish_both: print(f"Output: Both LoRA and merged models will be published") print("=" * 70) if args.dry_run: print("\nDRY RUN MODE - Commands will be shown but not executed\n") # Phase 1: Process chunks if not args.skip_chunks: logger.info("\n" + "=" * 70) logger.info("PHASE 1: Processing Chunks") logger.info("=" * 70) max_mobile = 0 if args.skip_mobile_actions else args.max_mobile_actions # Launch all chunk jobs for idx in range(total_chunks): success = launch_chunk_job( hf_username=args.hf_username, base_repo=args.base_repo, chunk_index=idx, chunk_size=args.chunk_size, flavor=args.chunk_flavor, timeout=args.chunk_timeout, max_mobile_actions=max_mobile if idx == 0 else None, android_ratio=args.android_ratio, dry_run=args.dry_run, ) if not success and not args.dry_run: logger.error(f"Failed to launch chunk {idx}") # Wait for chunks if args.wait_for_chunks and not args.dry_run: chunk_repos = [f"{args.hf_username}/{args.base_repo}-chunk-{i}" for i in range(total_chunks)] chunks_ready = wait_for_datasets(chunk_repos, token, args.wait_timeout) if not chunks_ready: logger.error("Chunks failed. Cannot proceed.") sys.exit(1) elif args.dry_run: logger.info("[DRY RUN - Would wait for chunks]") else: logger.info("\nSkipping chunk processing (--skip-chunks)") # Phase 2: Merge chunks if not args.skip_merge: logger.info("\n" + "=" * 70) logger.info("PHASE 2: Merging Chunks") logger.info("=" * 70) success = launch_merge_job( hf_username=args.hf_username, base_repo=args.base_repo, final_repo=final_dataset, total_chunks=total_chunks, flavor=args.merge_flavor, timeout=args.merge_timeout, test_ratio=args.test_ratio, dry_run=args.dry_run, ) if not success and not args.dry_run: logger.error("Merge job failed") sys.exit(1) # Wait for merge if args.wait_for_merge and not args.dry_run: merge_ready = wait_for_datasets([f"{args.hf_username}/{final_dataset}"], token, args.wait_timeout) if not merge_ready: logger.error("Merge failed. Cannot proceed with training.") sys.exit(1) elif args.dry_run: logger.info("[DRY RUN - Would wait for merge]") else: logger.info("\nSkipping merge (--skip-merge)") # Verify dataset exists if not args.dry_run: if not check_dataset_exists(f"{args.hf_username}/{final_dataset}", token): logger.error(f"Dataset not found: {args.hf_username}/{final_dataset}") sys.exit(1) logger.info(f"✓ Dataset verified: {args.hf_username}/{final_dataset}") # Phase 3: Training if not args.skip_training: logger.info("\n" + "=" * 70) logger.info("PHASE 3: Training Model") logger.info("=" * 70) if args.publish_both: # Launch training with --merge-model to merged repo logger.info(f"Launching training with merged model output to {merged_repo}") success = launch_training_job( hf_username=args.hf_username, dataset_repo=final_dataset, model_repo=merged_repo, flavor=args.training_flavor, timeout=args.training_timeout, num_epochs=args.num_epochs, eval_split=args.eval_split, lora_r=args.lora_r, merge_model=True, dry_run=args.dry_run, ) if not success and not args.dry_run: logger.error("Training job for merged model failed") sys.exit(1) # Launch LoRA extraction job logger.info(f"Launching LoRA extraction to {lora_repo}") success = launch_lora_extraction_job( hf_username=args.hf_username, source_repo=merged_repo, target_repo=lora_repo, flavor="cpu-basic", timeout="30m", dry_run=args.dry_run, ) if not success and not args.dry_run: logger.error("LoRA extraction job failed") sys.exit(1) else: # Single model training (original behavior) success = launch_training_job( hf_username=args.hf_username, dataset_repo=final_dataset, model_repo=args.model_repo, flavor=args.training_flavor, timeout=args.training_timeout, num_epochs=args.num_epochs, eval_split=args.eval_split, lora_r=args.lora_r, merge_model=False, dry_run=args.dry_run, ) if not success and not args.dry_run: logger.error("Training job failed") sys.exit(1) else: logger.info("\nSkipping training (--skip-training)") # Summary print("\n" + "=" * 70) print("PIPELINE COMPLETE!") print("=" * 70) if args.dry_run: print("[DRY RUN - No jobs were actually launched]") print(f"\nFinal Dataset: https://huggingface.co/datasets/{args.hf_username}/{final_dataset}") if not args.skip_training: if args.publish_both: print(f"LoRA Model: https://huggingface.co/{args.hf_username}/{lora_repo}") print(f"Merged Model: https://huggingface.co/{args.hf_username}/{merged_repo}") else: print(f"Model: https://huggingface.co/{args.hf_username}/{args.model_repo}") print(f"Monitor: https://huggingface.co/jobs") print("=" * 70) if __name__ == "__main__": if len(sys.argv) == 1: print("=" * 70) print("End-to-End Chunked Dataset + Training Pipeline") print("=" * 70) print("\nOrchestrates: Chunks -> Merge -> Training") print("\nFor help: uv run run_end_to_end_chunked.py --help") print("=" * 70) sys.exit(0) main()