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.
Bug fixes
HenryNdubuaku5acb36ad8c97
diff --git a/src/data.py b/src/data.pyindex 5d40484..b916035 100644--- a/src/data.py+++ b/src/data.py@@ -17,15 +17,38 @@ from datasets import Audio, load_from_diskfrom tqdm import tqdmimport sentencepiece as spm-CACHE_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), ".data_cache")-TOKENIZER_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "tokenizer")+_PROJECT_ROOT = os.path.dirname(os.path.dirname(__file__))+_DISK_CACHE_DIR = os.path.join(_PROJECT_ROOT, ".data_cache")+TOKENIZER_DIR = os.path.join(_PROJECT_ROOT, "tokenizer")TOKENIZER_PREFIX = os.path.join(TOKENIZER_DIR, "needle")-LOCAL_UNIFIED_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data", "tool_calls_unified")+LOCAL_UNIFIED_DIR = os.path.join(_PROJECT_ROOT, "data", "tool_calls_unified")GCS_DATASET_PATH = "gs://cactus-dataset/tool_calls"+_MIN_SHM_BYTES = 200 * 1024**3+++def _pick_cache_dir():+ """Use /dev/shm (tmpfs/RAM) when available and large enough, else disk."""+ shm = "/dev/shm"+ if os.path.isdir(shm):+ try:+ st = os.statvfs(shm)+ avail = st.f_bavail * st.f_frsize+ if avail >= _MIN_SHM_BYTES:+ d = os.path.join(shm, "needle_cache")+ os.makedirs(d, exist_ok=True)+ return d+ except OSError:+ pass+ os.makedirs(_DISK_CACHE_DIR, exist_ok=True)+ return _DISK_CACHE_DIR+++CACHE_DIR = _pick_cache_dir()+PAD_ID = 0EOS_ID = 1-BOS_ID = 2 # reserved for SentencePiece, unused at runtime (EOS_ID serves as SOS)+BOS_ID = 2UNK_ID = 3TOOL_CALL_ID = 4TRANSCRIBE_ID = 5@@ -631,6 +654,72 @@ def load_tool_call_audio(split="train", max_samples=None):return indices+_GCS_SHARD_ROWS = 5000+_GCS_N_SHARDS = 19+_shard_cache = {}+++def _load_shard(shard_idx):+ """Load a single arrow shard, from local or GCS. Caches in memory."""+ if shard_idx in _shard_cache:+ return _shard_cache[shard_idx]++ fname = f"data-{shard_idx:05d}-of-{_GCS_N_SHARDS:05d}.arrow"++ local_path = os.path.join(LOCAL_UNIFIED_DIR, fname)+ if os.path.exists(local_path):+ import pyarrow as pa+ source = pa.memory_map(local_path, "r")+ try:+ reader = pa.ipc.open_file(source)+ except pa.lib.ArrowInvalid:+ source.seek(0)+ reader = pa.ipc.open_stream(source)+ tbl = reader.read_all()+ from datasets import Dataset+ ds = Dataset(tbl)+ ds = _set_audio_backend(ds)+ _shard_cache[shard_idx] = ds+ return ds++ import subprocess+ shm_dir = os.path.join(CACHE_DIR, "arrow_shards")+ os.makedirs(shm_dir, exist_ok=True)+ dest = os.path.join(shm_dir, fname)+ if not os.path.exists(dest):+ gcs_src = f"{GCS_DATASET_PATH}/{fname}"+ subprocess.run(+ ["gcloud", "storage", "cp", gcs_src, dest],+ capture_output=True, text=True,+ )+ if not os.path.exists(dest):+ raise FileNotFoundError(f"Failed to download shard {fname} from GCS")++ import pyarrow as pa+ source = pa.memory_map(dest, "r")+ try:+ reader = pa.ipc.open_file(source)+ except pa.lib.ArrowInvalid:+ source.seek(0)+ reader = pa.ipc.open_stream(source)+ tbl = reader.read_all()+ from datasets import Dataset+ ds = Dataset(tbl)+ ds = _set_audio_backend(ds)+ _shard_cache[shard_idx] = ds+ return ds+++def _load_example_by_index(idx):+ """Load a single example by global index, downloading only the needed shard."""+ shard_idx = idx // _GCS_SHARD_ROWS+ local_idx = idx % _GCS_SHARD_ROWS+ shard = _load_shard(shard_idx)+ if local_idx >= len(shard):+ raise IndexError(f"Index {idx} out of range (shard {shard_idx} has {len(shard)} rows)")+ return shard[local_idx]++def load_audio_for_index(idx):"""Load and decode audio for a single dataset index.@@ -639,8 +728,7 @@ def load_audio_for_index(idx):import ioimport soundfile as sf- ds = _load_unified_dataset()- ex = ds[idx]+ ex = _load_example_by_index(idx)audio_val = ex.get("audio")if audio_val is None:return None, None@@ -662,10 +750,10 @@ def load_audio_for_index(idx):def load_example_with_audio(idx):"""Load a dataset example with decoded audio for eval use.+ Downloads only the needed arrow shard (~1-4GB) instead of the full dataset (~35GB).Returns dict with {query, answers, tools, audio_array, sampling_rate}."""- ds = _load_unified_dataset()- ex = ds[idx]+ ex = _load_example_by_index(idx)audio, sr = load_audio_for_index(idx)return {"query": ex["query"],diff --git a/src/model.py b/src/model.pyindex 65bdcac..bc0c468 100644--- a/src/model.py+++ b/src/model.py@@ -217,7 +217,12 @@ class MemoryMixerEncoder(nn.Module):x = x.astype(dt)s_base = self.param("memory_slots", jinit.normal(stddev=0.02), (1, cfg.num_memory_slots, cfg.d_model))- x_pool = jnp.mean(x, axis=1) # (B, d)+ if mask is not None:+ # mask: (B, 1, 1, T) -> (B, T)+ pool_mask = mask[:, 0, 0, :x.shape[1]]+ x_pool = jnp.sum(x * pool_mask[:, :, None], axis=1) / jnp.maximum(pool_mask.sum(axis=1, keepdims=True), 1.0)+ else:+ x_pool = jnp.mean(x, axis=1) # (B, d)s_bias = nn.Dense(cfg.d_model, dtype=dt, use_bias=False, kernel_init=jinit.zeros, name="slot_init")(x_pool)s = jnp.broadcast_to(s_base.astype(dt), (x.shape[0], cfg.num_memory_slots, cfg.d_model)) + s_bias[:, None, :]diff --git a/src/run.py b/src/run.pyindex eb3cb9b..f029414 100644--- a/src/run.py+++ b/src/run.py@@ -52,7 +52,7 @@ def generate(model, params, tokenizer, query, tools="[]", max_gen_len=512, seed="""Generate tool-call output.Encoder: query only.- Decoder: prefilled with [BOS, <tool_call>, tools_tokens...], then greedy decode.+ Decoder: prefilled with [EOS, <tool_call>, tools_tokens...], then greedy decode."""enc_tokens = tokenizer.encode(query)enc_input = jnp.array([enc_tokens])diff --git a/src/train.py b/src/train.pyindex 0b26e4a..65ea052 100644--- a/src/train.py+++ b/src/train.py@@ -889,9 +889,7 @@ def train(args):from .run import generate, generate_from_audiotp = measure_throughput(eval_model, eval_params, tokenizer, num_runs=5)- from .data import _load_unified_dataset- _ds_full = _load_unified_dataset()- _val_start = int(len(_ds_full) * 0.9)+ _val_start = len(enc_inputs)val_kept = val_data["kept_indices"]n_eval_samples = min(3, len(val_kept))step = max(1, len(val_kept) // n_eval_samples)