Tonic commited on
Commit
5a923d3
·
verified ·
1 Parent(s): 21e63f0

Upload run_end_to_end_chunked.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. run_end_to_end_chunked.py +661 -0
run_end_to_end_chunked.py ADDED
@@ -0,0 +1,661 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ End-to-End Chunked Dataset Preparation + Training Pipeline
4
+
5
+ This script orchestrates the complete workflow:
6
+ 1. Plans and launches parallel chunk jobs
7
+ 2. Waits for all chunks to complete
8
+ 3. Launches merge job
9
+ 4. Waits for merged dataset
10
+ 5. Automatically launches training
11
+ 6. Optionally publishes both LoRA and merged models separately
12
+
13
+ Usage:
14
+ # Full end-to-end with default settings
15
+ uv run run_end_to_end_chunked.py \
16
+ --hf-username Tonic \
17
+ --base-repo android-text-full \
18
+ --model-repo l-operator-instruct \
19
+ --chunk-size 45 \
20
+ --test-ratio 0.07
21
+
22
+ # With custom training parameters
23
+ uv run run_end_to_end_chunked.py \
24
+ --hf-username Tonic \
25
+ --base-repo android-text-full \
26
+ --model-repo l-operator-instruct \
27
+ --chunk-size 45 \
28
+ --max-mobile-actions 9600 \
29
+ --android-ratio 0.7 \
30
+ --test-ratio 0.07 \
31
+ --num-epochs 3 \
32
+ --flavor a10g-medium \
33
+ --timeout 12h
34
+
35
+ # Publish both LoRA and merged models separately
36
+ uv run run_end_to_end_chunked.py \
37
+ --hf-username Tonic \
38
+ --base-repo android-text-full \
39
+ --lora-repo l-operator-lora \
40
+ --merged-repo l-operator-merged \
41
+ --publish-both \
42
+ --chunk-size 45 \
43
+ --num-epochs 3
44
+
45
+ # Resume from existing chunks (skip to training)
46
+ uv run run_end_to_end_chunked.py \
47
+ --hf-username Tonic \
48
+ --base-repo android-text-full \
49
+ --model-repo l-operator-instruct \
50
+ --skip-chunks \
51
+ --total-chunks 6
52
+ """
53
+
54
+ import argparse
55
+ import logging
56
+ import os
57
+ import subprocess
58
+ import sys
59
+ import time
60
+ from typing import List, Optional, Tuple
61
+
62
+ logging.basicConfig(
63
+ level=logging.INFO,
64
+ format="%(asctime)s - %(levelname)s - %(message)s",
65
+ )
66
+ logger = logging.getLogger(__name__)
67
+
68
+ TOTAL_TRAIN_FILES = 275
69
+
70
+
71
+ def run_command(cmd: List[str], description: str, dry_run: bool = False, extra_env: Optional[dict] = None) -> Tuple[bool, str]:
72
+ """Run a shell command and return success status and output."""
73
+ cmd_str = " ".join(cmd)
74
+ logger.info(f"\n{'='*70}")
75
+ logger.info(f"{description}")
76
+ logger.info(f"{'='*70}")
77
+ logger.info(f"Command: {cmd_str}")
78
+
79
+ if dry_run:
80
+ logger.info("[DRY RUN - Command not executed]")
81
+ return True, ""
82
+
83
+ env = os.environ.copy()
84
+ env.setdefault("PYTHONIOENCODING", "utf-8")
85
+ env.setdefault("PYTHONUTF8", "1")
86
+ if extra_env:
87
+ env.update(extra_env)
88
+
89
+ try:
90
+ result = subprocess.run(
91
+ cmd,
92
+ capture_output=True,
93
+ text=True,
94
+ check=True,
95
+ env=env,
96
+ encoding="utf-8",
97
+ errors="replace",
98
+ )
99
+ logger.info("Success!")
100
+ return True, result.stdout
101
+ except subprocess.CalledProcessError as e:
102
+ logger.error(f"Command failed: {e}")
103
+ logger.error(f"stderr: {e.stderr[-1000:]}")
104
+ return False, e.stderr
105
+
106
+
107
+ def calculate_chunks(chunk_size: int) -> List[Tuple[int, int, int]]:
108
+ """Calculate chunk boundaries."""
109
+ chunks = []
110
+ for start in range(0, TOTAL_TRAIN_FILES, chunk_size):
111
+ end = min(start + chunk_size, TOTAL_TRAIN_FILES)
112
+ chunk_idx = start // chunk_size
113
+ chunks.append((chunk_idx, start, end))
114
+ return chunks
115
+
116
+
117
+ def launch_chunk_job(
118
+ hf_username: str,
119
+ base_repo: str,
120
+ chunk_index: int,
121
+ chunk_size: int,
122
+ flavor: str,
123
+ timeout: str,
124
+ max_mobile_actions: Optional[int] = None,
125
+ android_ratio: float = 0.5,
126
+ dry_run: bool = False,
127
+ ) -> bool:
128
+ """Launch a single chunk processing job."""
129
+ # Use HF jobs with script args passed via SCRIPT_ARGS env var
130
+ script_args = f"--hf-username {hf_username} --base-repo {base_repo} --chunk-index {chunk_index} --chunk-size {chunk_size} --upload"
131
+
132
+ # Add mobile-actions only to chunk 0
133
+ if chunk_index == 0 and max_mobile_actions and max_mobile_actions > 0:
134
+ script_args += f" --max-mobile-actions {max_mobile_actions} --android-ratio {android_ratio}"
135
+ elif chunk_index == 0:
136
+ script_args += " --skip-mobile-actions"
137
+
138
+ cmd = [
139
+ "hf", "jobs", "uv", "run",
140
+ "--flavor", flavor,
141
+ "--secrets", "HF_TOKEN",
142
+ "--timeout", timeout,
143
+ "--env", f"SCRIPT_ARGS={script_args}",
144
+ "--",
145
+ "bash", "-c",
146
+ f'python -c "import sys; sys.argv=[\"script.py\"] + \"$SCRIPT_ARGS\".split(); exec(open(\"train/prepare_chunked_dataset.py\").read())"',
147
+ ]
148
+
149
+ success, _ = run_command(
150
+ cmd,
151
+ f"Launch Chunk {chunk_index} (files {chunk_index * chunk_size}-{min((chunk_index + 1) * chunk_size, TOTAL_TRAIN_FILES) - 1})",
152
+ dry_run,
153
+ )
154
+ return success
155
+
156
+
157
+ def launch_merge_job(
158
+ hf_username: str,
159
+ base_repo: str,
160
+ final_repo: str,
161
+ total_chunks: int,
162
+ flavor: str,
163
+ timeout: str,
164
+ test_ratio: float,
165
+ dry_run: bool = False,
166
+ ) -> bool:
167
+ """Launch the final merge job."""
168
+ 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"
169
+
170
+ cmd = [
171
+ "hf", "jobs", "uv", "run",
172
+ "--flavor", flavor,
173
+ "--secrets", "HF_TOKEN",
174
+ "--timeout", timeout,
175
+ "--env", f"SCRIPT_ARGS={script_args}",
176
+ "--",
177
+ "bash", "-c",
178
+ f'python -c "import sys; sys.argv=[\"script.py\"] + \"$SCRIPT_ARGS\".split(); exec(open(\"train/prepare_chunked_dataset.py\").read())"',
179
+ ]
180
+
181
+ success, _ = run_command(
182
+ cmd,
183
+ f"Launch Final Merge ({total_chunks} chunks -> {final_repo})",
184
+ dry_run,
185
+ )
186
+ return success
187
+
188
+
189
+ def launch_training_job(
190
+ hf_username: str,
191
+ dataset_repo: str,
192
+ model_repo: str,
193
+ flavor: str,
194
+ timeout: str,
195
+ num_epochs: int,
196
+ eval_split: float,
197
+ lora_r: int,
198
+ merge_model: bool = False,
199
+ dry_run: bool = False,
200
+ ) -> bool:
201
+ """Launch training job."""
202
+ cmd = [
203
+ "hf", "jobs", "uv", "run",
204
+ "train/sft-lfm2.5.py",
205
+ "--flavor", flavor,
206
+ "--secrets", "HF_TOKEN",
207
+ "--timeout", timeout,
208
+ "--",
209
+ "--dataset", f"{hf_username}/{dataset_repo}",
210
+ "--output-repo", f"{hf_username}/{model_repo}",
211
+ "--num-epochs", str(num_epochs),
212
+ "--eval-split", str(eval_split),
213
+ "--lora-r", str(lora_r),
214
+ ]
215
+
216
+ if merge_model:
217
+ cmd.append("--merge-model")
218
+
219
+ model_type = "Merged" if merge_model else "LoRA"
220
+ success, _ = run_command(
221
+ cmd,
222
+ f"Launch Training ({dataset_repo} -> {model_repo}, {model_type})",
223
+ dry_run,
224
+ )
225
+ return success
226
+
227
+
228
+ def launch_lora_extraction_job(
229
+ hf_username: str,
230
+ source_repo: str,
231
+ target_repo: str,
232
+ flavor: str,
233
+ timeout: str,
234
+ dry_run: bool = False,
235
+ ) -> bool:
236
+ """Launch a job to extract and copy LoRA adapter to separate repo."""
237
+ # Use an inline Python script via hf jobs
238
+ python_code = (
239
+ "import os; import sys; "
240
+ "from huggingface_hub import HfApi, snapshot_download, upload_folder; "
241
+ "source = os.environ['SOURCE_REPO']; target = os.environ['TARGET_REPO']; token = os.environ['HF_TOKEN']; "
242
+ "print(f'Extracting LoRA from {source} to {target}'); "
243
+ "api = HfApi(token=token); "
244
+ "local_path = '/tmp/lora_adapter'; os.makedirs(local_path, exist_ok=True); "
245
+ "snapshot_download(repo_id=source, local_dir=local_path, allow_patterns=['adapter*', '*.json', 'README*'], token=token); "
246
+ "api.create_repo(repo_id=target, repo_type='model', exist_ok=True, private=True); "
247
+ "upload_folder(folder_path=local_path, repo_id=target, token=token); "
248
+ "print(f'LoRA adapter copied to {target}')"
249
+ )
250
+
251
+ cmd = [
252
+ "hf", "jobs", "uv", "run",
253
+ "--flavor", flavor,
254
+ "--secrets", "HF_TOKEN",
255
+ "--timeout", timeout,
256
+ "--",
257
+ "python", "-c", python_code,
258
+ ]
259
+
260
+ # Set environment variables for the job
261
+ extra_env = {
262
+ "SOURCE_REPO": f"{hf_username}/{source_repo}",
263
+ "TARGET_REPO": f"{hf_username}/{target_repo}",
264
+ }
265
+
266
+ success, _ = run_command(
267
+ cmd,
268
+ f"Extract LoRA ({source_repo} -> {target_repo})",
269
+ dry_run,
270
+ extra_env=extra_env,
271
+ )
272
+ return success
273
+
274
+
275
+ def check_dataset_exists(repo_id: str, token: str) -> bool:
276
+ """Check if a dataset exists on HuggingFace Hub."""
277
+ try:
278
+ from huggingface_hub import dataset_info
279
+ dataset_info(repo_id, token=token)
280
+ return True
281
+ except Exception:
282
+ return False
283
+
284
+
285
+ def wait_for_datasets(
286
+ repo_ids: List[str],
287
+ token: str,
288
+ max_wait_minutes: int,
289
+ poll_interval: int = 30,
290
+ ) -> bool:
291
+ """Wait for multiple datasets to be available."""
292
+ logger.info(f"\n{'='*70}")
293
+ logger.info(f"Waiting for {len(repo_ids)} datasets...")
294
+ logger.info(f"Max wait: {max_wait_minutes} minutes")
295
+ logger.info(f"{'='*70}")
296
+
297
+ start_time = time.time()
298
+ max_wait_seconds = max_wait_minutes * 60
299
+
300
+ pending = set(repo_ids)
301
+ ready = set()
302
+
303
+ while time.time() - start_time < max_wait_seconds:
304
+ for repo in list(pending):
305
+ if check_dataset_exists(repo, token):
306
+ ready.add(repo)
307
+ pending.remove(repo)
308
+ logger.info(f" ✓ Ready: {repo}")
309
+
310
+ if not pending:
311
+ logger.info(f"\nAll {len(repo_ids)} datasets ready!")
312
+ return True
313
+
314
+ remaining = len(pending)
315
+ elapsed = int(time.time() - start_time)
316
+ logger.info(f" ... {remaining} pending ({elapsed}s elapsed)")
317
+ time.sleep(poll_interval)
318
+
319
+ logger.error(f"\nTimeout! {len(pending)} datasets not ready:")
320
+ for repo in pending:
321
+ logger.error(f" - {repo}")
322
+ return False
323
+
324
+
325
+ def parse_args() -> argparse.Namespace:
326
+ """Parse command line arguments."""
327
+ parser = argparse.ArgumentParser(
328
+ description="End-to-end chunked dataset + training pipeline",
329
+ formatter_class=argparse.RawDescriptionHelpFormatter,
330
+ epilog="""
331
+ Examples:
332
+ # Full end-to-end with defaults
333
+ uv run run_end_to_end_chunked.py \\
334
+ --hf-username Tonic \\
335
+ --base-repo android-text-full \\
336
+ --model-repo l-operator-instruct \\
337
+ --chunk-size 45 \\
338
+ --test-ratio 0.07
339
+
340
+ # With custom training parameters
341
+ uv run run_end_to_end_chunked.py \\
342
+ --hf-username Tonic \\
343
+ --base-repo android-text-full \\
344
+ --model-repo l-operator-instruct \\
345
+ --chunk-size 45 \\
346
+ --max-mobile-actions 9600 \\
347
+ --android-ratio 0.7 \\
348
+ --test-ratio 0.07 \\
349
+ --num-epochs 3 \\
350
+ --flavor a10g-medium \\
351
+ --timeout 12h
352
+
353
+ # Publish both LoRA and merged models to separate repos
354
+ uv run run_end_to_end_chunked.py \\
355
+ --hf-username Tonic \\
356
+ --base-repo android-text-full \\
357
+ --lora-repo l-operator-lora \\
358
+ --merged-repo l-operator-merged \\
359
+ --publish-both \\
360
+ --chunk-size 45 \\
361
+ --num-epochs 3
362
+
363
+ # Resume from existing chunks (skip chunk processing)
364
+ uv run run_end_to_end_chunked.py \\
365
+ --hf-username Tonic \\
366
+ --base-repo android-text-full \\
367
+ --model-repo l-operator-instruct \\
368
+ --skip-chunks \\
369
+ --total-chunks 6 \\
370
+ --wait-for-merge
371
+
372
+ # Skip to training only (dataset exists)
373
+ uv run run_end_to_end_chunked.py \\
374
+ --hf-username Tonic \\
375
+ --base-repo android-text-full \\
376
+ --model-repo l-operator-instruct \\
377
+ --skip-chunks \\
378
+ --skip-merge \\
379
+ --dataset-repo Tonic/android-text-full
380
+
381
+ # Training only with dual model publishing
382
+ uv run run_end_to_end_chunked.py \\
383
+ --hf-username Tonic \\
384
+ --base-repo android-text-full \\
385
+ --lora-repo l-operator-lora \\
386
+ --merged-repo l-operator-merged \\
387
+ --publish-both \\
388
+ --skip-chunks \\
389
+ --skip-merge \\
390
+ --dataset-repo Tonic/android-text-full
391
+ """,
392
+ )
393
+
394
+ # Required
395
+ parser.add_argument("--hf-username", required=True, help="HuggingFace username")
396
+ parser.add_argument("--base-repo", required=True, help="Base repository name for chunks")
397
+ parser.add_argument("--model-repo", required=True, help="Model repository name (used when not using --publish-both)")
398
+
399
+ # Dual model publishing
400
+ parser.add_argument("--lora-repo", default=None, help="LoRA adapter repository name (for --publish-both)")
401
+ parser.add_argument("--merged-repo", default=None, help="Merged model repository name (for --publish-both)")
402
+ parser.add_argument("--publish-both", action="store_true", help="Publish both LoRA and merged models to separate repos")
403
+
404
+ # Chunk configuration
405
+ parser.add_argument("--chunk-size", type=int, default=45, help="Files per chunk (default: 45)")
406
+ parser.add_argument("--total-chunks", type=int, default=None, help="Total chunks (auto-calculate if not set)")
407
+
408
+ # Data configuration
409
+ parser.add_argument("--max-mobile-actions", type=int, default=9600, help="Mobile actions for chunk 0")
410
+ parser.add_argument("--skip-mobile-actions", action="store_true", help="Exclude mobile-actions")
411
+ parser.add_argument("--android-ratio", type=float, default=0.7, help="Android ratio")
412
+ parser.add_argument("--test-ratio", type=float, default=0.0, help="Test split ratio")
413
+
414
+ # Training configuration
415
+ parser.add_argument("--num-epochs", type=int, default=1, help="Training epochs")
416
+ parser.add_argument("--eval-split", type=float, default=0.2, help="Evaluation split")
417
+ parser.add_argument("--lora-r", type=int, default=16, help="LoRA rank")
418
+ parser.add_argument("--dataset-repo", default=None, help="Override final dataset repo (default: base-repo)")
419
+
420
+ # HF Jobs configuration (using cheapest CPU flavors for dataset processing)
421
+ parser.add_argument("--chunk-flavor", default="cpu-basic", help="Flavor for chunk jobs (default: cpu-basic)")
422
+ parser.add_argument("--merge-flavor", default="cpu-basic", help="Flavor for merge job (default: cpu-basic)")
423
+ parser.add_argument("--training-flavor", default="a10g-small", help="Flavor for training")
424
+ parser.add_argument("--chunk-timeout", default="6h", help="Timeout for chunk jobs")
425
+ parser.add_argument("--merge-timeout", default="2h", help="Timeout for merge job")
426
+ parser.add_argument("--training-timeout", default="6h", help="Timeout for training")
427
+
428
+ # Execution control
429
+ parser.add_argument("--skip-chunks", action="store_true", help="Skip chunk processing (use existing)")
430
+ parser.add_argument("--skip-merge", action="store_true", help="Skip merge (use existing dataset)")
431
+ parser.add_argument("--skip-training", action="store_true", help="Skip training (dataset prep only)")
432
+ parser.add_argument("--wait-for-chunks", action="store_true", default=True, help="Wait for chunks")
433
+ parser.add_argument("--wait-for-merge", action="store_true", default=True, help="Wait for merge")
434
+ parser.add_argument("--wait-timeout", type=int, default=90, help="Max wait minutes")
435
+ parser.add_argument("--dry-run", action="store_true", help="Show commands without executing")
436
+ parser.add_argument("--public", action="store_true", help="Make repos public")
437
+
438
+ return parser.parse_args()
439
+
440
+
441
+ def main():
442
+ """Main entry point."""
443
+ args = parse_args()
444
+
445
+ # Get token
446
+ token = os.environ.get("HF_TOKEN") or os.environ.get("hfjob")
447
+ if not token:
448
+ logger.error("HF_TOKEN environment variable not set!")
449
+ sys.exit(1)
450
+
451
+ # Calculate chunks
452
+ if args.total_chunks:
453
+ total_chunks = args.total_chunks
454
+ else:
455
+ chunks = calculate_chunks(args.chunk_size)
456
+ total_chunks = len(chunks)
457
+
458
+ final_dataset = args.dataset_repo or args.base_repo
459
+
460
+ # Determine model repos
461
+ if args.publish_both:
462
+ if not args.lora_repo or not args.merged_repo:
463
+ logger.error("--publish-both requires both --lora-repo and --merged-repo")
464
+ sys.exit(1)
465
+ lora_repo = args.lora_repo
466
+ merged_repo = args.merged_repo
467
+ model_display = f"LoRA: {lora_repo}, Merged: {merged_repo}"
468
+ else:
469
+ lora_repo = None
470
+ merged_repo = args.model_repo
471
+ model_display = merged_repo
472
+
473
+ # Print configuration
474
+ print("\n" + "=" * 70)
475
+ print("END-TO-END CHUNKED PIPELINE")
476
+ print("=" * 70)
477
+ print(f"HF Username: {args.hf_username}")
478
+ print(f"Base Repo: {args.base_repo}")
479
+ print(f"Final Dataset: {final_dataset}")
480
+ if args.publish_both:
481
+ print(f"LoRA Repo: {lora_repo}")
482
+ print(f"Merged Repo: {merged_repo}")
483
+ else:
484
+ print(f"Model Repo: {args.model_repo}")
485
+ print(f"Chunks: {total_chunks} x ~{args.chunk_size} files")
486
+ print(f"Mobile Actions: {'EXCLUDED' if args.skip_mobile_actions else args.max_mobile_actions}")
487
+ print(f"Test Ratio: {args.test_ratio}")
488
+ print(f"Training: {args.num_epochs} epochs, LoRA r={args.lora_r}")
489
+ if args.publish_both:
490
+ print(f"Output: Both LoRA and merged models will be published")
491
+ print("=" * 70)
492
+
493
+ if args.dry_run:
494
+ print("\nDRY RUN MODE - Commands will be shown but not executed\n")
495
+
496
+ # Phase 1: Process chunks
497
+ if not args.skip_chunks:
498
+ logger.info("\n" + "=" * 70)
499
+ logger.info("PHASE 1: Processing Chunks")
500
+ logger.info("=" * 70)
501
+
502
+ max_mobile = 0 if args.skip_mobile_actions else args.max_mobile_actions
503
+
504
+ # Launch all chunk jobs
505
+ for idx in range(total_chunks):
506
+ success = launch_chunk_job(
507
+ hf_username=args.hf_username,
508
+ base_repo=args.base_repo,
509
+ chunk_index=idx,
510
+ chunk_size=args.chunk_size,
511
+ flavor=args.chunk_flavor,
512
+ timeout=args.chunk_timeout,
513
+ max_mobile_actions=max_mobile if idx == 0 else None,
514
+ android_ratio=args.android_ratio,
515
+ dry_run=args.dry_run,
516
+ )
517
+
518
+ if not success and not args.dry_run:
519
+ logger.error(f"Failed to launch chunk {idx}")
520
+
521
+ # Wait for chunks
522
+ if args.wait_for_chunks and not args.dry_run:
523
+ chunk_repos = [f"{args.hf_username}/{args.base_repo}-chunk-{i}" for i in range(total_chunks)]
524
+ chunks_ready = wait_for_datasets(chunk_repos, token, args.wait_timeout)
525
+
526
+ if not chunks_ready:
527
+ logger.error("Chunks failed. Cannot proceed.")
528
+ sys.exit(1)
529
+ elif args.dry_run:
530
+ logger.info("[DRY RUN - Would wait for chunks]")
531
+ else:
532
+ logger.info("\nSkipping chunk processing (--skip-chunks)")
533
+
534
+ # Phase 2: Merge chunks
535
+ if not args.skip_merge:
536
+ logger.info("\n" + "=" * 70)
537
+ logger.info("PHASE 2: Merging Chunks")
538
+ logger.info("=" * 70)
539
+
540
+ success = launch_merge_job(
541
+ hf_username=args.hf_username,
542
+ base_repo=args.base_repo,
543
+ final_repo=final_dataset,
544
+ total_chunks=total_chunks,
545
+ flavor=args.merge_flavor,
546
+ timeout=args.merge_timeout,
547
+ test_ratio=args.test_ratio,
548
+ dry_run=args.dry_run,
549
+ )
550
+
551
+ if not success and not args.dry_run:
552
+ logger.error("Merge job failed")
553
+ sys.exit(1)
554
+
555
+ # Wait for merge
556
+ if args.wait_for_merge and not args.dry_run:
557
+ merge_ready = wait_for_datasets([f"{args.hf_username}/{final_dataset}"], token, args.wait_timeout)
558
+
559
+ if not merge_ready:
560
+ logger.error("Merge failed. Cannot proceed with training.")
561
+ sys.exit(1)
562
+ elif args.dry_run:
563
+ logger.info("[DRY RUN - Would wait for merge]")
564
+ else:
565
+ logger.info("\nSkipping merge (--skip-merge)")
566
+ # Verify dataset exists
567
+ if not args.dry_run:
568
+ if not check_dataset_exists(f"{args.hf_username}/{final_dataset}", token):
569
+ logger.error(f"Dataset not found: {args.hf_username}/{final_dataset}")
570
+ sys.exit(1)
571
+ logger.info(f"✓ Dataset verified: {args.hf_username}/{final_dataset}")
572
+
573
+ # Phase 3: Training
574
+ if not args.skip_training:
575
+ logger.info("\n" + "=" * 70)
576
+ logger.info("PHASE 3: Training Model")
577
+ logger.info("=" * 70)
578
+
579
+ if args.publish_both:
580
+ # Launch training with --merge-model to merged repo
581
+ logger.info(f"Launching training with merged model output to {merged_repo}")
582
+ success = launch_training_job(
583
+ hf_username=args.hf_username,
584
+ dataset_repo=final_dataset,
585
+ model_repo=merged_repo,
586
+ flavor=args.training_flavor,
587
+ timeout=args.training_timeout,
588
+ num_epochs=args.num_epochs,
589
+ eval_split=args.eval_split,
590
+ lora_r=args.lora_r,
591
+ merge_model=True,
592
+ dry_run=args.dry_run,
593
+ )
594
+
595
+ if not success and not args.dry_run:
596
+ logger.error("Training job for merged model failed")
597
+ sys.exit(1)
598
+
599
+ # Launch LoRA extraction job
600
+ logger.info(f"Launching LoRA extraction to {lora_repo}")
601
+ success = launch_lora_extraction_job(
602
+ hf_username=args.hf_username,
603
+ source_repo=merged_repo,
604
+ target_repo=lora_repo,
605
+ flavor="cpu-basic",
606
+ timeout="30m",
607
+ dry_run=args.dry_run,
608
+ )
609
+
610
+ if not success and not args.dry_run:
611
+ logger.error("LoRA extraction job failed")
612
+ sys.exit(1)
613
+ else:
614
+ # Single model training (original behavior)
615
+ success = launch_training_job(
616
+ hf_username=args.hf_username,
617
+ dataset_repo=final_dataset,
618
+ model_repo=args.model_repo,
619
+ flavor=args.training_flavor,
620
+ timeout=args.training_timeout,
621
+ num_epochs=args.num_epochs,
622
+ eval_split=args.eval_split,
623
+ lora_r=args.lora_r,
624
+ merge_model=False,
625
+ dry_run=args.dry_run,
626
+ )
627
+
628
+ if not success and not args.dry_run:
629
+ logger.error("Training job failed")
630
+ sys.exit(1)
631
+ else:
632
+ logger.info("\nSkipping training (--skip-training)")
633
+
634
+ # Summary
635
+ print("\n" + "=" * 70)
636
+ print("PIPELINE COMPLETE!")
637
+ print("=" * 70)
638
+ if args.dry_run:
639
+ print("[DRY RUN - No jobs were actually launched]")
640
+ print(f"\nFinal Dataset: https://huggingface.co/datasets/{args.hf_username}/{final_dataset}")
641
+ if not args.skip_training:
642
+ if args.publish_both:
643
+ print(f"LoRA Model: https://huggingface.co/{args.hf_username}/{lora_repo}")
644
+ print(f"Merged Model: https://huggingface.co/{args.hf_username}/{merged_repo}")
645
+ else:
646
+ print(f"Model: https://huggingface.co/{args.hf_username}/{args.model_repo}")
647
+ print(f"Monitor: https://huggingface.co/jobs")
648
+ print("=" * 70)
649
+
650
+
651
+ if __name__ == "__main__":
652
+ if len(sys.argv) == 1:
653
+ print("=" * 70)
654
+ print("End-to-End Chunked Dataset + Training Pipeline")
655
+ print("=" * 70)
656
+ print("\nOrchestrates: Chunks -> Merge -> Training")
657
+ print("\nFor help: uv run run_end_to_end_chunked.py --help")
658
+ print("=" * 70)
659
+ sys.exit(0)
660
+
661
+ main()