File size: 24,217 Bytes
5a923d3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 | #!/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()
|