Files
leleka/crates/experimental-ref/src/cvec/load_control_vectors.rs
T

296 lines
11 KiB
Rust

//! Moved out of the parent module by STRA-338: fn load_control_vectors, fn check_tables, fn sigmoid, fn warp_xor_sum, fn apply.
#[allow(unused_imports)]
use super::*;
/// The layer a `direction.<l>` tensor is for, or `None` for another tensor. Like `std::strtol`: an optional sign
/// and leading digits, anything else stops the parse (0 if none).
fn direction_layer(name: &str) -> Option<i64> {
let rest = name.strip_prefix("direction.")?;
let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
Some(digits.parse().unwrap_or(0))
}
/// Add `scale` times one file's f32 direction to `row`.
fn add_scaled(row: &mut [f32], src: &[u8], scale: f32) {
for (j, slot) in row.iter_mut().enumerate() {
let v = f32::from_le_bytes(src[j * 4..j * 4 + 4].try_into().expect("4"));
*slot += scale * v;
}
}
/// Add one file's directions, times its scale, into `data` (`[layer][n_embd]`) and mark the layers in `have`.
fn add_file(
(data, have): (&mut [f32], &mut [bool]),
(label, bytes, scale): &(String, Vec<u8>, f32),
(n_layers, n_embd): (i64, i64),
) -> Result<(), CvecError> {
let n = n_embd as usize;
let f = parse_gguf(bytes)?;
if f.architecture.as_deref() != Some("controlvector") {
return Err(CvecError::NotAControlVector(label.clone()));
}
let mut found = 0;
for t in &f.tensors {
let Some(l) = direction_layer(&t.name) else { continue };
if l < 1 || l >= n_layers {
continue;
}
if t.ggml_type != 0 || t.elements() != n as u64 {
return Err(CvecError::BadTensor { file: label.clone(), tensor: t.name.clone(), n_embd });
}
add_scaled(&mut data[l as usize * n..(l as usize + 1) * n], &bytes[t.data.clone()], *scale);
have[l as usize] = true;
found += 1;
}
if found == 0 {
return Err(CvecError::NoDirections(label.clone()));
}
Ok(())
}
/// One layer's table row for the direction `d`: project normalises it (and records its norm as the scale), add
/// copies it. False when a zero-norm projection leaves the layer unsteered.
fn steer_row(mode: CvecMode, d: &[f32], dir_row: &mut [f32], scale: &mut f32) -> bool {
match mode {
CvecMode::Project => {
let mut nrm = 0.0f64;
for v in d {
nrm += f64::from(*v) * f64::from(*v);
}
let nrm = nrm.sqrt();
if nrm <= 0.0 {
return false;
}
*scale = nrm as f32;
for (slot, v) in dir_row.iter_mut().zip(d) {
*slot = (f64::from(*v) / nrm) as f32;
}
}
CvecMode::Add => {
*scale = 1.0;
dir_row.copy_from_slice(d);
}
}
true
}
/// The first and last steered layer and the single source layer (-1: each layer is its own source).
fn layer_range(o: &CvecOptions, n_layers: i64) -> (i64, i64, i64) {
let first = if o.first <= 0 { 1 } else { o.first };
let last = if o.last <= 0 || o.last >= n_layers { n_layers - 1 } else { o.last };
let single = if o.mode == CvecMode::Project { o.single } else { -1 };
(first, last, single)
}
/// The direction and scale tables of the layers `first..=last` and how many layers they steer.
fn steer_layers(
(data, have): (&[f32], &[bool]),
(first, last, single): (i64, i64, i64),
(mode, n_layers, n): (CvecMode, i64, usize),
) -> (Vec<f32>, Vec<f32>, usize) {
let l_n = n_layers as usize;
let mut dir = vec![0.0f32; l_n * n];
let mut s = vec![0.0f32; l_n];
let mut steered = 0;
for l in first..=last {
let src = if single >= 0 { single } else { l };
if src < 0 || src >= n_layers || !have[src as usize] {
continue;
}
let d = &data[src as usize * n..(src as usize + 1) * n];
let row = l as usize * n..(l as usize + 1) * n;
if !steer_row(mode, d, &mut dir[row], &mut s[l as usize]) {
continue;
}
steered += 1;
}
(dir, s, steered)
}
/// The one-line description of the loaded vector, e.g. `project:1-23:single7`.
fn summary_of(mode: CvecMode, (first, last, single): (i64, i64, i64)) -> String {
format!(
"{}:{}-{}{}",
if mode == CvecMode::Project { "project" } else { "add" },
first,
last,
if single >= 0 { format!(":single{single}") } else { String::new() }
)
}
/// `load_control_vectors`: every file's `direction.<l>` times its scale, summed (f32 multiply then add), then the
/// project/add tables. `files` are `(label, bytes, scale)`. A `direction.<l>` with `l < 1` or `l >= n_layers` is
/// ignored (layer 0 has no vector; past the model is ignored, as in llama.cpp).
pub fn load_control_vectors(
files: &[(String, Vec<u8>, f32)],
n_layers: i64,
n_embd: i64,
hc: i64,
o: &CvecOptions,
) -> Result<CvecTables, CvecError> {
let (l_n, n) = (n_layers as usize, n_embd as usize);
let mut data = vec![0.0f32; l_n * n];
let mut have = vec![false; l_n];
for file in files {
add_file((&mut data, &mut have), file, (n_layers, n_embd))?;
}
let range = layer_range(o, n_layers);
let (first, last, single) = range;
if single >= 0 && (single >= n_layers || !have[single as usize]) {
return Err(CvecError::NoSingleDirection(single));
}
let (dir, s, steered) = steer_layers((&data, &have), range, (o.mode, n_layers, n));
if steered == 0 {
return Err(CvecError::NothingSteered { first, last });
}
check_tables(&dir, &s, n_embd)?;
let summary = summary_of(o.mode, range);
let steered_flags = s.iter().map(|v| *v != 0.0).collect();
Ok(CvecTables { dir, s, mode: o.mode, first, last, n_embd, hc, steered: steered_flags, summary })
}
/// The admission of `cvec_upload`.
pub fn check_tables(dir: &[f32], s: &[f32], n_embd: i64) -> Result<(), CvecError> {
if n_embd < 1 || n_embd > (THREADS * MAXK) as i64 {
return Err(CvecError::UnsupportedEmbd);
}
if s.is_empty() || dir.len() != s.len() * n_embd as usize {
return Err(CvecError::BadTables);
}
Ok(())
}
// ---------------------------------------------------------------------------------------------- kernel
/// The fused hyper-connection read's gate (`sigmoidf_`, `1 / (1 + __expf(-x))`). The device uses the fast
/// intrinsic; this is the libm result, so a pending write is exact only up to that intrinsic's error.
pub fn sigmoid(x: f32) -> f32 {
1.0 / (1.0 + (-x).exp())
}
/// Butterfly sum over 32 lanes with `__shfl_xor_sync` offsets 16, 8, 4, 2, 1 (every lane ends with the same
/// value; lane 0's is returned).
pub fn warp_xor_sum(mut lanes: [f32; 32]) -> f32 {
let mut o = 16;
while o > 0 {
let prev = lanes;
for l in 0..32 {
lanes[l] = prev[l] + prev[l ^ o];
}
o >>= 1;
}
lanes[0]
}
/// A register after steering: projected off the direction (by `dot`) or shifted by it.
fn steered_value(xv: f32, v: f32, (project, dot): (bool, f32)) -> f32 {
if project { (-dot).mul_add(v, xv) } else { xv + v }
}
/// Store the stream back: the registers, steered by `(project, dot)` when steering is on.
#[allow(clippy::needless_range_loop)] // thread/k indices mirror the CUDA text
fn write_back(stream: &mut [f32], x: &[[f32; MAXK]], v: &[f32], steering: Option<(bool, f32)>) {
let n = stream.len();
for tid in 0..THREADS {
for k in 0..MAXK {
let d = tid + k * THREADS;
if d < n {
let xv = x[tid][k];
stream[d] = steering.map_or(xv, |st| steered_value(xv, v[d], st));
}
}
}
}
/// The pending FFN write's weight `2 sigmoid(inj / hc)` and the `bo` row of token `t` for stream `c`, if any.
fn pending_write<'a>(
pending: Option<(&'a [f32], usize, &'a [f32], usize)>,
(t, c, hc, n): (usize, usize, usize, usize),
) -> (f32, Option<&'a [f32]>) {
match pending {
Some((bo, bo_ld, inj, inj_ld)) => (2.0 * sigmoid(inj[t * inj_ld + c] / hc as f32), Some(&bo[t * bo_ld..][..n])),
None => (0.0, None),
}
}
/// The per-thread registers of one stream: its values (with the pending write added) and, when `project_on` is
/// given, each thread's partial dot product with that direction.
#[allow(clippy::needless_range_loop)] // thread/k indices mirror the CUDA text
fn thread_registers(
stream: &[f32],
n: usize,
write: (f32, Option<&[f32]>),
project_on: Option<&[f32]>,
) -> (Vec<[f32; MAXK]>, [f32; THREADS]) {
let (w, b) = write;
let mut x = vec![[0.0f32; MAXK]; THREADS];
let mut dots = [0.0f32; THREADS];
for tid in 0..THREADS {
let mut dot = 0.0f32;
for k in 0..MAXK {
let d = tid + k * THREADS;
if d < n {
let mut xv = stream[d];
if let Some(b) = b {
xv = b[d].mul_add(w, xv);
}
x[tid][k] = xv;
if let Some(v) = project_on {
dot = xv.mul_add(v[d], dot);
}
}
}
dots[tid] = dot;
}
(x, dots)
}
/// The block's dot product: each warp's butterfly sum, then the butterfly sum of the warp sums.
fn block_dot(dots: &[f32; THREADS]) -> f32 {
let mut part = [0.0f32; THREADS / 32];
for (w_i, p) in part.iter_mut().enumerate() {
let mut lanes = [0.0f32; 32];
lanes.copy_from_slice(&dots[w_i * 32..w_i * 32 + 32]);
*p = warp_xor_sum(lanes);
}
let mut lanes = [0.0f32; 32];
lanes[..THREADS / 32].copy_from_slice(&part);
warp_xor_sum(lanes)
}
/// One `cvec_apply` over a batch: `R` is `T` rows of `r_ld` floats, each holding `hc` streams of `n`. With
/// `write`, the pending FFN write `R += bo * 2 sigmoid(inj / hc)` is applied first (`bo` rows of `bo_ld`,
/// `inj` rows of `inj_ld`). Literal twin of `cvec_kernel`'s per-thread dataflow, including the reduction tree.
#[allow(clippy::too_many_arguments, clippy::needless_range_loop)] // thread/k indices mirror the CUDA text
pub fn apply(
r: &mut [f32],
tables: &CvecTables,
on: bool,
layer: usize,
t_count: usize,
r_ld: usize,
pending: Option<(&[f32], usize, &[f32], usize)>,
) {
let (n, hc) = (tables.n_embd as usize, tables.hc as usize);
let write = pending.is_some();
let s = tables.s[layer];
let steer = on && s != 0.0;
if !steer && !write {
return;
}
let v = &tables.dir[layer * n..(layer + 1) * n];
let project = steer && tables.mode == CvecMode::Project;
for t in 0..t_count {
for c in 0..hc {
let base = t * r_ld + c * n;
let write_args = pending_write(pending, (t, c, hc, n));
// per-thread registers
let (x, dots) = thread_registers(&r[base..base + n], n, write_args, project.then_some(v));
let dot = if project { block_dot(&dots) * s } else { 0.0 }; // s (h . v)
let steering = steer.then_some((project, dot));
write_back(&mut r[base..base + n], &x, v, steering);
}
}
}