Automation foundation model for tiny devices: 2-bit, 8-29 MB, tool calls, ASR, structured extraction and embeddings on phones, wearables, smart homes, robots, cars and microcontrollers.
Working states
HenryNdubuaku3dea7f0e999a
diff --git a/scripts/build_dataset.py b/scripts/build_dataset.pyindex 9a0fdf3..89b8033 100644--- a/scripts/build_dataset.py+++ b/scripts/build_dataset.py@@ -4,9 +4,12 @@Combines the text pipeline (tools_data.py) with TTS audio generation intoone script that produces a single HF Dataset with an Audio column.+When --gcs-upload is provided, processes in batches: each batch is synthesized,+saved as a shard, uploaded to GCS, and deleted locally — keeping disk usage bounded.+Usage:python scripts/build_dataset.py --max-samples 1000 --workers 16- python scripts/build_dataset.py --max-samples 1000 --gcs-upload gs://cactus-dataset/tool_calls+ python scripts/build_dataset.py --gcs-upload gs://cactus-dataset/tool_calls --batch-size 500"""import argparse@@ -14,11 +17,12 @@ import ioimport loggingimport osimport random+import shutilimport subprocessimport sysimport timeimport wave-from concurrent.futures import ThreadPoolExecutor, as_completed+from concurrent.futures import ThreadPoolExecutorfrom datasets import Audio, Dataset, load_from_diskfrom tqdm import tqdm@@ -29,8 +33,6 @@ from tools_data import load_and_combinelogging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")logger = logging.getLogger(__name__)-# Voice templates — defined as Wavenet; the type (Wavenet/Neural2/Standard)-# is swapped at synthesis time via _get_voice() to spread load across quotas._VOICE_TEMPLATES = [("en-GB", "en-GB-Wavenet-B", "MALE", True, False),("en-GB", "en-GB-Wavenet-A", "FEMALE", True, False),@@ -47,16 +49,16 @@ _VOICE_TEMPLATES = [("en-IN", "en-IN-Wavenet-A", "FEMALE", True, True),]-# Two voice types, each with its own 1k/min quota (2k/min total)_VOICE_TYPES = ["Wavenet", "Neural2"]+VOICES = _VOICE_TEMPLATES+def _get_voice(idx):"""Return (lang, voice_name, gender_str, configurable, child) for a sample.- Cycles through voice types (Wavenet→Neural2→Standard) via idx % 3,+ Cycles through voice types (Wavenet->Neural2) via idx % 2,then picks a voice template via (idx // 3) % len(_VOICE_TEMPLATES).- This distributes requests evenly across the three quota buckets."""vtype = _VOICE_TYPES[idx % len(_VOICE_TYPES)]template = _VOICE_TEMPLATES[(idx // 3) % len(_VOICE_TEMPLATES)]@@ -64,9 +66,6 @@ def _get_voice(idx):voice_name = base_name.replace("Wavenet", vtype)return lang, voice_name, gender, configurable, child-# Keep VOICES as alias for backfill (uses templates only)-VOICES = _VOICE_TEMPLATES-def _pcm_to_wav_bytes(pcm_bytes: bytes, sample_rate: int) -> bytes:"""Convert raw LINEAR16 PCM bytes to a WAV byte buffer."""@@ -82,9 +81,6 @@ def _pcm_to_wav_bytes(pcm_bytes: bytes, sample_rate: int) -> bytes:def _synthesize_one(client, idx, query, max_retries=5):"""Synthesize TTS audio for a single query via GCP Cloud TTS.- Selects a voice from VOICES based on idx, applies randomized prosody- for configurable voices, and retries on transient API errors.-Returns:Tuple of (idx, wav_bytes, voice_name, error_msg).wav_bytes is None on failure; error_msg is None on success.@@ -140,13 +136,269 @@ def _synthesize_one(client, idx, query, max_retries=5):return idx, None, voice_name, "max retries exceeded"+def _synthesize_rows(batch_ds, audio_data, voice_names, workers, rate_limit,+ cache_dir, global_offset=0):+ """Run TTS synthesis for rows where audio_data[i] is None.-def _load_text_dataset(output_path, max_samples):- """Load the text dataset and optionally resume from an existing build.+ Uses global_offset + local_index for voice selection so that voice+ assignment is deterministic regardless of batch boundaries.+ WAV files are written to cache_dir/{local_idx}.wav.+ """+ needs = [i for i in range(len(batch_ds)) if audio_data[i] is None]+ if not needs:+ return- Returns:- Tuple of (combined_dataset, existing_dataset_or_None).+ from google.cloud import texttospeech++ os.makedirs(cache_dir, exist_ok=True)++ items = [(i, global_offset + i, batch_ds[i]["query"]) for i in needs]+ logger.info(f"Synthesizing TTS for {len(items)} rows with {workers} workers...")++ def _worker(item):+ local_idx, global_idx, query = item+ client = texttospeech.TextToSpeechClient()+ _, wav_bytes, voice_name, err = _synthesize_one(client, global_idx, query)+ return local_idx, wav_bytes, voice_name, err++ success, failed = 0, 0+ delay = 1.0 / rate_limit if rate_limit > 0 else 0+ total = len(items)++ with ThreadPoolExecutor(max_workers=workers) as pool:+ pending = {}+ submitted = 0+ qi = iter(items)++ for _ in range(min(workers * 2, total)):+ q = next(qi)+ pending[pool.submit(_worker, q)] = q+ submitted += 1++ with tqdm(total=total, desc="TTS") as pbar:+ while pending:+ done_set = {f for f in list(pending) if f.done()}+ if not done_set:+ time.sleep(0.05)+ continue+ for fut in done_set:+ local_idx, wav_bytes, voice_name, err = fut.result()+ if wav_bytes is not None:+ wav_path = os.path.join(cache_dir, f"{local_idx}.wav")+ with open(wav_path, "wb") as f:+ f.write(wav_bytes)+ audio_data[local_idx] = wav_path+ voice_names[local_idx] = voice_name+ success += 1+ else:+ failed += 1+ logger.warning(f"Failed idx={global_offset + local_idx}: {err}")+ pbar.update(1)+ del pending[fut]++ if submitted < total:+ q = next(qi)+ pending[pool.submit(_worker, q)] = q+ submitted += 1+ time.sleep(delay)++ logger.info(f"TTS done: {success} generated, {failed} failed")+++def _backfill_voice_names(voice_names, global_offset=0):+ """Assign default voice names to any rows that don't have one."""+ for i in range(len(voice_names)):+ if not voice_names[i]:+ _, voice_name, _, _, _ = VOICES[(global_offset + i) % len(VOICES)]+ voice_names[i] = voice_name++def _build_arrow(batch_ds, audio_data, voice_names, arrow_path):+ """Build an HF Dataset from a batch and write a single .arrow file.++ Uses save_to_disk into a temp dir so that Audio columns are properly+ serialized (WAV bytes embedded), then moves the generated .arrow file."""+ import tempfile++ n = len(batch_ds)+ audio_column = []+ for i in range(n):+ path = audio_data[i]+ if path is not None and os.path.exists(path):+ audio_column.append(path)+ else:+ audio_column.append(None)++ ds_dict = {+ "query": [batch_ds[i]["query"] for i in range(n)],+ "audio": audio_column,+ "tools": [batch_ds[i]["tools"] for i in range(n)],+ "answers": [batch_ds[i]["answers"] for i in range(n)],+ "source": [batch_ds[i]["source"] for i in range(n)],+ "voice": voice_names[:n],+ }++ ds = Dataset.from_dict(ds_dict)+ ds = ds.cast_column("audio", Audio(sampling_rate=16000))++ with tempfile.TemporaryDirectory() as tmpdir:+ ds.save_to_disk(tmpdir)+ arrow_files = sorted(f for f in os.listdir(tmpdir) if f.endswith(".arrow"))+ if len(arrow_files) == 1:+ shutil.move(os.path.join(tmpdir, arrow_files[0]), arrow_path)+ else:+ import pyarrow as pa+ tables = []+ for af in arrow_files:+ with open(os.path.join(tmpdir, af), "rb") as fh:+ reader = pa.ipc.open_stream(fh)+ tables.append(reader.read_all())+ merged = pa.concat_tables(tables)+ with pa.OSFile(arrow_path, "wb") as sink:+ writer = pa.ipc.new_stream(sink, merged.schema)+ writer.write_table(merged)+ writer.close()++ logger.info(f"Built {arrow_path} ({n} rows)")+ info = ds.info+ del ds, ds_dict, audio_column+ return info+++def _arrow_exists_on_gcs(gcs_base, arrow_name):+ """Check if an arrow file already exists on GCS."""+ gcs_path = gcs_base + "/" + arrow_name+ result = subprocess.run(+ ["gcloud", "storage", "ls", gcs_path],+ capture_output=True, text=True,+ )+ return result.returncode == 0 and result.stdout.strip()+++def _upload_file_to_gcs(local_path, gcs_dest):+ """Upload a single file to GCS."""+ logger.info(f"Uploading {os.path.basename(local_path)} -> {gcs_dest}")+ result = subprocess.run(+ ["gcloud", "storage", "cp", local_path, gcs_dest],+ text=True,+ )+ if result.returncode != 0:+ logger.error(f"Upload failed for {local_path}")+ sys.exit(1)+++def _upload_metadata_to_gcs(gcs_base, num_batches, dataset_info):+ """Generate and upload state.json + dataset_info.json so load_from_disk works."""+ import json+ import tempfile++ arrow_files = [+ {"filename": f"data-{i:05d}-of-{num_batches:05d}.arrow"}+ for i in range(num_batches)+ ]++ state = {+ "_data_files": arrow_files,+ "_fingerprint": "batch_upload",+ "_format_columns": None,+ "_format_kwargs": {},+ "_format_type": None,+ "_output_all_columns": False,+ "_split": None,+ }++ with tempfile.TemporaryDirectory() as tmpdir:+ state_path = os.path.join(tmpdir, "state.json")+ with open(state_path, "w") as f:+ json.dump(state, f)+ _upload_file_to_gcs(state_path, gcs_base + "/state.json")++ info_path = os.path.join(tmpdir, "dataset_info.json")+ dataset_info.write_to_directory(tmpdir)+ _upload_file_to_gcs(info_path, gcs_base + "/dataset_info.json")+++def _process_batched(combined, batch_size, workers, rate_limit, output_path, gcs_upload):+ """Process dataset in batches: one arrow per batch, flat on GCS.++ GCS layout:+ gs://bucket/path/data-00000-of-00020.arrow+ gs://bucket/path/data-00001-of-00020.arrow+ ...+ gs://bucket/path/state.json+ gs://bucket/path/dataset_info.json++ load_from_disk("gs://bucket/path") works directly.+ """+ n = len(combined)+ num_batches = (n + batch_size - 1) // batch_size+ total_rows = 0+ dataset_info = None++ logger.info(f"Processing {n} rows in {num_batches} batches of {batch_size}...")++ for batch_idx in range(num_batches):+ start = batch_idx * batch_size+ end = min(start + batch_size, n)+ arrow_name = f"data-{batch_idx:05d}-of-{num_batches:05d}.arrow"++ # Resume: skip arrows already on GCS+ if _arrow_exists_on_gcs(gcs_upload, arrow_name):+ logger.info(f"{arrow_name} already on GCS, skipping (rows {start}-{end - 1})")+ total_rows += (end - start)+ continue++ logger.info(f"=== Batch {batch_idx + 1}/{num_batches}: {arrow_name} (rows {start}-{end - 1}) ===")+ batch = combined.select(range(start, end))+ batch_len = len(batch)++ audio_data = [None] * batch_len+ voice_names = [""] * batch_len+ cache_dir = os.path.join(output_path, f".cache_{batch_idx:05d}")++ existing_cache = os.path.join(output_path, ".audio_cache")+ if os.path.isdir(existing_cache):+ recovered = 0+ for i in range(batch_len):+ wav_path = os.path.join(existing_cache, f"{start + i}.wav")+ if os.path.exists(wav_path):+ audio_data[i] = wav_path+ recovered += 1+ if recovered:+ logger.info(f" Recovered {recovered}/{batch_len} WAVs from existing cache")++ _synthesize_rows(batch, audio_data, voice_names, workers, rate_limit,+ cache_dir, global_offset=start)+ _backfill_voice_names(voice_names, global_offset=start)++ os.makedirs(output_path, exist_ok=True)+ arrow_path = os.path.join(output_path, arrow_name)+ info = _build_arrow(batch, audio_data, voice_names, arrow_path)+ if dataset_info is None:+ dataset_info = info++ _upload_file_to_gcs(arrow_path, gcs_upload + "/" + arrow_name)+ os.remove(arrow_path)+ shutil.rmtree(cache_dir, ignore_errors=True)++ existing_cache = os.path.join(output_path, ".audio_cache")+ if os.path.isdir(existing_cache):+ for i in range(batch_len):+ wav_path = os.path.join(existing_cache, f"{start + i}.wav")+ if os.path.exists(wav_path):+ os.remove(wav_path)++ total_rows += batch_len+ logger.info(f"Progress: {total_rows}/{n} rows uploaded")++ if dataset_info is not None:+ _upload_metadata_to_gcs(gcs_upload, num_batches, dataset_info)++ return total_rows+++def _load_text_dataset(output_path, max_samples):+ """Load the text dataset and optionally resume from an existing build."""existing_ds = Noneif os.path.exists(output_path):try:@@ -167,14 +419,7 @@ def _load_text_dataset(output_path, max_samples):def _find_rows_needing_tts(combined, existing_ds, output_path):- """Identify which rows lack audio by checking the cache dir and existing dataset.-- First checks {output_path}/.audio_cache/ for WAV files from prior runs,- then falls back to inspecting the Arrow column in existing_ds.-- Returns:- Set of row indices that need TTS synthesis.- """+ """Identify which rows lack audio."""n = len(combined)needs_tts = set(range(n))@@ -204,14 +449,7 @@ def _find_rows_needing_tts(combined, existing_ds, output_path):def _recover_existing_audio(existing_ds, n, needs_tts, output_path):- """Recover audio file paths from the cache dir and existing dataset.-- Stores file paths (not bytes) to keep memory usage low.-- Returns:- Tuple of (audio_data list, voice_names list).- audio_data entries are file paths (str) or None.- """+ """Recover audio file paths from the cache dir and existing dataset."""audio_data = [None] * nvoice_names = [""] * n@@ -243,144 +481,47 @@ def _recover_existing_audio(existing_ds, n, needs_tts, output_path):return audio_data, voice_names-def _synthesize_missing(combined, needs_tts, audio_data, voice_names, workers, rate_limit, output_path):- """Run TTS synthesis, writing each WAV to disk immediately.-- Audio bytes are written to {output_path}/.audio_cache/{idx}.wav as they- arrive, keeping RAM usage constant regardless of dataset size. The- audio_data list stores file paths (not bytes) for later assembly.- """- if not needs_tts:- return+def _process_local(combined, workers, rate_limit, output_path):+ """Original local-only processing: synthesize all, build one dataset."""+ existing_ds = None+ if os.path.exists(output_path):+ try:+ existing_ds = load_from_disk(output_path)+ except Exception:+ pass- from google.cloud import texttospeech+ needs_tts = _find_rows_needing_tts(combined, existing_ds, output_path)+ audio_data, voice_names = _recover_existing_audio(+ existing_ds, len(combined), needs_tts, output_path+ )cache_dir = os.path.join(output_path, ".audio_cache")- os.makedirs(cache_dir, exist_ok=True)-- queries_to_synth = [(i, combined[i]["query"]) for i in sorted(needs_tts)]- logger.info(f"Synthesizing TTS for {len(queries_to_synth)} rows with {workers} workers...")- logger.info(f" Audio cache: {cache_dir}/")-- def _worker(item):- idx, query = item- client = texttospeech.TextToSpeechClient()- return _synthesize_one(client, idx, query)-- success, failed = 0, 0- delay = 1.0 / rate_limit if rate_limit > 0 else 0- total = len(queries_to_synth)-- with ThreadPoolExecutor(max_workers=workers) as pool:- pending = {}- submitted = 0- qi = iter(queries_to_synth)-- # Seed the pool with initial batch- for _ in range(min(workers * 2, total)):- q = next(qi)- pending[pool.submit(_worker, q)] = q- submitted += 1-- with tqdm(total=total, desc="TTS") as pbar:- while pending:- done_set = set()- for fut in list(pending):- if fut.done():- done_set.add(fut)- if not done_set:- # Wait for at least one to finish- time.sleep(0.05)- continue- for fut in done_set:- idx, wav_bytes, voice_name, err = fut.result()- if wav_bytes is not None:- wav_path = os.path.join(cache_dir, f"{idx}.wav")- with open(wav_path, "wb") as f:- f.write(wav_bytes)- audio_data[idx] = wav_path- voice_names[idx] = voice_name- success += 1- else:- failed += 1- logger.warning(f"Failed idx={idx}: {err}")- pbar.update(1)- del pending[fut]-- # Submit new work to maintain pool pressure- if submitted < total:- q = next(qi)- pending[pool.submit(_worker, q)] = q- submitted += 1- time.sleep(delay)-- logger.info(f"TTS done: {success} generated, {failed} failed")---def _backfill_voice_names(voice_names):- """Assign default voice names to any rows that don't have one."""- for i in range(len(voice_names)):- if not voice_names[i]:- _, voice_name, _, _, _ = VOICES[i % len(VOICES)]- voice_names[i] = voice_name---def _build_and_save(combined, audio_data, voice_names, output_path):- """Assemble the unified HF Dataset from file paths and save to disk.-- audio_data entries are file paths (str) or None. Each file is read- one at a time during assembly to avoid loading all audio into RAM.+ _synthesize_rows(combined, audio_data, voice_names, workers, rate_limit, cache_dir)+ _backfill_voice_names(voice_names)- Returns:- The saved Dataset.- """n = len(combined)- has_audio = sum(1 for x in audio_data if x is not None)- logger.info(f"Building unified HF Dataset... ({has_audio}/{n} with audio)")-- audio_column = []- for path in audio_data:- if path is not None and os.path.exists(path):- audio_column.append(path)- else:- audio_column.append(None)-- ds_dict = {- "query": [combined[i]["query"] for i in range(n)],- "audio": audio_column,- "tools": [combined[i]["tools"] for i in range(n)],- "answers": [combined[i]["answers"] for i in range(n)],- "source": [combined[i]["source"] for i in range(n)],- "voice": voice_names,+ os.makedirs(output_path, exist_ok=True)+ arrow_path = os.path.join(output_path, "data-00000-of-00001.arrow")+ info = _build_arrow(combined, audio_data, voice_names, arrow_path)++ # Write metadata so load_from_disk works+ import json+ state = {+ "_data_files": [{"filename": "data-00000-of-00001.arrow"}],+ "_fingerprint": "local_build",+ "_format_columns": None,+ "_format_kwargs": {},+ "_format_type": None,+ "_output_all_columns": False,+ "_split": None,}-- unified = Dataset.from_dict(ds_dict)- unified = unified.cast_column("audio", Audio(sampling_rate=16000))-- os.makedirs(os.path.dirname(output_path) if os.path.dirname(output_path) else ".", exist_ok=True)- unified.save_to_disk(output_path)- logger.info(f"Saved unified dataset to {output_path}/ ({len(unified)} rows)")- return unified---def _upload_to_gcs(output_path, gcs_upload):- """Upload the dataset to GCS via gcloud CLI."""- logger.info(f"Uploading dataset to {gcs_upload}...")- import glob as globmod- files = globmod.glob(os.path.join(output_path, "*"))- result = subprocess.run(- ["gcloud", "storage", "cp"] + files + [gcs_upload + "/"],- capture_output=True, text=True,- )- if result.returncode == 0:- logger.info(f"Dataset upload complete: {gcs_upload}")- else:- logger.error(f"Dataset upload failed: {result.stderr}")- sys.exit(1)-+ with open(os.path.join(output_path, "state.json"), "w") as f:+ json.dump(state, f)+ info.write_to_directory(output_path)+ logger.info(f"Saved {n} rows to {output_path}/")+ return ndef main():- """Entry point for the unified dataset build pipeline."""parser = argparse.ArgumentParser(description="Build unified tool-call dataset with TTS audio")parser.add_argument("--max-samples", type=int, default=None, help="Max samples to process")parser.add_argument("--workers", type=int, default=16, help="TTS concurrent workers (default: 16)")@@ -389,17 +530,27 @@ def main():help="Max TTS requests per second (default: 30, quota is 2x1000/min)")parser.add_argument("--gcs-upload", type=str, default=None,help="GCS path to upload dataset (e.g. gs://cactus-dataset/tool_calls)")+ parser.add_argument("--batch-size", type=int, default=5000,+ help="Rows per batch when using --gcs-upload (default: 500)")args = parser.parse_args()- combined, existing_ds = _load_text_dataset(args.output, args.max_samples)- needs_tts = _find_rows_needing_tts(combined, existing_ds, args.output)- audio_data, voice_names = _recover_existing_audio(existing_ds, len(combined), needs_tts, args.output)- _synthesize_missing(combined, needs_tts, audio_data, voice_names, args.workers, args.rate_limit, args.output)- _backfill_voice_names(voice_names)- _build_and_save(combined, audio_data, voice_names, args.output)+ output_path = args.output++ logger.info("Loading and combining text datasets...")+ combined = load_and_combine()+ if args.max_samples:+ combined = combined.select(range(min(args.max_samples, len(combined))))+ logger.info(f"Text dataset: {len(combined)} rows")if args.gcs_upload:- _upload_to_gcs(args.output, args.gcs_upload)+ total_rows = _process_batched(+ combined, args.batch_size, args.workers, args.rate_limit,+ output_path, args.gcs_upload,+ )+ else:+ total_rows = _process_local(combined, args.workers, args.rate_limit, output_path)++ logger.info(f"Pipeline complete: {total_rows} rows")if __name__ == "__main__":diff --git a/src/cli.py b/src/cli.pyindex aa4f802..15a909e 100644--- a/src/cli.py+++ b/src/cli.py@@ -70,6 +70,8 @@ def main():help="Max encoder sequence length (default: 256)")p.add_argument("--max-dec-len", type=int, default=1024,help="Max decoder sequence length (default: 1024)")+ p.add_argument("--batch-size", type=int, default=None,+ help="Process in batches of this size, uploading shards to GCS incrementally")p = sub.add_parser("run", add_help=False)p.add_argument("--checkpoint", type=str, required=True)diff --git a/src/data.py b/src/data.pyindex 3353430..45a313a 100644--- a/src/data.py+++ b/src/data.py@@ -46,10 +46,13 @@ def _load_unified_dataset():if os.path.exists(LOCAL_UNIFIED_DIR) and any(f.endswith(".arrow") for f in os.listdir(LOCAL_UNIFIED_DIR)):- ds = load_from_disk(LOCAL_UNIFIED_DIR)- print(f"Loaded unified dataset from {LOCAL_UNIFIED_DIR} ({len(ds)} rows)")- _unified_dataset_cache = _set_audio_backend(ds)- return _unified_dataset_cache+ try:+ ds = load_from_disk(LOCAL_UNIFIED_DIR)+ print(f"Loaded unified dataset from {LOCAL_UNIFIED_DIR} ({len(ds)} rows)")+ _unified_dataset_cache = _set_audio_backend(ds)+ return _unified_dataset_cache+ except Exception:+ print(f"Local dataset at {LOCAL_UNIFIED_DIR} is incomplete, trying GCS...")try:ds = load_from_disk(GCS_DATASET_PATH)@@ -256,6 +259,27 @@ def _gcs_cache_upload(cache_id, suffixes):)+def _gcs_download_shards(cache_id, n_shards, shard_suffixes):+ """Download sharded .npy files from GCS. Returns True if all found."""+ import subprocess+ os.makedirs(CACHE_DIR, exist_ok=True)+ srcs = []+ for suffix in shard_suffixes:+ for i in range(n_shards):+ srcs.append(f"{GCS_CACHE_PATH}/{cache_id}{suffix}_{i:05d}.npy")+ if not srcs:+ return True+ subprocess.run(+ ["gcloud", "storage", "cp"] + srcs + [CACHE_DIR + "/"],+ capture_output=True, text=True,+ )+ for suffix in shard_suffixes:+ for i in range(n_shards):+ if not os.path.exists(os.path.join(CACHE_DIR, f"{cache_id}{suffix}_{i:05d}.npy")):+ return False+ return True++def load_tool_calls(split="train", max_samples=None):"""Load tool-calling dataset, splitting 90/10 for train/val."""ds = _load_unified_dataset()@@ -316,7 +340,7 @@ def _load_cache_metadata(split):if os.path.exists(meta_path):with open(meta_path) as f:return _json.load(f)- # Try GCS+import subprocessos.makedirs(CACHE_DIR, exist_ok=True)gcs_path = f"{GCS_CACHE_PATH}/{split}_metadata.json"@@ -330,7 +354,7 @@ def _load_cache_metadata(split):return None-def prepare_tool_call_pairs(ds, tokenizer, max_enc_len=256, max_dec_len=1024):+def prepare_tool_call_pairs(ds, tokenizer, max_enc_len=256, max_dec_len=1024, batch_size=None):"""Prepare tool-call encoder-decoder pairs with <tool_call> task token.Encoder input: tokenize(query), truncated to max_enc_len.@@ -338,29 +362,47 @@ def prepare_tool_call_pairs(ds, tokenizer, max_enc_len=256, max_dec_len=1024):Decoder target: [<tool_call>, tools_tokens..., answer_tokens..., EOS]Loss mask: 1 only on answer + EOS positions (not tools prefix or padding).- Returns (enc_inputs, dec_inputs, dec_targets, loss_mask).+ When batch_size is set, produces per-batch shard files uploaded to GCS+ incrementally. Returns (None, None, None, None, kept_indices).+ When batch_size is None, returns (enc_inputs, dec_inputs, dec_targets,+ loss_mask, kept_indices) as before."""cache_id = _cache_key("toolcall", len(ds), max_enc_len, max_dec_len)cache_path = os.path.join(CACHE_DIR, cache_id)- tc_suffixes = ["_enc.npy", "_dec_in.npy", "_dec_tgt.npy", "_loss_mask.npy", "_kept_idx.npy"]- def _load_tc_cache():- return (- np.load(cache_path + "_enc.npy"),- np.load(cache_path + "_dec_in.npy"),- np.load(cache_path + "_dec_tgt.npy"),- np.load(cache_path + "_loss_mask.npy"),- np.load(cache_path + "_kept_idx.npy"),- )+ if batch_size is None:+ tc_suffixes = ["_enc.npy", "_dec_in.npy", "_dec_tgt.npy", "_loss_mask.npy", "_kept_idx.npy"]++ def _load_tc_cache():+ return (+ np.load(cache_path + "_enc.npy"),+ np.load(cache_path + "_dec_in.npy"),+ np.load(cache_path + "_dec_tgt.npy"),+ np.load(cache_path + "_loss_mask.npy"),+ np.load(cache_path + "_kept_idx.npy"),+ )++ if os.path.exists(cache_path + "_enc.npy"):+ print(f"Loading cached tool-call data ({cache_id})...")+ return _load_tc_cache()- if os.path.exists(cache_path + "_enc.npy"):- print(f"Loading cached tool-call data ({cache_id})...")- return _load_tc_cache()+ if _gcs_cache_download(cache_id, tc_suffixes):+ print(f"Downloaded tool-call cache from GCS ({cache_id})...")+ return _load_tc_cache()- if _gcs_cache_download(cache_id, tc_suffixes):- print(f"Downloaded tool-call cache from GCS ({cache_id})...")- return _load_tc_cache()+ if batch_size is not None:+ manifest_path = cache_path + "_manifest.json"+ if os.path.exists(manifest_path):+ kept_indices = np.load(cache_path + "_kept_idx.npy")+ print(f"Loading cached sharded tool-call data ({cache_id})...")+ return None, None, None, None, kept_indices++ if _gcs_cache_download(cache_id, ["_manifest.json", "_kept_idx.npy"]):+ if os.path.exists(manifest_path):+ kept_indices = np.load(cache_path + "_kept_idx.npy")+ print(f"Downloaded sharded tool-call cache from GCS ({cache_id})...")+ return None, None, None, None, kept_indicespad_id = tokenizer.pad_token_ideos_id = tokenizer.eos_token_id@@ -396,50 +438,127 @@ def prepare_tool_call_pairs(ds, tokenizer, max_enc_len=256, max_dec_len=1024):all_ans_tokens = [tok for chunk in ans_results for tok in chunk]n = len(ds)- enc_inputs = np.full((n, max_enc_len), pad_id, dtype=np.int32)- dec_inputs = np.full((n, max_dec_len), pad_id, dtype=np.int32)- dec_targets = np.full((n, max_dec_len), pad_id, dtype=np.int32)- loss_mask = np.zeros((n, max_dec_len), dtype=np.float32)-- skipped = 0- for i in range(n):- e_tok = all_enc_tokens[i]- t_tok = all_tools_tokens[i]- a_tok = all_ans_tokens[i]+ def _fill_sample(j, e_tok, t_tok, a_tok, enc_arr, dec_in_arr, dec_tgt_arr, lm_arr):+ """Fill arrays at position j for one sample. Returns False if skipped."""prefix_len = 2 + len(t_tok)total_dec = prefix_len + len(a_tok) + 1-if total_dec > max_dec_len:available_for_tools = max_dec_len - 2 - len(a_tok) - 1if available_for_tools < 1:- skipped += 1- continue+ return Falset_tok = t_tok[:available_for_tools]prefix_len = 2 + len(t_tok)- total_dec = prefix_len + len(a_tok) + 1el = len(e_tok)- enc_inputs[i, :el] = e_tok+ enc_arr[j, :el] = e_tok- dec_inputs[i, 0] = eos_id- dec_inputs[i, 1] = tool_call_id+ dec_in_arr[j, 0] = eos_id+ dec_in_arr[j, 1] = tool_call_idtl = len(t_tok)if tl > 0:- dec_inputs[i, 2:2 + tl] = t_tok+ dec_in_arr[j, 2:2 + tl] = t_tokal = len(a_tok)if al > 0:- dec_inputs[i, prefix_len:prefix_len + al] = a_tok+ dec_in_arr[j, prefix_len:prefix_len + al] = a_tok- # Decoder target: [<tool_call>, tools..., answer..., EOS]- dec_targets[i, 0] = tool_call_id+ dec_tgt_arr[j, 0] = tool_call_idif tl > 0:- dec_targets[i, 1:1 + tl] = t_tok+ dec_tgt_arr[j, 1:1 + tl] = t_tokif al > 0:- dec_targets[i, prefix_len - 1:prefix_len - 1 + al] = a_tok- dec_targets[i, prefix_len - 1 + al] = eos_id+ dec_tgt_arr[j, prefix_len - 1:prefix_len - 1 + al] = a_tok+ dec_tgt_arr[j, prefix_len - 1 + al] = eos_id++ lm_arr[j, prefix_len - 1:prefix_len - 1 + al + 1] = 1.0+ return True++ os.makedirs(CACHE_DIR, exist_ok=True)++ if batch_size is not None:+ all_kept_indices = []+ shard_counts = []+ shard_idx = 0+ total_skipped = 0++ for batch_start in range(0, n, batch_size):+ batch_end = min(batch_start + batch_size, n)+ batch_n = batch_end - batch_start++ enc_batch = np.full((batch_n, max_enc_len), pad_id, dtype=np.int32)+ dec_in_batch = np.full((batch_n, max_dec_len), pad_id, dtype=np.int32)+ dec_tgt_batch = np.full((batch_n, max_dec_len), pad_id, dtype=np.int32)+ loss_batch = np.zeros((batch_n, max_dec_len), dtype=np.float32)++ skipped = 0+ for j in range(batch_n):+ i = batch_start + j+ if not _fill_sample(j, all_enc_tokens[i], all_tools_tokens[i],+ all_ans_tokens[i], enc_batch, dec_in_batch,+ dec_tgt_batch, loss_batch):+ skipped += 1++ if skipped > 0:+ keep = enc_batch[:, 0] != pad_id+ kept_in_batch = np.where(keep)[0]+ enc_batch = enc_batch[keep]+ dec_in_batch = dec_in_batch[keep]+ dec_tgt_batch = dec_tgt_batch[keep]+ loss_batch = loss_batch[keep]+ all_kept_indices.extend((batch_start + kept_in_batch).tolist())+ total_skipped += skipped+ else:+ all_kept_indices.extend(range(batch_start, batch_end))++ if len(enc_batch) == 0:+ continue++ shard_suffixes = []+ for suffix, arr in [("_enc", enc_batch), ("_dec_in", dec_in_batch),+ ("_dec_tgt", dec_tgt_batch), ("_loss_mask", loss_batch)]:+ shard_suffix = f"{suffix}_{shard_idx:05d}.npy"+ np.save(os.path.join(CACHE_DIR, f"{cache_id}{shard_suffix}"), arr)+ shard_suffixes.append(shard_suffix)++ _gcs_cache_upload(cache_id, shard_suffixes)+ for s in shard_suffixes:+ fpath = os.path.join(CACHE_DIR, f"{cache_id}{s}")+ if os.path.exists(fpath):+ os.remove(fpath)++ shard_counts.append(len(enc_batch))+ shard_idx += 1++ if total_skipped > 0:+ print(f" Skipped {total_skipped} examples (too long for max_dec_len={max_dec_len})")++ kept_indices = np.array(all_kept_indices, dtype=np.int64)+ np.save(cache_path + "_kept_idx.npy", kept_indices)++ manifest = {+ "n_shards": shard_idx,+ "shard_counts": shard_counts,+ "total_kept": len(kept_indices),+ }+ manifest_path = cache_path + "_manifest.json"+ with open(manifest_path, "w") as f:+ _json.dump(manifest, f)++ _gcs_cache_upload(cache_id, ["_manifest.json", "_kept_idx.npy"])+ print(f"Cached {len(kept_indices):,} tool-call pairs in {shard_idx} shards ({cache_id})")++ return None, None, None, None, kept_indices++ enc_inputs = np.full((n, max_enc_len), pad_id, dtype=np.int32)+ dec_inputs = np.full((n, max_dec_len), pad_id, dtype=np.int32)+ dec_targets = np.full((n, max_dec_len), pad_id, dtype=np.int32)+ loss_mask = np.zeros((n, max_dec_len), dtype=np.float32)- loss_mask[i, prefix_len - 1:prefix_len - 1 + al + 1] = 1.0+ skipped = 0+ for i in range(n):+ if not _fill_sample(i, all_enc_tokens[i], all_tools_tokens[i],+ all_ans_tokens[i], enc_inputs, dec_inputs,+ dec_targets, loss_mask):+ skipped += 1if skipped > 0:keep = enc_inputs[:, 0] != pad_id@@ -452,12 +571,12 @@ def prepare_tool_call_pairs(ds, tokenizer, max_enc_len=256, max_dec_len=1024):else:kept_indices = np.arange(n, dtype=np.int64)- os.makedirs(CACHE_DIR, exist_ok=True)np.save(cache_path + "_enc.npy", enc_inputs)np.save(cache_path + "_dec_in.npy", dec_inputs)np.save(cache_path + "_dec_tgt.npy", dec_targets)np.save(cache_path + "_loss_mask.npy", loss_mask)np.save(cache_path + "_kept_idx.npy", kept_indices)+ tc_suffixes = ["_enc.npy", "_dec_in.npy", "_dec_tgt.npy", "_loss_mask.npy", "_kept_idx.npy"]_gcs_cache_upload(cache_id, tc_suffixes)print(f"Cached {len(enc_inputs):,} tool-call pairs to {CACHE_DIR}/{cache_id}")@@ -550,10 +669,8 @@ def compute_mel_spectrogram(audio, sr=16000, n_mels=80, n_fft=400, hop_length=16from scipy.signal import windows as scipy_windowsfrom scipy.fft import rfft- # Pre-emphasisaudio = np.append(audio[0], audio[1:] - 0.97 * audio[:-1])- # STFTwindow = scipy_windows.hann(n_fft, sym=False).astype(np.float32)num_frames = 1 + (len(audio) - n_fft) // hop_lengthif num_frames <= 0:@@ -567,7 +684,6 @@ def compute_mel_spectrogram(audio, sr=16000, n_mels=80, n_fft=400, hop_length=16frames = frames * windowspectrum = np.abs(rfft(frames, n=n_fft, axis=-1)) ** 2- # Mel filterbankfmin, fmax = 0.0, sr / 2.0mel_low = 2595.0 * np.log10(1.0 + fmin / 700.0)mel_high = 2595.0 * np.log10(1.0 + fmax / 700.0)@@ -590,52 +706,164 @@ def compute_mel_spectrogram(audio, sr=16000, n_mels=80, n_fft=400, hop_length=16return log_mel.astype(np.float32)-def precompute_mels(kept_indices, n_mels=80, max_mel_len=1024, cache_id_prefix=""):- """Precompute mel spectrograms -> write to disk via writable memmap.+def precompute_mels(kept_indices, n_mels=80, max_mel_len=1024, cache_id_prefix="", batch_size=None):+ """Precompute mel spectrograms.- Creates {cache_id}_mels.npy of shape (N, max_mel_len, n_mels) float32.- Processes one sample at a time, writing to the memmap in-place.- Uploads to GCS when done. Returns the cache_id.+ When batch_size is None: write a single (N, max_mel_len, n_mels) memmap file.+ When batch_size is set: produce per-batch shard .npy files, upload each to GCS.+ Returns the cache_id."""n_samples = len(kept_indices)cache_id = _mel_cache_key(cache_id_prefix, n_samples, n_mels, max_mel_len)cache_path = os.path.join(CACHE_DIR, cache_id)- mel_file = cache_path + "_mels.npy"- if os.path.exists(mel_file):- print(f" Mel cache already exists ({cache_id})")+ if batch_size is None:+ mel_file = cache_path + "_mels.npy"++ if os.path.exists(mel_file):+ print(f" Mel cache already exists ({cache_id})")+ return cache_id++ if _gcs_cache_download(cache_id, ["_mels.npy"]):+ print(f" Downloaded mel cache from GCS ({cache_id})")+ return cache_id++ os.makedirs(CACHE_DIR, exist_ok=True)+ shape = (n_samples, max_mel_len, n_mels)+ fp = np.lib.format.open_memmap(mel_file, mode='w+', dtype=np.float32, shape=shape)++ print(f" Precomputing {n_samples} mel spectrograms (n_mels={n_mels}, max_mel_len={max_mel_len})...")+ for i, idx in enumerate(tqdm(kept_indices, desc=" Computing mels")):+ audio, sr = load_audio_for_index(int(idx))+ if audio is None:+ continue+ mel = compute_mel_spectrogram(audio, sr=sr, n_mels=n_mels)+ if mel.shape[0] > max_mel_len:+ mel = mel[:max_mel_len]+ t = mel.shape[0]+ fp[i, :t, :] = mel++ del fp+ _gcs_cache_upload(cache_id, ["_mels.npy"])+ print(f" Cached mel spectrograms to {CACHE_DIR}/{cache_id}")return cache_id- if _gcs_cache_download(cache_id, ["_mels.npy"]):- print(f" Downloaded mel cache from GCS ({cache_id})")+ manifest_path = cache_path + "_mel_manifest.json"++ if os.path.exists(manifest_path):+ print(f" Mel shard cache already exists ({cache_id})")return cache_id+ if _gcs_cache_download(cache_id, ["_mel_manifest.json"]):+ if os.path.exists(manifest_path):+ print(f" Downloaded mel shard manifest from GCS ({cache_id})")+ return cache_id+os.makedirs(CACHE_DIR, exist_ok=True)- shape = (n_samples, max_mel_len, n_mels)- # Create the file with header so np.load(mmap_mode=...) works later- fp = np.lib.format.open_memmap(mel_file, mode='w+', dtype=np.float32, shape=shape)-- print(f" Precomputing {n_samples} mel spectrograms (n_mels={n_mels}, max_mel_len={max_mel_len})...")- for i, idx in enumerate(tqdm(kept_indices, desc=" Computing mels")):- audio, sr = load_audio_for_index(int(idx))- if audio is None:- # Leave zeros for missing audio- continue- mel = compute_mel_spectrogram(audio, sr=sr, n_mels=n_mels)- if mel.shape[0] > max_mel_len:- mel = mel[:max_mel_len]- t = mel.shape[0]- fp[i, :t, :] = mel+ shard_counts = []+ shard_idx = 0++ print(f" Precomputing {n_samples} mel spectrograms in shards of {batch_size}...")+ for batch_start in range(0, n_samples, batch_size):+ batch_end = min(batch_start + batch_size, n_samples)+ batch_indices = kept_indices[batch_start:batch_end]+ batch_n = len(batch_indices)++ mel_batch = np.zeros((batch_n, max_mel_len, n_mels), dtype=np.float32)++ for j, idx in enumerate(tqdm(batch_indices, desc=f" Shard {shard_idx}", leave=False)):+ audio, sr = load_audio_for_index(int(idx))+ if audio is None:+ continue+ mel = compute_mel_spectrogram(audio, sr=sr, n_mels=n_mels)+ if mel.shape[0] > max_mel_len:+ mel = mel[:max_mel_len]+ t = mel.shape[0]+ mel_batch[j, :t, :] = mel++ shard_suffix = f"_mels_{shard_idx:05d}.npy"+ shard_path = os.path.join(CACHE_DIR, f"{cache_id}{shard_suffix}")+ np.save(shard_path, mel_batch)++ _gcs_cache_upload(cache_id, [shard_suffix])+ if os.path.exists(shard_path):+ os.remove(shard_path)++ shard_counts.append(batch_n)+ shard_idx += 1++ manifest = {+ "n_shards": shard_idx,+ "shard_counts": shard_counts,+ "total_samples": n_samples,+ }+ with open(manifest_path, "w") as f:+ _json.dump(manifest, f)- del fp # flush to disk- _gcs_cache_upload(cache_id, ["_mels.npy"])- print(f" Cached mel spectrograms to {CACHE_DIR}/{cache_id}")+ _gcs_cache_upload(cache_id, ["_mel_manifest.json"])+ print(f" Cached mel spectrograms in {shard_idx} shards ({cache_id})")return cache_id+class ShardedMmapArray:+ """Array-like wrapper over multiple .npy shard files with mmap support.++ Provides __len__ and __getitem__ (int, slice, numpy array) to transparently+ index across shards. Each shard is memory-mapped individually.+ """++ def __init__(self, paths, mmap_mode="r"):+ self._shards = [np.load(p, mmap_mode=mmap_mode) for p in paths]+ self._lengths = [len(s) for s in self._shards]+ self._cumulative = np.cumsum(self._lengths)+ self._total = int(self._cumulative[-1]) if len(self._cumulative) else 0++ def __len__(self):+ return self._total++ @property+ def shape(self):+ if not self._shards:+ return (0,)+ return (self._total,) + self._shards[0].shape[1:]++ @property+ def dtype(self):+ return self._shards[0].dtype if self._shards else np.float32++ def __getitem__(self, idx):+ if isinstance(idx, (int, np.integer)):+ if idx < 0:+ idx += self._total+ si = int(np.searchsorted(self._cumulative, idx, side="right"))+ offset = int(self._cumulative[si - 1]) if si > 0 else 0+ return self._shards[si][idx - offset]++ if isinstance(idx, np.ndarray):+ result = np.empty((len(idx),) + self._shards[0].shape[1:],+ dtype=self._shards[0].dtype)+ shard_ids = np.searchsorted(self._cumulative, idx, side="right")+ for si in range(len(self._shards)):+ mask = shard_ids == si+ if not mask.any():+ continue+ offset = int(self._cumulative[si - 1]) if si > 0 else 0+ local = idx[mask] - offset+ result[mask] = self._shards[si][local]+ return result++ if isinstance(idx, slice):+ start, stop, step = idx.indices(self._total)+ indices = np.arange(start, stop, step)+ return self[indices]++ raise TypeError(f"Unsupported index type: {type(idx)}")++def load_prepared_data(split, mmap=False):"""Load pre-tokenized .npy files. If mmap=True, returns memory-mapped arrays.+ Supports both single-file and sharded (manifest-based) caches.Tries local cache first, then GCS download. Raises FileNotFoundErrorif not found (no fallback tokenization — run 'needle tokenize' first).@@ -650,9 +878,47 @@ def load_prepared_data(split, mmap=False):text_cache_id = meta["text_cache_id"]cache_path = os.path.join(CACHE_DIR, text_cache_id)- tc_suffixes = ["_enc.npy", "_dec_in.npy", "_dec_tgt.npy", "_loss_mask.npy", "_kept_idx.npy"]+ manifest_path = cache_path + "_manifest.json"++ if not os.path.exists(manifest_path):+ _gcs_cache_download(text_cache_id, ["_manifest.json"])++ if os.path.exists(manifest_path):+ with open(manifest_path) as f:+ manifest = _json.load(f)+ n_shards = manifest["n_shards"]++ if not os.path.exists(cache_path + "_kept_idx.npy"):+ _gcs_cache_download(text_cache_id, ["_kept_idx.npy"])++ shard_suffixes = ["_enc", "_dec_in", "_dec_tgt", "_loss_mask"]+ _gcs_download_shards(text_cache_id, n_shards, shard_suffixes)++ def _shard_paths(suffix):+ return [os.path.join(CACHE_DIR, f"{text_cache_id}{suffix}_{i:05d}.npy")+ for i in range(n_shards)]++ mmap_mode = "r" if mmap else None+ if mmap:+ result = {+ "enc_inputs": ShardedMmapArray(_shard_paths("_enc"), mmap_mode="r"),+ "dec_inputs": ShardedMmapArray(_shard_paths("_dec_in"), mmap_mode="r"),+ "dec_targets": ShardedMmapArray(_shard_paths("_dec_tgt"), mmap_mode="r"),+ "loss_mask": ShardedMmapArray(_shard_paths("_loss_mask"), mmap_mode="r"),+ }+ else:+ result = {+ "enc_inputs": np.concatenate([np.load(p) for p in _shard_paths("_enc")]),+ "dec_inputs": np.concatenate([np.load(p) for p in _shard_paths("_dec_in")]),+ "dec_targets": np.concatenate([np.load(p) for p in _shard_paths("_dec_tgt")]),+ "loss_mask": np.concatenate([np.load(p) for p in _shard_paths("_loss_mask")]),+ }++ result["kept_indices"] = np.load(cache_path + "_kept_idx.npy", mmap_mode=mmap_mode)+ result["mel_cache_id"] = meta.get("mel_cache_id")+ return result- # Try local, then GCS+ tc_suffixes = ["_enc.npy", "_dec_in.npy", "_dec_tgt.npy", "_loss_mask.npy", "_kept_idx.npy"]if not os.path.exists(cache_path + "_enc.npy"):if not _gcs_cache_download(text_cache_id, tc_suffixes):raise FileNotFoundError(@@ -671,10 +937,32 @@ def load_prepared_data(split, mmap=False):def load_prepared_mels(mel_cache_id, mmap=False):- """Load precomputed mel .npy file, optionally memory-mapped."""+ """Load precomputed mel .npy file(s), optionally memory-mapped.++ Supports both single-file and sharded (manifest-based) caches.+ """cache_path = os.path.join(CACHE_DIR, mel_cache_id)- mel_file = cache_path + "_mels.npy"+ manifest_path = cache_path + "_mel_manifest.json"++ if not os.path.exists(manifest_path):+ _gcs_cache_download(mel_cache_id, ["_mel_manifest.json"])+ if os.path.exists(manifest_path):+ with open(manifest_path) as f:+ manifest = _json.load(f)+ n_shards = manifest["n_shards"]++ _gcs_download_shards(mel_cache_id, n_shards, ["_mels"])++ shard_paths = [os.path.join(CACHE_DIR, f"{mel_cache_id}_mels_{i:05d}.npy")+ for i in range(n_shards)]++ if mmap:+ return ShardedMmapArray(shard_paths, mmap_mode="r")+ else:+ return np.concatenate([np.load(p) for p in shard_paths])++ mel_file = cache_path + "_mels.npy"if not os.path.exists(mel_file):if not _gcs_cache_download(mel_cache_id, ["_mels.npy"]):raise FileNotFoundError(diff --git a/src/tokenize_data.py b/src/tokenize_data.pyindex fccde4e..9a1740e 100644--- a/src/tokenize_data.py+++ b/src/tokenize_data.py@@ -49,45 +49,40 @@ def _clear_local_caches():def tokenize(args):- # 1. Clear existing cachesprint("=== Clearing existing caches ===")_clear_gcs_caches()_clear_local_caches()- # 2. Train tokenizer and upload to GCSprint("\n=== Training tokenizer ===")train_tokenizer(max_samples=args.max_samples, force=True)upload_tokenizer_to_gcs()- # 3. Load tokenizertokenizer = get_tokenizer()- # 4. Tokenize text data + precompute mels (train + val)print("\n=== Tokenizing text data + precomputing mels ===")max_enc_len = getattr(args, "max_enc_len", 256)max_dec_len = getattr(args, "max_dec_len", 1024)n_mels = getattr(args, "n_mels", 80)max_mel_len = getattr(args, "max_mel_len", 1024)+ batch_size = getattr(args, "batch_size", 5000)for split in ("train", "val"):print(f"\n--- {split} split ---")ds = load_tool_calls(split=split, max_samples=args.max_samples)_, _, _, _, kept_indices = prepare_tool_call_pairs(- ds, tokenizer, max_enc_len=max_enc_len, max_dec_len=max_dec_len+ ds, tokenizer, max_enc_len=max_enc_len, max_dec_len=max_dec_len,+ batch_size=batch_size,)text_cache_id = _cache_key("toolcall", len(ds), max_enc_len, max_dec_len)- # Precompute mel spectrogramsmel_cache_id = precompute_mels(kept_indices, n_mels=n_mels, max_mel_len=max_mel_len,- cache_id_prefix=split,+ cache_id_prefix=split, batch_size=batch_size,)- # Save metadata for train.py to find caches_save_cache_metadata(split, text_cache_id, mel_cache_id, len(kept_indices),max_enc_len, max_dec_len, n_mels, max_mel_len)- # 5. Optionally clean up local cacheif args.cleanup and os.path.exists(CACHE_DIR):print(f"\n=== Cleaning up {CACHE_DIR}/ ===")shutil.rmtree(CACHE_DIR)