const SPLITMIX_GAMMA: u64 = 0x9E37_79B9_7F4A_7C15;
const SPLITMIX_M1: u64 = 0xBF58_476D_1CE4_E5B9;
const SPLITMIX_M2: u64 = 0x94D0_49BB_1331_11EB;
const PRIME_1: u64 = 10007;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GateAct {
Sigmoid,
Silu,
}
#[derive(Debug, Clone)]
pub struct NgramConfig {
pub vocab_size: u64,
pub ngram_size: usize,
pub heads_per_ngram: usize,
pub ngram_vocab_size_base: u64,
pub seed: u64,
pub eos_token_id: i64,
pub embed_dim: usize,
pub ple_layer_index: usize,
}
pub struct PleParams<'a> {
pub ngram: &'a NgramConfig,
pub hidden_size: usize,
pub hc_count: usize,
pub kernel: usize,
pub eps: f32,
pub table: &'a [f32],
pub key_proj: &'a [f32],
pub value_proj: &'a [f32],
pub norm_key: &'a [f32],
pub norm_query: &'a [f32],
pub norm_conv: &'a [f32],
pub conv_w: &'a [f32],
}
fn sigmoid(x: f32) -> f32 {
1.0 / (1.0 + (-x).exp())
}
fn silu(x: f32) -> f32 {
x * sigmoid(x)
}
pub fn gated_rms_norm(x: &[f32], gate: &[f32], weight: &[f32], eps: f32, act: GateAct) -> Vec<f32> {
let d = weight.len().max(1);
let mut out = Vec::with_capacity(x.len());
for (xr, zr) in x.chunks(d).zip(gate.chunks(d)) {
let ms = xr.iter().map(|v| v * v).sum::<f32>() / xr.len() as f32;
let inv = (ms + eps).sqrt().recip();
out.extend(xr.iter().zip(zr).zip(weight).map(|((&v, &z), &w)| {
let g = match act {
GateAct::Sigmoid => sigmoid(z),
GateAct::Silu => silu(z),
};
w * (v * inv) * g
}));
}
out
}
fn splitmix64(value: u64) -> u64 {
let v = value.wrapping_add(SPLITMIX_GAMMA);
let v = (v ^ (v >> 30)).wrapping_mul(SPLITMIX_M1);
let v = (v ^ (v >> 27)).wrapping_mul(SPLITMIX_M2);
v ^ (v >> 31)
}
pub fn layer_multipliers(cfg: &NgramConfig) -> Vec<i64> {
let half = ((i64::MAX as u64) / cfg.vocab_size.max(1) / 2).max(1);
let base = cfg
.seed
.wrapping_add(PRIME_1.wrapping_mul(cfg.ple_layer_index as u64));
(0..cfg.ngram_size as u64)
.map(|i| {
let s = base.wrapping_add(SPLITMIX_GAMMA.wrapping_mul(i + 1));
(2 * (splitmix64(s) % half) + 1) as i64
})
.collect()
}
fn is_prime(v: u64) -> bool {
if v < 2 || (v % 2 == 0 && v != 2) {
return v == 2;
}
(3..)
.step_by(2)
.take_while(|d| d * d <= v)
.all(|d| v % d != 0)
}
fn nth_prime_after(start: u64, count: usize) -> u64 {
let mut p = start;
for _ in 0..count {
p += 1;
while !is_prime(p) {
p += 1;
}
}
p
}
pub fn head_tables(cfg: &NgramConfig) -> Vec<(u64, u64)> {
let heads = (cfg.ngram_size - 1) * cfg.heads_per_ngram;
let mut off = 0;
(0..heads)
.map(|h| {
let g = cfg.ple_layer_index * heads + h + 1;
let size = nth_prime_after(cfg.ngram_vocab_size_base - 1, g);
let pair = (size, off);
off += size;
pair
})
.collect()
}
fn shift_ignore_eos(hist: &[i64], shift: usize, eos: i64) -> Vec<i64> {
let mut seg_start = 0usize;
let mut out = Vec::with_capacity(hist.len());
for (p, &tok) in hist.iter().enumerate() {
let valid = p >= shift && p - seg_start >= shift;
out.push(if shift == 0 {
tok
} else if valid {
hist[p - shift]
} else {
eos
});
if tok == eos {
seg_start = p + 1;
}
}
out
}
pub fn ngram_ids(cfg: &NgramConfig, ids: &[i64], ctx: Option<&[i64]>) -> Vec<i64> {
let ctx_len = cfg.ngram_size - 1;
let mut hist: Vec<i64> = match ctx {
Some(c) => c.to_vec(),
None => vec![cfg.eos_token_id; ctx_len],
};
hist.extend_from_slice(ids);
let shifted: Vec<Vec<i64>> = (0..cfg.ngram_size)
.map(|k| shift_ignore_eos(&hist, k, cfg.eos_token_id))
.collect();
let mult = layer_multipliers(cfg);
let heads = head_tables(cfg);
let first = hist.len() - ids.len();
let mut out = Vec::with_capacity(ids.len() * heads.len());
for p in first..hist.len() {
for n in 2..=cfg.ngram_size {
let mixed = (0..n).fold(0i64, |acc, j| {
let t = shifted[j][p].wrapping_mul(mult[j]);
if j == 0 {
t
} else {
acc ^ t
}
});
let lo = (n - 2) * cfg.heads_per_ngram;
for &(size, off) in &heads[lo..lo + cfg.heads_per_ngram] {
out.push(mixed.rem_euclid(size as i64) + off as i64);
}
}
}
out
}
pub fn ngram_embed(cfg: &NgramConfig, table: &[f32], ids: &[i64]) -> Vec<f32> {
let heads = (cfg.ngram_size - 1) * cfg.heads_per_ngram;
let w = cfg.embed_dim / heads;
ngram_ids(cfg, ids, None)
.iter()
.flat_map(|&row| {
let s = row as usize * w;
table.get(s..s + w).unwrap_or(&[]).iter().copied()
})
.collect()
}
fn linear(x: &[f32], w: &[f32], inp: usize, out: usize) -> Vec<f32> {
x.chunks(inp)
.flat_map(|row| {
w.chunks(inp)
.take(out)
.map(|wr| row.iter().zip(wr).map(|(a, b)| a * b).sum::<f32>())
})
.collect()
}
fn grouped_rms_norm(x: &[f32], weight: &[f32], group: usize, eps: f32) -> Vec<f32> {
let d = weight.len();
let mut out = Vec::with_capacity(x.len());
for row in x.chunks(d) {
for (gi, g) in row.chunks(group).enumerate() {
let ms = g.iter().map(|v| v * v).sum::<f32>() / g.len() as f32;
let inv = (ms + eps).sqrt().recip();
let base = gi * group;
out.extend(
g.iter()
.enumerate()
.map(|(i, v)| v * inv * (1.0 + weight[base + i])),
);
}
}
out
}
fn dilated_causal_conv_silu(
x: &[f32],
w: &[f32],
ch: usize,
kernel: usize,
dil: usize,
) -> Vec<f32> {
let seq = x.len() / ch.max(1);
let mut out = vec![0.0f32; seq * ch];
for s in 0..seq {
for c in 0..ch {
let acc: f32 = (0..kernel)
.filter_map(|j| {
let back = (kernel - 1 - j) * dil;
s.checked_sub(back)
.map(|t| w[c * kernel + j] * x[t * ch + c])
})
.sum();
out[s * ch + c] = silu(acc);
}
}
out
}
fn gate_value(key: &[f32], query: &[f32], value: &[f32], h: usize, c: usize) -> Vec<f32> {
let scale = (h as f32).sqrt();
let mut out = Vec::with_capacity(key.len());
for ((kr, qr), vr) in key
.chunks(c * h)
.zip(query.chunks(c * h))
.zip(value.chunks(h))
{
for (kc, qc) in kr.chunks(h).zip(qr.chunks(h)) {
let raw = kc.iter().zip(qc).map(|(a, b)| a * b).sum::<f32>() / scale;
let g = raw.abs().max(1e-6).sqrt()
* if raw < 0.0 {
-1.0
} else if raw > 0.0 {
1.0
} else {
0.0
};
out.extend(vr.iter().map(|v| sigmoid(g) * v));
}
}
out
}
pub fn ple_forward(p: &PleParams<'_>, hidden: &[f32], ids: &[i64]) -> Vec<f32> {
let (h, c, e) = (p.hidden_size, p.hc_count, p.ngram.embed_dim);
let emb = ngram_embed(p.ngram, p.table, ids);
let key = grouped_rms_norm(&linear(&emb, p.key_proj, e, c * h), p.norm_key, h, p.eps);
let value = linear(&emb, p.value_proj, e, h);
let query = grouped_rms_norm(hidden, p.norm_query, h, p.eps);
let gv = gate_value(&key, &query, &value, h, c);
let normed = grouped_rms_norm(&gv, p.norm_conv, h, p.eps);
let conv = dilated_causal_conv_silu(&normed, p.conv_w, c * h, p.kernel, p.ngram.ngram_size);
gv.iter().zip(&conv).map(|(a, b)| a + b).collect()
}