Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/crates/allen-reflex/src/model.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / crates / allen-reflex / src / model.rs` 736 lines ยท 23787 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 //! Label scorers. All three read the same feature list. 17 //! 18 //! - [`HvModel`]: hypervector exemplar memory + ternary class prototypes (the REFLEX core). 19 //! - [`NearestModel`]: nearest exemplar over the sparse feature sets, no hypervectors (ablation). 20 //! - [`PerceptronModel`]: averaged multiclass perceptron over the sparse features (baseline). 21 22 use crate::action::{Action, N_LABELS}; 23 use crate::features::Feat; 24 use crate::hv; 25 use alloc::collections::BTreeMap; 26 use alloc::string::String; 27 use alloc::vec; 28 use alloc::vec::Vec; 29 30 /// What a scorer says about one request. 31 #[derive(Clone, Debug)] 32 pub struct Scores { 33 /// per-label score (higher is better); labels without any training example get -9 34 pub s: [f32; N_LABELS], 35 /// similarity of the single nearest exemplar (1.0 for the perceptron, which has none) 36 pub best_sim: f32, 37 /// index of the nearest exemplar 38 pub nearest: Option, 39 /// share of the top-k neighbours that carry the top label (1.0 for the perceptron) 40 pub agree: f32, 41 } 42 43 impl Scores { 44 fn empty() -> Scores { 45 Scores { 46 s: [-9.0; N_LABELS], 47 best_sim: 0.0, 48 nearest: None, 49 agree: 1.0, 50 } 51 } 52 } 53 54 /// Memory is full: the caller should run `sleep()` (which merges near duplicates). 55 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 56 pub struct MemoryFull; 57 58 /// A pair of exemplars with different labels that look alike. 59 #[derive(Clone, Debug)] 60 pub struct Conflict { 61 /// first exemplar index (after consolidation) 62 pub a: usize, 63 /// second exemplar index 64 pub b: usize, 65 /// their similarity 66 pub sim: f32, 67 } 68 69 /// Result of `sleep()`. 70 #[derive(Clone, Debug, Default)] 71 pub struct SleepReport { 72 /// exemplars removed as near duplicates of an earlier one with the same label 73 pub merged: usize, 74 /// exemplars kept 75 pub kept: usize, 76 /// label conflicts, most similar first, at most [`MAX_CONFLICTS`] 77 pub conflicts: Vec, 78 /// retraining passes run 79 pub passes: u32, 80 } 81 82 /// Bound on conflicts reported by one sleep. 83 pub const MAX_CONFLICTS: usize = 32; 84 /// Bound on the explanation note kept per exemplar (bytes). 85 pub const NOTE_BYTES: usize = 96; 86 87 fn short(note: &str) -> String { 88 let mut n = NOTE_BYTES.min(note.len()); 89 while !note.is_char_boundary(n) { 90 n -= 1; 91 } 92 String::from(¬e[..n]) 93 } 94 95 /// Hypervector settings. 96 #[derive(Clone, Copy, Debug)] 97 pub struct HvConfig { 98 /// u64 words per vector (128 = 8192 bits) 99 pub words: usize, 100 /// exemplars per label averaged for the k-NN part 101 pub k: usize, 102 /// weight of the k-NN part (the prototype part gets 1 - alpha) 103 pub alpha: f32, 104 /// ternary zero band, in standard deviations of a class's counters 105 pub zero_band: f32, 106 /// retraining passes (at most) 107 pub epochs: u32, 108 /// retraining rate 109 pub eta: f32, 110 /// exemplar capacity 111 pub max_exemplars: usize, 112 } 113 114 /// Counter scale of one exemplar in a prototype. 115 const SCALE: f32 = 64.0; 116 117 /// Hypervector exemplar memory with ternary prototypes. 118 #[derive(Clone)] 119 pub struct HvModel { 120 /// settings 121 pub cfg: HvConfig, 122 hvs: Vec, 123 labels: Vec, 124 notes: Vec, 125 counts: Vec, 126 sign: Vec, 127 mask: Vec, 128 nnz: [u32; N_LABELS], 129 n_label: [u32; N_LABELS], 130 } 131 132 impl HvModel { 133 /// Empty memory. 134 pub fn new(cfg: HvConfig) -> HvModel { 135 let d = cfg.words * 64; 136 HvModel { 137 cfg, 138 hvs: Vec::with_capacity(cfg.max_exemplars * cfg.words), 139 labels: Vec::with_capacity(cfg.max_exemplars), 140 notes: Vec::with_capacity(cfg.max_exemplars), 141 counts: vec![0; N_LABELS * d], 142 sign: vec![0; N_LABELS * cfg.words], 143 mask: vec![0; N_LABELS * cfg.words], 144 nnz: [0; N_LABELS], 145 n_label: [0; N_LABELS], 146 } 147 } 148 149 /// Number of exemplars. 150 pub fn len(&self) -> usize { 151 self.labels.len() 152 } 153 154 /// True when no exemplar is stored. 155 pub fn is_empty(&self) -> bool { 156 self.labels.is_empty() 157 } 158 159 /// Exemplar label and note. 160 pub fn exemplar(&self, i: usize) -> (Action, &str) { 161 (Action::from_idx(self.labels[i] as usize), &self.notes[i]) 162 } 163 164 /// Encode features into a fresh vector. 165 pub fn encode(&self, feats: &[Feat]) -> Vec { 166 let w = self.cfg.words; 167 let mut out = vec![0u64; w]; 168 let mut cnt = vec![0i32; w * 64]; 169 let mut acc = vec![0u64; w]; 170 let mut tmp = vec![0u64; w]; 171 hv::encode(feats, &mut out, &mut cnt, &mut acc, &mut tmp); 172 out 173 } 174 175 fn hv(&self, i: usize) -> &[u64] { 176 &self.hvs[i * self.cfg.words..(i + 1) * self.cfg.words] 177 } 178 179 /// Bytes held (vectors, counters, prototypes, notes; capacity-based). 180 pub fn bytes(&self) -> usize { 181 self.hvs.capacity() * 8 182 + self.labels.capacity() 183 + self.notes.iter().map(|n| n.capacity() + 24).sum::() 184 + self.counts.len() * 4 185 + (self.sign.len() + self.mask.len()) * 8 186 } 187 188 /// Store one exemplar (vector already encoded). Prototypes are not touched. 189 pub fn push(&mut self, q: &[u64], label: Action, note: &str) -> Result { 190 if self.labels.len() >= self.cfg.max_exemplars { 191 return Err(MemoryFull); 192 } 193 self.hvs.extend_from_slice(q); 194 self.labels.push(label.idx() as u8); 195 self.notes.push(short(note)); 196 self.n_label[label.idx()] += 1; 197 Ok(self.labels.len() - 1) 198 } 199 200 fn add_counts(&mut self, l: usize, q: &[u64], wt: i32) { 201 let d = self.cfg.words * 64; 202 let c = &mut self.counts[l * d..(l + 1) * d]; 203 for (x, &v) in q.iter().enumerate() { 204 for b in 0..64 { 205 let bit = ((v >> b) & 1) as i32; 206 c[x * 64 + b] += (2 * bit - 1) * wt; 207 } 208 } 209 } 210 211 fn quantize(&mut self, l: usize) { 212 let w = self.cfg.words; 213 let d = w * 64; 214 let c = &self.counts[l * d..(l + 1) * d]; 215 let mean = c.iter().map(|&x| x as f32).sum::() / d as f32; 216 let var = c 217 .iter() 218 .map(|&x| { 219 let t = x as f32 - mean; 220 t * t 221 }) 222 .sum::() 223 / d as f32; 224 let band = self.cfg.zero_band * hv::sqrtf(var); 225 let mut nnz = 0u32; 226 for x in 0..w { 227 let mut s = 0u64; 228 let mut m = 0u64; 229 for b in 0..64 { 230 let v = c[x * 64 + b] as f32; 231 if v > 0.0 { 232 s |= 1 << b; 233 } 234 if v > band || -v > band { 235 m |= 1 << b; 236 } 237 } 238 self.sign[l * w + x] = s; 239 self.mask[l * w + x] = m; 240 nnz += m.count_ones(); 241 } 242 self.nnz[l] = nnz; 243 } 244 245 /// Cosine-like similarity of a binary query with the ternary prototype of `l`. 246 pub fn proto_sim(&self, q: &[u64], l: usize) -> f32 { 247 if self.n_label[l] == 0 || self.nnz[l] == 0 { 248 return -1.0; 249 } 250 let w = self.cfg.words; 251 let mut agree = 0i64; 252 let mut dis = 0i64; 253 for x in 0..w { 254 let m = self.mask[l * w + x]; 255 let diff = q[x] ^ self.sign[l * w + x]; 256 dis += (diff & m).count_ones() as i64; 257 agree += (!diff & m).count_ones() as i64; 258 } 259 let d = (w * 64) as f32; 260 (agree - dis) as f32 / hv::sqrtf(self.nnz[l] as f32 * d) 261 } 262 263 fn proto_argmax(&self, q: &[u64]) -> (usize, [f32; N_LABELS]) { 264 let mut s = [-9.0f32; N_LABELS]; 265 for (l, sl) in s.iter_mut().enumerate() { 266 if self.n_label[l] > 0 { 267 *sl = self.proto_sim(q, l); 268 } 269 } 270 (argmax(&s), s) 271 } 272 273 /// Rebuild prototypes from all exemplars: one bundling pass, then retraining passes with 274 /// the ternary model in the loop (OnlineHD-style weights). Returns passes run. 275 pub fn rebuild(&mut self) -> u32 { 276 for c in self.counts.iter_mut() { 277 *c = 0; 278 } 279 let w = self.cfg.words; 280 for i in 0..self.len() { 281 let l = self.labels[i] as usize; 282 let q: Vec = self.hvs[i * w..(i + 1) * w].to_vec(); 283 self.add_counts(l, &q, SCALE as i32); 284 } 285 for l in 0..N_LABELS { 286 self.quantize(l); 287 } 288 let mut passes = 0; 289 for _ in 0..self.cfg.epochs { 290 passes += 1; 291 let mut errors = 0; 292 for i in 0..self.len() { 293 let y = self.labels[i] as usize; 294 let q: Vec = self.hvs[i * w..(i + 1) * w].to_vec(); 295 let (p, s) = self.proto_argmax(&q); 296 if p != y { 297 errors += 1; 298 let wy = (self.cfg.eta * (1.0 - s[y]) * SCALE) as i32; 299 let wp = (self.cfg.eta * (1.0 - s[p]) * SCALE) as i32; 300 self.add_counts(y, &q, wy.max(1)); 301 self.add_counts(p, &q, -wp.max(1)); 302 self.quantize(y); 303 self.quantize(p); 304 } 305 } 306 if errors == 0 { 307 break; 308 } 309 } 310 passes 311 } 312 313 /// One-shot online update after storing exemplar `i`: add it to its class (weight 314 /// 1 - similarity, so familiar cases add little) and, when a wrong label `wrong` had been 315 /// predicted, subtract it from that class. 316 pub fn online(&mut self, i: usize, wrong: Option) { 317 let w = self.cfg.words; 318 let q: Vec = self.hvs[i * w..(i + 1) * w].to_vec(); 319 let y = self.labels[i] as usize; 320 let sy = self.proto_sim(&q, y).max(-1.0); 321 let wy = ((1.0 - sy) * SCALE) as i32; 322 self.add_counts(y, &q, wy.max(1)); 323 self.quantize(y); 324 if let Some(p) = wrong { 325 let p = p.idx(); 326 if p != y && self.n_label[p] > 0 { 327 let sp = self.proto_sim(&q, p); 328 let wp = ((1.0 + sp) * 0.5 * SCALE) as i32; 329 self.add_counts(p, &q, -wp.max(1)); 330 self.quantize(p); 331 } 332 } 333 } 334 335 /// Score a query vector. 336 pub fn score_hv(&self, q: &[u64]) -> Scores { 337 let mut out = Scores::empty(); 338 if self.is_empty() { 339 return out; 340 } 341 let k = self.cfg.k.max(1); 342 // per label: top-k similarities (small fixed arrays) 343 let mut top = [[-2.0f32; 8]; N_LABELS]; 344 let kk = k.min(8); 345 let ka = kk.max(3); 346 let mut glob: [(f32, usize); 8] = [(-2.0, 0); 8]; 347 for i in 0..self.len() { 348 let s = hv::sim(q, self.hv(i)); 349 let l = self.labels[i] as usize; 350 ins(&mut top[l][..kk], s); 351 insi(&mut glob[..ka], (s, i)); 352 } 353 out.best_sim = glob[0].0; 354 out.nearest = Some(glob[0].1); 355 let a = self.cfg.alpha; 356 for l in 0..N_LABELS { 357 if self.n_label[l] == 0 { 358 continue; 359 } 360 let m = (self.n_label[l] as usize).min(kk); 361 let knn = top[l][..m].iter().sum::() / m as f32; 362 let pr = if a < 1.0 { self.proto_sim(q, l) } else { 0.0 }; 363 out.s[l] = a * knn + (1.0 - a) * pr; 364 } 365 let tl = argmax(&out.s); 366 let n = glob[..ka].iter().filter(|g| g.0 > -2.0).count().max(1); 367 out.agree = glob[..ka] 368 .iter() 369 .filter(|g| g.0 > -2.0 && self.labels[g.1] as usize == tl) 370 .count() as f32 371 / n as f32; 372 out 373 } 374 375 /// Consolidation: merge near duplicates (same label, similarity >= `dup`), list label 376 /// conflicts (different labels, similarity >= `conflict`), rebuild prototypes. 377 /// Work is bounded by capacity^2 vector comparisons. 378 pub fn sleep(&mut self, dup: f32, conflict: f32) -> SleepReport { 379 let w = self.cfg.words; 380 let n = self.len(); 381 let mut keep = vec![true; n]; 382 let mut merged = 0; 383 for i in 0..n { 384 if !keep[i] { 385 continue; 386 } 387 for j in i + 1..n { 388 if keep[j] 389 && self.labels[i] == self.labels[j] 390 && hv::sim(self.hv(i), self.hv(j)) >= dup 391 { 392 keep[j] = false; 393 merged += 1; 394 } 395 } 396 } 397 if merged > 0 { 398 let mut hvs = Vec::with_capacity(self.hvs.capacity()); 399 let mut labels = Vec::with_capacity(self.labels.capacity()); 400 let mut notes = Vec::with_capacity(self.notes.capacity()); 401 self.n_label = [0; N_LABELS]; 402 for i in 0..n { 403 if keep[i] { 404 hvs.extend_from_slice(&self.hvs[i * w..(i + 1) * w]); 405 labels.push(self.labels[i]); 406 notes.push(self.notes[i].clone()); 407 self.n_label[self.labels[i] as usize] += 1; 408 } 409 } 410 self.hvs = hvs; 411 self.labels = labels; 412 self.notes = notes; 413 } 414 let n = self.len(); 415 let mut conflicts: Vec = Vec::new(); 416 for i in 0..n { 417 for j in i + 1..n { 418 if self.labels[i] != self.labels[j] { 419 let s = hv::sim(self.hv(i), self.hv(j)); 420 if s >= conflict { 421 conflicts.push(Conflict { a: i, b: j, sim: s }); 422 } 423 } 424 } 425 } 426 conflicts.sort_by(|x, y| { 427 y.sim 428 .partial_cmp(&x.sim) 429 .unwrap_or(core::cmp::Ordering::Equal) 430 }); 431 conflicts.truncate(MAX_CONFLICTS); 432 let passes = self.rebuild(); 433 SleepReport { 434 merged, 435 kept: n, 436 conflicts, 437 passes, 438 } 439 } 440 } 441 442 /// Index of the largest score (first on ties). 443 pub fn argmax(s: &[f32; N_LABELS]) -> usize { 444 let mut b = 0; 445 for l in 1..N_LABELS { 446 if s[l] > s[b] { 447 b = l; 448 } 449 } 450 b 451 } 452 453 fn ins(top: &mut [f32], s: f32) { 454 if top.is_empty() || s <= top[top.len() - 1] { 455 return; 456 } 457 let mut p = top.len() - 1; 458 top[p] = s; 459 while p > 0 && top[p] > top[p - 1] { 460 top.swap(p, p - 1); 461 p -= 1; 462 } 463 } 464 465 fn insi(top: &mut [(f32, usize)], v: (f32, usize)) { 466 if top.is_empty() || v.0 <= top[top.len() - 1].0 { 467 return; 468 } 469 let mut p = top.len() - 1; 470 top[p] = v; 471 while p > 0 && top[p].0 > top[p - 1].0 { 472 top.swap(p, p - 1); 473 p -= 1; 474 } 475 } 476 477 /// Sparse weighted feature set: sorted by key, weights summed for repeated keys. 478 pub fn sparse(feats: &[Feat]) -> Vec<(u64, u32)> { 479 let mut v: Vec<(u64, u32)> = feats.iter().map(|f| (f.key(), f.w as u32)).collect(); 480 v.sort_unstable_by_key(|x| x.0); 481 let mut o: Vec<(u64, u32)> = Vec::with_capacity(v.len()); 482 for (k, w) in v { 483 match o.last_mut() { 484 Some(l) if l.0 == k => l.1 += w, 485 _ => o.push((k, w)), 486 } 487 } 488 o 489 } 490 491 /// Weighted Dice similarity of two sparse sets, in [0, 1]. 492 pub fn dice(a: &[(u64, u32)], b: &[(u64, u32)]) -> f32 { 493 let (mut i, mut j, mut inter) = (0, 0, 0u64); 494 while i < a.len() && j < b.len() { 495 if a[i].0 == b[j].0 { 496 inter += a[i].1.min(b[j].1) as u64; 497 i += 1; 498 j += 1; 499 } else if a[i].0 < b[j].0 { 500 i += 1; 501 } else { 502 j += 1; 503 } 504 } 505 let ta: u64 = a.iter().map(|x| x.1 as u64).sum(); 506 let tb: u64 = b.iter().map(|x| x.1 as u64).sum(); 507 if ta + tb == 0 { 508 return 0.0; 509 } 510 2.0 * inter as f32 / (ta + tb) as f32 511 } 512 513 /// Nearest exemplar over sparse feature sets (no hypervectors). 514 #[derive(Clone)] 515 pub struct NearestModel { 516 /// exemplars per label averaged (as in HvModel) 517 pub k: usize, 518 /// capacity 519 pub max_exemplars: usize, 520 sets: Vec>, 521 labels: Vec, 522 notes: Vec, 523 n_label: [u32; N_LABELS], 524 } 525 526 impl NearestModel { 527 /// Empty memory. 528 pub fn new(k: usize, max_exemplars: usize) -> NearestModel { 529 NearestModel { 530 k, 531 max_exemplars, 532 sets: Vec::new(), 533 labels: Vec::new(), 534 notes: Vec::new(), 535 n_label: [0; N_LABELS], 536 } 537 } 538 /// Number of exemplars. 539 pub fn len(&self) -> usize { 540 self.labels.len() 541 } 542 /// True when empty. 543 pub fn is_empty(&self) -> bool { 544 self.labels.is_empty() 545 } 546 /// Exemplar label and note. 547 pub fn exemplar(&self, i: usize) -> (Action, &str) { 548 (Action::from_idx(self.labels[i] as usize), &self.notes[i]) 549 } 550 /// Store one exemplar. 551 pub fn push(&mut self, f: &[Feat], label: Action, note: &str) -> Result { 552 if self.labels.len() >= self.max_exemplars { 553 return Err(MemoryFull); 554 } 555 self.sets.push(sparse(f)); 556 self.labels.push(label.idx() as u8); 557 self.notes.push(short(note)); 558 self.n_label[label.idx()] += 1; 559 Ok(self.labels.len() - 1) 560 } 561 /// Bytes held. 562 pub fn bytes(&self) -> usize { 563 self.sets 564 .iter() 565 .map(|s| s.capacity() * 16 + 24) 566 .sum::() 567 + self.labels.capacity() 568 + self.notes.iter().map(|n| n.capacity() + 24).sum::() 569 } 570 /// Score. 571 pub fn score(&self, f: &[Feat]) -> Scores { 572 let mut out = Scores::empty(); 573 if self.is_empty() { 574 return out; 575 } 576 let q = sparse(f); 577 let kk = self.k.clamp(1, 8); 578 let ka = kk.max(3); 579 let mut top = [[-2.0f32; 8]; N_LABELS]; 580 let mut glob: [(f32, usize); 8] = [(-2.0, 0); 8]; 581 for (i, s) in self.sets.iter().enumerate() { 582 let d = dice(&q, s); 583 ins(&mut top[self.labels[i] as usize][..kk], d); 584 insi(&mut glob[..ka], (d, i)); 585 } 586 out.best_sim = glob[0].0; 587 out.nearest = Some(glob[0].1); 588 for l in 0..N_LABELS { 589 if self.n_label[l] == 0 { 590 continue; 591 } 592 let m = (self.n_label[l] as usize).min(kk); 593 out.s[l] = top[l][..m].iter().sum::() / m as f32; 594 } 595 let tl = argmax(&out.s); 596 let n = glob[..ka].iter().filter(|g| g.0 > -2.0).count().max(1); 597 out.agree = glob[..ka] 598 .iter() 599 .filter(|g| g.0 > -2.0 && self.labels[g.1] as usize == tl) 600 .count() as f32 601 / n as f32; 602 out 603 } 604 } 605 606 /// Averaged multiclass perceptron over sparse features. 607 #[derive(Clone)] 608 pub struct PerceptronModel { 609 /// training passes 610 pub epochs: u32, 611 /// bound on distinct features 612 pub max_features: usize, 613 w: BTreeMap, 614 train: Vec<(Vec<(u64, u32)>, u8)>, 615 n_label: [u32; N_LABELS], 616 } 617 618 impl PerceptronModel { 619 /// Empty model. 620 pub fn new(epochs: u32, max_features: usize) -> PerceptronModel { 621 PerceptronModel { 622 epochs, 623 max_features, 624 w: BTreeMap::new(), 625 train: Vec::new(), 626 n_label: [0; N_LABELS], 627 } 628 } 629 /// Queue one training example. 630 pub fn push(&mut self, f: &[Feat], label: Action) { 631 self.train.push((sparse(f), label.idx() as u8)); 632 self.n_label[label.idx()] += 1; 633 } 634 /// Bytes held. 635 pub fn bytes(&self) -> usize { 636 self.w.len() * (8 + 4 * N_LABELS + 32) 637 } 638 fn raw(w: &BTreeMap, x: &[(u64, u32)]) -> [f32; N_LABELS] { 639 let mut s = [0.0f32; N_LABELS]; 640 for (k, v) in x { 641 if let Some(r) = w.get(k) { 642 for l in 0..N_LABELS { 643 s[l] += r[l] * *v as f32; 644 } 645 } 646 } 647 s 648 } 649 /// Train with averaging; deterministic shuffle per pass. 650 pub fn fit(&mut self) { 651 let mut w: BTreeMap = BTreeMap::new(); 652 let mut u: BTreeMap = BTreeMap::new(); 653 let mut c = 1.0f32; 654 let n = self.train.len(); 655 let mut order: Vec = (0..n).collect(); 656 let mut rng = hv::SEED; 657 for _ in 0..self.epochs { 658 for i in (1..n).rev() { 659 let j = (hv::splitmix(&mut rng) % (i as u64 + 1)) as usize; 660 order.swap(i, j); 661 } 662 for &i in &order { 663 let (x, y) = (&self.train[i].0, self.train[i].1 as usize); 664 let mut s = Self::raw(&w, x); 665 for (l, sl) in s.iter_mut().enumerate() { 666 if self.n_label[l] == 0 { 667 *sl = f32::MIN; 668 } 669 } 670 let p = argmax(&s); 671 if p != y { 672 for (k, v) in x { 673 if !w.contains_key(k) && w.len() >= self.max_features { 674 continue; 675 } 676 let r = w.entry(*k).or_insert([0.0; N_LABELS]); 677 r[y] += *v as f32; 678 r[p] -= *v as f32; 679 let a = u.entry(*k).or_insert([0.0; N_LABELS]); 680 a[y] += c * *v as f32; 681 a[p] -= c * *v as f32; 682 } 683 } 684 c += 1.0; 685 } 686 } 687 for (k, r) in w.iter_mut() { 688 if let Some(a) = u.get(k) { 689 for l in 0..N_LABELS { 690 r[l] -= a[l] / c; 691 } 692 } 693 } 694 self.w = w; 695 } 696 /// Online correction: perceptron steps on this example until it is predicted right 697 /// (at most 8 steps). 698 pub fn online(&mut self, f: &[Feat], label: Action) { 699 let x = sparse(f); 700 let y = label.idx(); 701 self.n_label[y] += 1; 702 self.train.push((x.clone(), y as u8)); 703 for _ in 0..8 { 704 let s = self.score_sparse(&x); 705 let p = argmax(&s.s); 706 if p == y { 707 break; 708 } 709 for (k, v) in &x { 710 if !self.w.contains_key(k) && self.w.len() >= self.max_features { 711 continue; 712 } 713 let r = self.w.entry(*k).or_insert([0.0; N_LABELS]); 714 r[y] += *v as f32; 715 r[p] -= *v as f32; 716 } 717 } 718 } 719 fn score_sparse(&self, x: &[(u64, u32)]) -> Scores { 720 let mut out = Scores::empty(); 721 let tot: f32 = x.iter().map(|v| v.1 as f32).sum::().max(1.0); 722 let s = Self::raw(&self.w, x); 723 for l in 0..N_LABELS { 724 if self.n_label[l] > 0 { 725 out.s[l] = s[l] / tot; 726 } 727 } 728 out.best_sim = 1.0; 729 out.agree = 1.0; 730 out 731 } 732 /// Score. 733 pub fn score(&self, f: &[Feat]) -> Scores { 734 self.score_sparse(&sparse(f)) 735 } 736 }