Skip to main content

handwired_rs/
tensor.rs

1//! Compilation into layers of sparse matrix multiplications, and a CPU executor.
2//!
3//! Independent operations at the same dependency depth share a layer. A layer
4//! gathers its earlier inputs, evaluates one sparse affine projection (one row
5//! per output, then one gate row per ReGLU, then one index row per index read),
6//! applies gather reads, index reads, ReGLU gates and boolean rounding, and
7//! appends its outputs. Operations that no requested root reads are removed.
8//! A masked sum over a declared one-hot group compiles to a gather read (see
9//! [`OneHotGroup`](crate::OneHotGroup)).
10
11use std::collections::HashMap;
12
13use crate::Error;
14use crate::circuit::{Circuit, OpKind, OutOfRange, resolve_index_position};
15use crate::gather::{GatherPlan, plan_gather_lowering};
16use crate::numeric::{evaluate_boolean, relu32};
17use crate::wire::Wire;
18
19#[derive(Clone, Debug)]
20pub struct IndexReadRow {
21    pub row: u32,
22    pub index_row: u32,
23    pub below_zero: bool,
24    pub above_zero: bool,
25    /// Packed positions of the candidates.
26    pub candidate_positions: Vec<u32>,
27}
28
29/// Resolves a one-hot group's selected position once per evaluation, at the
30/// first layer that reads the group: `Σ position × bit` and `Σ bit`, exact for
31/// 0/1 bits.
32#[derive(Clone, Debug)]
33pub struct GatherCompute {
34    pub slot: u32,
35    /// Packed positions of the group's members, in group order.
36    pub bit_positions: Vec<u32>,
37}
38
39/// A lowered masked sum: the row's bias plus the selected candidate, which is
40/// first multiplied by the group's sum of bits when the group allows all zeros.
41#[derive(Clone, Debug)]
42pub struct GatherRead {
43    pub row: u32,
44    pub slot: u32,
45    pub masked: bool,
46    pub candidate_positions: Vec<u32>,
47}
48
49#[derive(Clone, Debug, Copy)]
50pub struct CompileOptions {
51    /// Lower masked sums over declared one-hot groups to gather reads. On by default.
52    pub lower_gathers: bool,
53    /// Place each operation one layer after the deepest value it reads in the compiled program, instead of at its
54    /// build-time depth, so a gather read stops waiting for the products it replaced. Off by default.
55    pub recompute_depths: bool,
56}
57
58impl Default for CompileOptions {
59    fn default() -> CompileOptions {
60        CompileOptions { lower_gathers: true, recompute_depths: false }
61    }
62}
63
64#[derive(Clone, Debug)]
65pub struct TensorLayer {
66    /// Packed positions this layer reads, in column order.
67    pub input_indices: Vec<u32>,
68    pub output_size: usize,
69    /// One bias per projection row, already rounded to f32.
70    pub bias: Vec<f32>,
71    /// CSR sparse matrix over the projection rows.
72    pub row_offsets: Vec<u32>,
73    pub columns: Vec<u32>,
74    pub weights: Vec<f32>,
75    /// Output rows whose value is multiplied by relu of gate row `output_size + k`.
76    pub gate_rows: Vec<u32>,
77    pub boolean_rows: Vec<u32>,
78    pub gather_computes: Vec<GatherCompute>,
79    pub gather_reads: Vec<GatherRead>,
80    pub index_reads: Vec<IndexReadRow>,
81}
82
83#[derive(Clone, Debug)]
84pub struct TensorProgram {
85    pub layers: Vec<TensorLayer>,
86    pub roots: Vec<Wire>,
87    pub source_size: usize,
88    /// Source cells plus live operations.
89    pub value_count: usize,
90    /// `wire_order[packed]` is the wire held at that packed position.
91    pub wire_order: Vec<Wire>,
92    /// The circuit's width, for full-width results.
93    pub width: usize,
94    /// One slot per one-hot group that gather reads use.
95    pub gather_slot_count: usize,
96}
97
98impl TensorProgram {
99    pub fn stored_weight_count(&self) -> usize {
100        self.layers.iter().map(|layer| layer.weights.len()).sum()
101    }
102
103    pub fn live_operation_count(&self) -> usize {
104        self.value_count - self.source_size
105    }
106
107    pub fn gather_read_count(&self) -> usize {
108        self.layers.iter().map(|layer| layer.gather_reads.len()).sum()
109    }
110}
111
112impl Circuit {
113    /// Compile the operations that `roots` need, or every operation when
114    /// `roots` is `None`, with the default [`CompileOptions`].
115    pub fn compile(&self, roots: Option<&[Wire]>) -> TensorProgram {
116        self.compile_with(roots, CompileOptions::default())
117    }
118
119    pub fn compile_with(&self, roots: Option<&[Wire]>, options: CompileOptions) -> TensorProgram {
120        let width = self.width();
121        let source_size = self.source_size();
122        let roots: Vec<Wire> = match roots {
123            Some(roots) => roots.to_vec(),
124            None => (source_size..width).map(Wire::from_index).collect(),
125        };
126        let plans = if options.lower_gathers { plan_gather_lowering(self) } else { HashMap::new() };
127        let live = self.find_live_operations(&roots, &plans);
128        let compiled_depths = options.recompute_depths.then(|| self.compute_compiled_depths(&live, &plans));
129        let mut operations_by_layer: Vec<Vec<usize>> = Vec::new();
130        for (operation_index, operation) in self.operations.iter().enumerate() {
131            if !live[operation_index] {
132                continue;
133            }
134            let depth = compiled_depths.as_ref().map_or(operation.depth, |depths| depths[operation_index]);
135            let layer = depth as usize - 1;
136            if operations_by_layer.len() <= layer {
137                operations_by_layer.resize(layer + 1, Vec::new());
138            }
139            operations_by_layer[layer].push(operation_index);
140        }
141
142        let live_count = live.iter().filter(|&&is_live| is_live).count();
143        let value_count = source_size + live_count;
144        let mut wire_order: Vec<Wire> = (0..source_size).map(Wire::from_index).collect();
145        let mut packed_by_wire = vec![u32::MAX; width];
146        for (wire, packed) in packed_by_wire.iter_mut().enumerate().take(source_size) {
147            *packed = wire as u32;
148        }
149        // The column of each wire in the layer being compiled, reset after each layer.
150        let mut column_by_wire = vec![u32::MAX; width];
151        let mut available = source_size;
152        let mut layers = Vec::new();
153        let mut slot_by_group: HashMap<usize, u32> = HashMap::new();
154        for operation_indices in operations_by_layer.iter().filter(|indices| !indices.is_empty()) {
155            let output_size = operation_indices.len();
156            let mut input_wires: Vec<Wire> = Vec::new();
157            for &operation_index in operation_indices {
158                // Gather rows read packed values by position, not through the layer's input.
159                if plans.contains_key(&operation_index) {
160                    continue;
161                }
162                let operation = &self.operations[operation_index];
163                for &(wire, _) in operation.left_terms.iter().chain(&operation.gate_terms) {
164                    if column_by_wire[wire.index()] == u32::MAX {
165                        column_by_wire[wire.index()] = 0;
166                        input_wires.push(wire);
167                    }
168                }
169            }
170            input_wires.sort_by_key(|wire| packed_by_wire[wire.index()]);
171            for (column, wire) in input_wires.iter().enumerate() {
172                column_by_wire[wire.index()] = column as u32;
173            }
174            let gate_count =
175                operation_indices.iter().filter(|&&index| self.operations[index].kind == OpKind::Reglu).count();
176            let index_count =
177                operation_indices.iter().filter(|&&index| self.operations[index].kind == OpKind::Index).count();
178            let projection_size = output_size + gate_count + index_count;
179            let mut bias = vec![0f32; projection_size];
180            let mut projection_terms: Vec<&[(Wire, f64)]> = vec![&[]; projection_size];
181            let mut gate_rows = Vec::new();
182            let mut boolean_rows = Vec::new();
183            let mut pending_gather_reads = Vec::new();
184            let mut pending_index_reads = Vec::new();
185            let (mut gate_row, mut index_row) = (0, 0);
186            for (row, &operation_index) in operation_indices.iter().enumerate() {
187                let operation = &self.operations[operation_index];
188                let output_wire = source_size + operation_index;
189                wire_order.push(Wire::from_index(output_wire));
190                packed_by_wire[output_wire] = (available + row) as u32;
191                bias[row] = operation.left_bias as f32;
192                if let Some(plan) = plans.get(&operation_index) {
193                    // The row keeps its bias and stores no weights; the executor adds the gathered value.
194                    pending_gather_reads.push((row, plan));
195                    continue;
196                }
197                projection_terms[row] = &operation.left_terms;
198                match operation.kind {
199                    OpKind::Reglu => {
200                        let projection_row = output_size + gate_row;
201                        bias[projection_row] = operation.gate_bias as f32;
202                        projection_terms[projection_row] = &operation.gate_terms;
203                        gate_rows.push(row as u32);
204                        gate_row += 1;
205                    }
206                    OpKind::Boolean => boolean_rows.push(row as u32),
207                    OpKind::Index => {
208                        let projection_row = output_size + gate_count + index_row;
209                        bias[projection_row] = operation.gate_bias as f32;
210                        projection_terms[projection_row] = &operation.gate_terms;
211                        pending_index_reads.push((row, projection_row, operation.index_read.as_ref().unwrap()));
212                        index_row += 1;
213                    }
214                    OpKind::Affine => {}
215                }
216            }
217            let mut gather_computes = Vec::new();
218            let mut gather_reads = Vec::new();
219            for (row, plan) in pending_gather_reads {
220                let group = &self.one_hot_groups[plan.group];
221                let packed = |wire: Wire| {
222                    let position = packed_by_wire[wire.index()];
223                    assert!((position as usize) < available, "a gather's bit or candidate is not available");
224                    position
225                };
226                let next_slot = slot_by_group.len() as u32;
227                let slot = *slot_by_group.entry(plan.group).or_insert_with(|| {
228                    // The group's first read resolves its index; its bits are at earlier depths.
229                    gather_computes.push(GatherCompute {
230                        slot: next_slot,
231                        bit_positions: group.members.iter().map(|&m| packed(m)).collect(),
232                    });
233                    next_slot
234                });
235                gather_reads.push(GatherRead {
236                    row: row as u32,
237                    slot,
238                    masked: group.allow_all_zero,
239                    candidate_positions: plan.candidates.iter().map(|&candidate| packed(candidate)).collect(),
240                });
241            }
242            let index_reads = pending_index_reads
243                .into_iter()
244                .map(|(row, index_row, read)| IndexReadRow {
245                    row: row as u32,
246                    index_row: index_row as u32,
247                    below_zero: read.below == OutOfRange::Zero,
248                    above_zero: read.above == OutOfRange::Zero,
249                    candidate_positions: self.tables[read.table]
250                        .candidates
251                        .iter()
252                        .map(|candidate| {
253                            let position = packed_by_wire[candidate.index()];
254                            assert!((position as usize) < available, "index read candidate is not available");
255                            position
256                        })
257                        .collect(),
258                })
259                .collect();
260            let mut row_offsets = Vec::with_capacity(projection_size + 1);
261            let mut columns = Vec::new();
262            let mut weights = Vec::new();
263            row_offsets.push(0);
264            for terms in &projection_terms {
265                for &(wire, coefficient) in terms.iter() {
266                    let column = column_by_wire[wire.index()];
267                    assert!(column != u32::MAX, "tensor dependency is not available");
268                    columns.push(column);
269                    weights.push(coefficient as f32);
270                }
271                row_offsets.push(columns.len() as u32);
272            }
273            for wire in &input_wires {
274                column_by_wire[wire.index()] = u32::MAX;
275            }
276            layers.push(TensorLayer {
277                input_indices: input_wires.iter().map(|wire| packed_by_wire[wire.index()]).collect(),
278                output_size,
279                bias,
280                row_offsets,
281                columns,
282                weights,
283                gate_rows,
284                boolean_rows,
285                gather_computes,
286                gather_reads,
287                index_reads,
288            });
289            available += output_size;
290        }
291        TensorProgram {
292            layers,
293            roots,
294            source_size,
295            value_count,
296            wire_order,
297            width,
298            gather_slot_count: slot_by_group.len(),
299        }
300    }
301
302    /// Each live operation's depth from what it reads in the compiled program: a lowered sum reads its group's bits
303    /// and its candidates instead of its products. Without gather plans these are the build-time depths.
304    fn compute_compiled_depths(&self, live: &[bool], plans: &HashMap<usize, GatherPlan>) -> Vec<u32> {
305        let source_size = self.source_size();
306        let mut depths = vec![0u32; self.operations.len()];
307        let mut table_depths: HashMap<usize, u32> = HashMap::new();
308        for (operation_index, operation) in self.operations.iter().enumerate() {
309            if !live[operation_index] {
310                continue;
311            }
312            let depth_of = |wire: Wire| wire.index().checked_sub(source_size).map_or(0, |index| depths[index]);
313            let depth = match plans.get(&operation_index) {
314                Some(plan) => self.one_hot_groups[plan.group]
315                    .members
316                    .iter()
317                    .chain(&plan.candidates)
318                    .map(|&wire| depth_of(wire))
319                    .max()
320                    .unwrap_or(0),
321                None => {
322                    let mut depth = operation
323                        .left_terms
324                        .iter()
325                        .chain(&operation.gate_terms)
326                        .map(|&(wire, _)| depth_of(wire))
327                        .max()
328                        .unwrap_or(0);
329                    if let Some(read) = &operation.index_read {
330                        let table_depth = match table_depths.get(&read.table) {
331                            Some(&table_depth) => table_depth,
332                            None => {
333                                let table_depth = self.tables[read.table]
334                                    .candidates
335                                    .iter()
336                                    .map(|&candidate| depth_of(candidate))
337                                    .max()
338                                    .unwrap_or(0);
339                                table_depths.insert(read.table, table_depth);
340                                table_depth
341                            }
342                        };
343                        depth = depth.max(table_depth);
344                    }
345                    depth
346                }
347            };
348            depths[operation_index] = depth + 1;
349        }
350        depths
351    }
352
353    fn find_live_operations(&self, roots: &[Wire], plans: &HashMap<usize, GatherPlan>) -> Vec<bool> {
354        let source_size = self.source_size();
355        let mut live = vec![false; self.operations.len()];
356        let mut visited_tables = vec![false; self.tables.len()];
357        let mut pending = roots.to_vec();
358        while let Some(wire) = pending.pop() {
359            self.assert_wire(wire);
360            let Some(operation_index) = wire.index().checked_sub(source_size) else { continue };
361            if live[operation_index] {
362                continue;
363            }
364            live[operation_index] = true;
365            if let Some(plan) = plans.get(&operation_index) {
366                // A lowered sum reads the group's bits and every candidate, not its products.
367                pending.extend(&self.one_hot_groups[plan.group].members);
368                pending.extend(&plan.candidates);
369                continue;
370            }
371            let operation = &self.operations[operation_index];
372            pending.extend(operation.left_terms.iter().chain(&operation.gate_terms).map(|&(wire, _)| wire));
373            if let Some(read) = &operation.index_read
374                && !visited_tables[read.table]
375            {
376                visited_tables[read.table] = true;
377                pending.extend(&self.tables[read.table].candidates);
378            }
379        }
380        live
381    }
382
383    /// Every wire's value through the compiled program, with 0 for removed wires.
384    pub fn evaluate_tensor(&self, source: &[f32], program: &TensorProgram) -> Result<Vec<f32>, Error> {
385        self.validate_source_ranges(source)?;
386        let mut executor = TensorExecutor::new(program);
387        executor.run(source);
388        let mut values = vec![0f32; program.width];
389        for (packed, wire) in program.wire_order.iter().enumerate() {
390            values[wire.index()] = executor.packed_values[packed];
391        }
392        Ok(values)
393    }
394
395    /// Check that a compiled evaluation reproduces every live value of the
396    /// reference evaluator, compared with `==` like handwired's `===`.
397    pub fn validate_tensor_evaluation(
398        &self,
399        source: &[f32],
400        program: &TensorProgram,
401        tensor_values: &[f32],
402    ) -> Result<(), String> {
403        let expected = self.evaluate_unchecked(source);
404        for wire in &program.wire_order {
405            let (got, want) = (tensor_values[wire.index()], expected[wire.index()]);
406            if got != want {
407                return Err(format!("tensor wire {} is {got}, the reference evaluator gives {want}", wire.index()));
408            }
409        }
410        Ok(())
411    }
412}
413
414/// Reusable buffers for running one program many times.
415pub struct TensorExecutor<'program> {
416    program: &'program TensorProgram,
417    /// After a run, `packed_values[k]` is the value of `program.wire_order[k]`.
418    pub packed_values: Vec<f32>,
419    input: Vec<f32>,
420    projection: Vec<f32>,
421    gather_indices: Vec<i32>,
422    gather_masses: Vec<f32>,
423    root_positions: Vec<usize>,
424    outputs: Vec<f32>,
425}
426
427impl<'program> TensorExecutor<'program> {
428    pub fn new(program: &'program TensorProgram) -> TensorExecutor<'program> {
429        let max_input = program.layers.iter().map(|layer| layer.input_indices.len()).max().unwrap_or(0);
430        let max_projection = program.layers.iter().map(|layer| layer.bias.len()).max().unwrap_or(0);
431        let root_positions = program
432            .roots
433            .iter()
434            .map(|root| program.wire_order.iter().position(|wire| wire == root).expect("root was removed"))
435            .collect();
436        TensorExecutor {
437            program,
438            packed_values: vec![0.0; program.value_count],
439            input: vec![0.0; max_input],
440            projection: vec![0.0; max_projection],
441            gather_indices: vec![0; program.gather_slot_count],
442            gather_masses: vec![0.0; program.gather_slot_count],
443            root_positions,
444            outputs: vec![0.0; program.roots.len()],
445        }
446    }
447
448    /// Evaluate the program and return the roots' values. The source is not
449    /// range-checked; use [`Circuit::validate_source_ranges`] for that.
450    pub fn run(&mut self, source: &[f32]) -> &[f32] {
451        let program = self.program;
452        assert_eq!(source.len(), program.source_size, "source table has the wrong length");
453        let values = &mut self.packed_values;
454        values[..source.len()].copy_from_slice(source);
455        let mut available = source.len();
456        for layer in &program.layers {
457            for (column, &packed) in layer.input_indices.iter().enumerate() {
458                self.input[column] = values[packed as usize];
459            }
460            let projection = &mut self.projection[..layer.bias.len()];
461            for (row, output) in projection.iter_mut().enumerate() {
462                let mut value = layer.bias[row];
463                for entry in layer.row_offsets[row] as usize..layer.row_offsets[row + 1] as usize {
464                    value += layer.weights[entry] * self.input[layer.columns[entry] as usize];
465                }
466                *output = value;
467            }
468            for compute in &layer.gather_computes {
469                let (index, mass) = resolve_gather(compute.bit_positions.iter().map(|&bit| values[bit as usize]));
470                self.gather_indices[compute.slot as usize] = index;
471                self.gather_masses[compute.slot as usize] = mass;
472            }
473            for read in &layer.gather_reads {
474                let slot = read.slot as usize;
475                let contribution = gathered(values, read, self.gather_indices[slot], self.gather_masses[slot]);
476                projection[read.row as usize] += contribution;
477            }
478            for read in &layer.index_reads {
479                let index = projection[read.index_row as usize] as f64;
480                let below = if read.below_zero { OutOfRange::Zero } else { OutOfRange::Clamp };
481                let above = if read.above_zero { OutOfRange::Zero } else { OutOfRange::Clamp };
482                projection[read.row as usize] =
483                    match resolve_index_position(index, read.candidate_positions.len(), below, above) {
484                        -2 => f32::NAN,
485                        -1 => 0.0,
486                        position => values[read.candidate_positions[position as usize] as usize],
487                    };
488            }
489            for (gate, &row) in layer.gate_rows.iter().enumerate() {
490                let gate_value = relu32(projection[layer.output_size + gate]);
491                projection[row as usize] *= gate_value;
492            }
493            for &row in &layer.boolean_rows {
494                projection[row as usize] = evaluate_boolean(projection[row as usize]);
495            }
496            values[available..available + layer.output_size].copy_from_slice(&projection[..layer.output_size]);
497            available += layer.output_size;
498        }
499        for (output, &position) in self.outputs.iter_mut().zip(&self.root_positions) {
500            *output = values[position];
501        }
502        &self.outputs
503    }
504}
505
506/// A group's selected position and its sum of bits. For exact 0/1 bits both are exact small integers.
507pub(crate) fn resolve_gather(bits: impl Iterator<Item = f32>) -> (i32, f32) {
508    let (mut index, mut mass) = (0f64, 0f64);
509    for (position, bit) in bits.enumerate() {
510        index += position as f64 * bit as f64;
511        mass += bit as f64;
512    }
513    (index as i32, mass as f32)
514}
515
516/// The selected candidate, times the group's mass for a group that allows all zeros. The clamp keeps a violated
517/// one-hot declaration inside the table.
518pub(crate) fn gathered(values: &[f32], read: &GatherRead, index: i32, mass: f32) -> f32 {
519    let index = index.clamp(0, read.candidate_positions.len() as i32 - 1) as usize;
520    let candidate = values[read.candidate_positions[index] as usize];
521    if read.masked { mass * candidate } else { candidate }
522}