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.
updates
HenryNdubuaku56d051ed8201
diff --git a/src/export.py b/src/export.pyindex d088c7d..9be4e8d 100644--- a/src/export.py+++ b/src/export.py@@ -38,29 +38,32 @@ def export_submodel(checkpoint_path, d_prime, output_path):d_model = config.d_modeld_ff = config.d_ff+ def _target(size):+ """Map original dimension to sliced dimension."""+ if size == d_model:+ return d_prime+ if size == d_ff:+ return d_ff_prime+ if size == kv_dim:+ return kv_dim_prime+ return size+def slice_leaf(key_path, leaf):arr = np.asarray(leaf)if arr.ndim == 1:- # Norm scales: shape (d_model,)- return arr[:d_prime]+ return arr[:_target(arr.shape[0])]if arr.ndim == 3:- # Memory slots: shape (1, M, d_model)+ if arr.shape[0] > 1:+ _, in_ch, out_ch = arr.shape+ r_in = in_ch if in_ch == config.n_mels else _target(in_ch)+ r_out = _target(out_ch)+ return arr[:, :r_in, :r_out]return arr[:, :, :d_prime]if arr.ndim == 2:rows, cols = arr.shape- # Determine slice for each axis based on original size- def _target(size):- if size == d_model:- return d_prime- if size == d_ff:- return d_ff_prime- if size == kv_dim:- return kv_dim_prime- return size # vocab, num_memory_slots, etc.-r = _target(rows)c = _target(cols)return arr[:r, :c]diff --git a/src/model.py b/src/model.pyindex 15bd222..d29f084 100644--- a/src/model.py+++ b/src/model.py@@ -1,6 +1,7 @@import mathfrom dataclasses import dataclass+import jaximport jax.numpy as jnpimport jax.nn.initializers as jinitimport flax.linen as nn@@ -304,15 +305,59 @@ class Decoder(nn.Module):return x-class MelProjection(nn.Module):- """Project mel spectrogram features to model dimension."""+class ConvSubsampling(nn.Module):+ """Whisper-style convolutional frontend: two Conv1d layers with GELU, 4x temporal downsampling."""d_model: int+ n_mels: intdtype: jnp.dtype = jnp.bfloat16@nn.compactdef __call__(self, mel):- return nn.Dense(self.d_model, dtype=self.dtype, use_bias=True,- kernel_init=default_init(), name="proj")(mel)+ # mel: (B, T, n_mels)+ x = nn.Conv(features=self.d_model, kernel_size=(3,), strides=(2,),+ padding='SAME', use_bias=True, kernel_init=default_init(),+ dtype=self.dtype, name="conv1")(mel)+ x = nn.gelu(x)+ x = nn.Conv(features=self.d_model, kernel_size=(3,), strides=(2,),+ padding='SAME', use_bias=True, kernel_init=default_init(),+ dtype=self.dtype, name="conv2")(x)+ x = nn.gelu(x)+ return x+++class SpecAugment(nn.Module):+ """SpecAugment: time and frequency masking for speech regularization."""+ num_time_masks: int = 2+ max_time_width: int = 100+ num_freq_masks: int = 1+ max_freq_width: int = 27++ @nn.compact+ def __call__(self, mel, deterministic=True):+ if deterministic:+ return mel+ # mel: (B, T, F)+ B, T, F = mel.shape+ rng = self.make_rng('specaugment')++ x = mel+ # Time masking+ for i in range(self.num_time_masks):+ rng, k1, k2 = jax.random.split(rng, 3)+ width = jax.random.randint(k1, (), 0, jnp.minimum(self.max_time_width, T))+ start = jax.random.randint(k2, (), 0, jnp.maximum(T - width, 1))+ time_mask = (jnp.arange(T) >= start) & (jnp.arange(T) < start + width)+ x = x * (1.0 - time_mask[None, :, None].astype(x.dtype))++ # Frequency masking+ for i in range(self.num_freq_masks):+ rng, k1, k2 = jax.random.split(rng, 3)+ width = jax.random.randint(k1, (), 0, jnp.minimum(self.max_freq_width, F))+ start = jax.random.randint(k2, (), 0, jnp.maximum(F - width, 1))+ freq_mask = (jnp.arange(F) >= start) & (jnp.arange(F) < start + width)+ x = x * (1.0 - freq_mask[None, None, :].astype(x.dtype))++ return xclass EncoderDecoderTransformer(nn.Module):@@ -322,7 +367,8 @@ class EncoderDecoderTransformer(nn.Module):def setup(self):self.embedding = nn.Embed(self.config.vocab_size, self.config.d_model, embedding_init=jinit.normal(stddev=0.02))self.embed_scale = math.sqrt(self.config.d_model)- self.mel_proj = MelProjection(self.config.d_model, self.config.jax_dtype)+ self.conv_subsample = ConvSubsampling(self.config.d_model, self.config.n_mels, self.config.jax_dtype)+ self.spec_augment = SpecAugment()self.encoder = MemoryMixerEncoder(self.config)self.decoder = Decoder(self.config)@@ -339,9 +385,24 @@ class EncoderDecoderTransformer(nn.Module):"""Backward-compatible alias for encode_text."""return self.encode_text(src, src_mask=src_mask)- def encode_speech(self, mel, src_mask=None):- x = self.mel_proj(mel) * self.embed_scale- rope = self._rope(mel.shape[1])+ @staticmethod+ def _downsample_mask(mask, factor):+ """Downsample a padding mask by OR-pooling groups of `factor` frames."""+ if mask is None:+ return None+ # mask: (B, 1, 1, T)+ T = mask.shape[-1]+ pad = (factor - T % factor) % factor+ if pad > 0:+ mask = jnp.pad(mask, ((0, 0), (0, 0), (0, 0), (0, pad)))+ mask = mask.reshape(mask.shape[0], 1, 1, -1, factor).any(axis=-1)+ return mask++ def encode_speech(self, mel, src_mask=None, deterministic=True):+ mel = self.spec_augment(mel, deterministic=deterministic)+ x = self.conv_subsample(mel) * self.embed_scale+ src_mask = self._downsample_mask(src_mask, 4)+ rope = self._rope(x.shape[1])return self.encoder(x, mask=src_mask, rope=rope)def decode(self, tgt, encoder_out, self_mask=None, cross_mask=None):@@ -385,8 +446,8 @@ class EncoderDecoderTransformer(nn.Module):encoder_out = self.encode_text(src, src_mask=src_mask)return self._decode_with_aux(encoder_out, tgt, tgt_mask=tgt_mask, mrl_dims=mrl_dims)- def forward_speech_with_aux(self, mel, tgt, src_mask=None, tgt_mask=None, mrl_dims=None):- encoder_out = self.encode_speech(mel, src_mask=src_mask)+ def forward_speech_with_aux(self, mel, tgt, src_mask=None, tgt_mask=None, mrl_dims=None, deterministic=True):+ encoder_out = self.encode_speech(mel, src_mask=src_mask, deterministic=deterministic)return self._decode_with_aux(encoder_out, tgt, tgt_mask=tgt_mask, mrl_dims=mrl_dims)def init_all(self, src, tgt, mel):@@ -395,7 +456,7 @@ class EncoderDecoderTransformer(nn.Module):tgt_mask = make_causal_mask(tgt.shape[1]) & make_padding_mask(tgt, self.config.pad_token_id)text_out = self.encode_text(src, src_mask=src_mask)mel_mask = make_mel_padding_mask(mel)- speech_out = self.encode_speech(mel, src_mask=mel_mask)+ speech_out = self.encode_speech(mel, src_mask=mel_mask, deterministic=True)_ = self._decode_with_aux(text_out, tgt, tgt_mask=tgt_mask)_ = self._decode_with_aux(speech_out, tgt, tgt_mask=tgt_mask)return jnp.zeros(())diff --git a/src/run.py b/src/run.pyindex f4490f7..3d84a91 100644--- a/src/run.py+++ b/src/run.py@@ -114,7 +114,7 @@ def transcribe(model, params, tokenizer, audio_array, sr=16000, max_gen_len=128,src_mask = make_mel_padding_mask(mel_input)encoder_out = model.apply(- {"params": params}, mel_input, src_mask=src_mask, method="encode_speech"+ {"params": params}, mel_input, src_mask=src_mask, deterministic=True, method="encode_speech")tgt_mask = make_causal_mask(max_gen_len)diff --git a/src/train.py b/src/train.pyindex 45903e1..59e0063 100644--- a/src/train.py+++ b/src/train.py@@ -270,7 +270,7 @@ def _text_loss_fn(state, params, src, tgt_in, tgt_out, causal_mask):return _compute_loss(logits, slot_div, mrl_logits, tgt_out)-def _speech_loss_fn(state, params, mel, tgt_in, tgt_out, causal_mask):+def _speech_loss_fn(state, params, mel, tgt_in, tgt_out, causal_mask, rng):pad_id = 0src_mask = make_mel_padding_mask(mel)tgt_mask = causal_mask & make_padding_mask(tgt_in, pad_id)@@ -282,7 +282,9 @@ def _speech_loss_fn(state, params, mel, tgt_in, tgt_out, causal_mask):src_mask=src_mask,tgt_mask=tgt_mask,mrl_dims=_MRL_DIMS if _MRL_DIMS else None,+ deterministic=False,method="forward_speech_with_aux",+ rngs={"specaugment": rng},)return _compute_loss(logits, slot_div, mrl_logits, tgt_out)@@ -316,10 +318,10 @@ def _train_step_text_masked(state, ema_params, src, tgt_in, tgt_out, causal_maskreturn state, ema_params, loss, grad_norm-def _train_step_speech(state, ema_params, mel, tgt_in, tgt_out, causal_mask):+def _train_step_speech(state, ema_params, mel, tgt_in, tgt_out, causal_mask, rng):ema_decay = 0.999loss, grads = jax.value_and_grad(- lambda p: _speech_loss_fn(state, p, mel, tgt_in, tgt_out, causal_mask)+ lambda p: _speech_loss_fn(state, p, mel, tgt_in, tgt_out, causal_mask, rng))(state.params)grads = jax.lax.pmean(grads, axis_name="batch")loss = jax.lax.pmean(loss, axis_name="batch")@@ -329,11 +331,11 @@ def _train_step_speech(state, ema_params, mel, tgt_in, tgt_out, causal_mask):return state, ema_params, loss, grad_norm-def _train_step_speech_masked(state, ema_params, mel, tgt_in, tgt_out, causal_mask, prune_mask):+def _train_step_speech_masked(state, ema_params, mel, tgt_in, tgt_out, causal_mask, prune_mask, rng):"""Speech training step with fused mask application."""ema_decay = 0.999loss, grads = jax.value_and_grad(- lambda p: _speech_loss_fn(state, p, mel, tgt_in, tgt_out, causal_mask)+ lambda p: _speech_loss_fn(state, p, mel, tgt_in, tgt_out, causal_mask, rng))(state.params)grads = jax.lax.pmean(grads, axis_name="batch")loss = jax.lax.pmean(loss, axis_name="batch")@@ -406,6 +408,7 @@ def _make_speech_val_loss_fn(apply_fn):logits, _, _ = apply_fn({"params": params}, mel, tgt_in,src_mask=src_mask, tgt_mask=tgt_mask,+ deterministic=True,method="forward_speech_with_aux",)loss = optax.softmax_cross_entropy_with_integer_labels(logits.astype(jnp.float32), tgt_out)@@ -434,6 +437,10 @@ def _estimate_mrl_params(config, d_prime):d_ff = config.d_ff * d // config.d_modelm = config.num_memory_slots+ n_mels = config.n_mels+ # ConvSubsampling: conv1 (3*n_mels*d + d) + conv2 (3*d*d + d)+ conv_sub = 3 * n_mels * d + d + 3 * d * d + d+emb = v * dkv_dim = n_kv * head_dimattn = d * d + d * kv_dim * 2 + d * d@@ -442,7 +449,7 @@ def _estimate_mrl_params(config, d_prime):mixer_channel = d * d_ff * 3enc_block = attn + ffn + mixer_token + mixer_channeldec_block = attn * 2 + ffn- total = emb + n_enc * enc_block + n_dec * dec_block+ total = emb + conv_sub + n_enc * enc_block + n_dec * dec_blockreturn int(total)@@ -456,7 +463,7 @@ def train(args):num_devices = jax.local_device_count()no_speech = getattr(args, "no_speech", False)- speech_every = getattr(args, "speech_every", 3)+ speech_every_override = getattr(args, "speech_every", None)n_mels = getattr(args, "n_mels", 80)max_mel_len = getattr(args, "max_mel_len", 1024)@@ -563,6 +570,13 @@ def train(args):rng, init_rng = jax.random.split(rng)text_batches_per_epoch = len(enc_inputs) // effective_batch_size+ if speech_every_override is not None:+ speech_every = speech_every_override+ elif not no_speech and speech_mel is not None:+ speech_batches_available = len(speech_mel) // effective_batch_size+ speech_every = max(1, text_batches_per_epoch // max(1, speech_batches_available))+ else:+ speech_every = 1speech_batches_per_epoch = text_batches_per_epoch // speech_every if (not no_speech and speech_mel is not None) else 0num_batches = text_batches_per_epoch + speech_batches_per_epochtotal_steps = num_batches * args.epochs@@ -687,13 +701,16 @@ def train(args):sp_tgt_in_b = shard_batch(sp_tgt_in, num_devices)sp_tgt_out_b = shard_batch(sp_tgt_out, num_devices)+ rng, spec_rng = jax.random.split(rng)+ spec_rngs = jax.random.split(spec_rng, num_devices)+if prune_mask is not None:state, ema_params, sp_loss, sp_grad_norm = p_train_step_speech_masked(- state, ema_params, mel_b, sp_tgt_in_b, sp_tgt_out_b, causal_mask, prune_mask,+ state, ema_params, mel_b, sp_tgt_in_b, sp_tgt_out_b, causal_mask, prune_mask, spec_rngs,)else:state, ema_params, sp_loss, sp_grad_norm = p_train_step_speech(- state, ema_params, mel_b, sp_tgt_in_b, sp_tgt_out_b, causal_mask,+ state, ema_params, mel_b, sp_tgt_in_b, sp_tgt_out_b, causal_mask, spec_rngs,)speech_loss_val = float(sp_loss[0])speech_losses.append(speech_loss_val)@@ -732,7 +749,7 @@ def train(args):if speech_loss_val is not None:postfix["speech_loss"] = f"{speech_loss_val:.4f}"if epoch == weight_prune_epoch and not gradual_sparsify_done:- postfix["prune"] = f"{current_sparsity*100:.1f}%"+ postfix["sparsity"] = f"{current_sparsity*100:.1f}%"pbar.set_postfix(**postfix)if use_wandb: