Add GGUF weights, comparison charts, and updated model card
Browse filesFiles changed (11)
- .gitattributes+2
- README.mdAdded+32
- baseline_comparison.pngAdded
- config.jsonAdded+20
- external_model_comparison.pngAdded
- model.ggufAdded+3
- model.safetensorsAdded+3
- privoid_model.pyAdded+150
- routing_curve_test.pngAdded
- stage1_val_loss.pngAdded
- tokenizer.jsonAdded
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines333435363732 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textexternal_model_comparison.png filter=lfs diff=lfs merge=lfs -textmodel.gguf filter=lfs diff=lfs merge=lfs -text
1234567891011121314151617181920212223242526272829303132---license: apache-2.0language: [en]pipeline_tag: text-classificationtags:- llm-routing- router- from-scratch- small-language-model- on-device- privoid- gguf---
# Privoid Router (Privoid-Router-34M (from scratch))
Privoid Router is a highly optimized 34-million parameter routing model built entirely from scratch. It is designed to run locally with extremely low resource footprints to dynamically decide whether to answer a prompt using a cheap local SLM or delegate it to a frontier LLM API.
## Performance Comparison
Below is the comparative performance against baseline strategies on the test set:
| Metric | Random Routing | Privoid Router | Oracle (Perfect) ||---|---|---|---|| **AUC** | 0.500 | 0.754 | 1.000 || **APGR** | 0.500 | 0.720 | 1.000 || **CPT(50%)** | 50.0% | 22.6% | <10.0% || **CPT(80%)** | 80.0% | 47.3% | <20.0% |
### Formats Available- **PyTorch (`model.safetensors`)** for inference and fine-tuning pipelines.- **GGUF (`model.gguf`)** for direct integration with llama.cpp and lightweight edge setups.1234567891011121314151617181920{ "vocab_size": 16384, "d_model": 512, "n_layers": 8, "n_heads": 8, "ffn_dim": 1408, "max_pos": 1024, "architecture": "PrivoidRouter", "max_len": 512, "threshold": 0.3942009508609772, "label": "needs_frontier", "special_tokens": [ "[PAD]", "[UNK]", "[CLS]", "[SEP]", "[MASK]" ], "weak_ok_score": 4}123version https://git-lfs.github.com/spec/v1oid sha256:9afe34b9433ca1a62252f950c470192873c7af57780efe20573b39d188d5782bsize 137406688123version https://git-lfs.github.com/spec/v1oid sha256:a069646768d2d1f612b44644dbc09145239c1a4aba5d31ccaff867a57dacd56fsize 137408524123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150# Privoid model code, written from scratch in plain PyTorch (no pretrained weights).import mathimport torchimport torch.nn as nnimport torch.nn.functional as F
class RMSNorm(nn.Module): def __init__(self, dim, eps=1e-6): super().__init__() self.eps = eps self.weight = nn.Parameter(torch.ones(dim))
def forward(self, x): xf = x.float() xf = xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + self.eps) return (xf * self.weight.float()).type_as(x)
def build_rope(max_pos, head_dim, base=10000.0): inv = 1.0 / (base ** (torch.arange(0, head_dim, 2).float() / head_dim)) freqs = torch.outer(torch.arange(max_pos).float(), inv) return freqs.cos(), freqs.sin()
def apply_rope(x, cos, sin): T = x.shape[-2] cos, sin = cos[:T], sin[:T] x1, x2 = x.float().chunk(2, dim=-1) return torch.cat([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1).type_as(x)
class Attention(nn.Module): def __init__(self, d, n_heads, dropout): super().__init__() self.h = n_heads self.qkv = nn.Linear(d, 3 * d, bias=False) self.o = nn.Linear(d, d, bias=False) self.dropout = dropout
def forward(self, x, cos, sin, attn_mask=None): B, T, C = x.shape q, k, v = self.qkv(x).view(B, T, 3, self.h, C // self.h).permute(2, 0, 3, 1, 4).unbind(0) q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin) y = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask, dropout_p=self.dropout if self.training else 0.0) return self.o(y.transpose(1, 2).reshape(B, T, C))
class SwiGLU(nn.Module): def __init__(self, d, hidden): super().__init__() self.w1 = nn.Linear(d, hidden, bias=False) self.w3 = nn.Linear(d, hidden, bias=False) self.w2 = nn.Linear(hidden, d, bias=False)
def forward(self, x): return self.w2(F.silu(self.w1(x)) * self.w3(x))
class Block(nn.Module): def __init__(self, d, n_heads, ffn_dim, dropout): super().__init__() self.n1, self.n2 = RMSNorm(d), RMSNorm(d) self.attn = Attention(d, n_heads, dropout) self.mlp = SwiGLU(d, ffn_dim) self.drop = nn.Dropout(dropout)
def forward(self, x, cos, sin, attn_mask=None): x = x + self.drop(self.attn(self.n1(x), cos, sin, attn_mask)) return x + self.drop(self.mlp(self.n2(x)))
class PrivoidEncoder(nn.Module): """Bidirectional transformer encoder: RoPE + RMSNorm + SwiGLU, pre-norm."""
def __init__(self, cfg, dropout=0.0): super().__init__() d, L, H = cfg['d_model'], cfg['n_layers'], cfg['n_heads'] assert d % H == 0 and (d // H) % 2 == 0 self.tok_emb = nn.Embedding(cfg['vocab_size'], d) self.drop = nn.Dropout(dropout) self.blocks = nn.ModuleList([Block(d, H, cfg['ffn_dim'], dropout) for _ in range(L)]) self.norm = RMSNorm(d) cos, sin = build_rope(cfg['max_pos'], d // H) self.register_buffer('rope_cos', cos, persistent=False) self.register_buffer('rope_sin', sin, persistent=False) self.apply(_init_weights) for name, p in self.named_parameters(): # scaled init for residual projections if name.endswith('attn.o.weight') or name.endswith('mlp.w2.weight'): nn.init.normal_(p, mean=0.0, std=0.02 / math.sqrt(2 * L))
def forward(self, ids, pad_mask=None): x = self.drop(self.tok_emb(ids)) attn_mask = pad_mask[:, None, None, :] if pad_mask is not None else None for blk in self.blocks: x = blk(x, self.rope_cos, self.rope_sin, attn_mask) return self.norm(x)
def _init_weights(m): if isinstance(m, nn.Linear): nn.init.normal_(m.weight, mean=0.0, std=0.02) if m.bias is not None: nn.init.zeros_(m.bias) elif isinstance(m, nn.Embedding): nn.init.normal_(m.weight, mean=0.0, std=0.02)
class PrivoidForMLM(nn.Module): """Stage 1: masked-language-model pre-training head (output tied to the input embedding)."""
def __init__(self, cfg, dropout=0.0): super().__init__() d = cfg['d_model'] self.encoder = PrivoidEncoder(cfg, dropout) self.head_dense = nn.Linear(d, d) self.head_norm = RMSNorm(d) self.head_bias = nn.Parameter(torch.zeros(cfg['vocab_size'])) _init_weights(self.head_dense) self.__dict__['_enc_fn'] = None # optional torch.compile'd encoder (not a submodule)
def set_encoder_fn(self, fn): self.__dict__['_enc_fn'] = fn
def forward(self, ids, labels): enc = self._enc_fn if self._enc_fn is not None else self.encoder h = enc(ids) sel = labels != -100 hs = self.head_norm(F.gelu(self.head_dense(h[sel]))) logits = F.linear(hs, self.encoder.tok_emb.weight, self.head_bias) return F.cross_entropy(logits.float(), labels[sel])
class PrivoidRouter(nn.Module): """Stage 2: prompt -> logit of 'needs a frontier model'."""
def __init__(self, cfg, dropout=0.1): super().__init__() d = cfg['d_model'] self.encoder = PrivoidEncoder(cfg, dropout) self.head = nn.Sequential(nn.Dropout(dropout), nn.Linear(d, d), nn.GELU(), nn.Dropout(dropout), nn.Linear(d, 1)) self.head.apply(_init_weights)
def forward(self, ids, pad_mask): h = self.encoder(ids, pad_mask) m = pad_mask.unsqueeze(-1).to(h.dtype) pooled = (h * m).sum(1) / m.sum(1).clamp(min=1.0) return self.head(pooled).squeeze(-1).gitattributes+2
README.mdAdded+32
baseline_comparison.pngAdded

config.jsonAdded+20
external_model_comparison.pngAdded

Large File Pointer Details
- SHA256: f61b75e4f6e0363dcf37f6a953d0ec6888c08385706c4ff17af0bca441d97cd3
- Pointer size: 131 Bytes
- Size of remote file: 119 kB
model.ggufAdded+3
model.safetensorsAdded+3
privoid_model.pyAdded+150
routing_curve_test.pngAdded

stage1_val_loss.pngAdded

tokenizer.jsonAdded