Streaming Stats
streaming_stats.nr95 lines
streaming_stats.nr· neuro
// Feature statistics gathered row by row from batches of any size. Integration example:
// tensors as `for` heads in all three receiver modes alongside a `?B` batch extent, a
// `Float`-generic function, a struct whose `&mut self` method writes its tensors through
// a loop, `Result` with `?` leaving a loop early, a `pool` block around per-row scratch
// tensors, a closure over a lent row, masks reduced with `.any()` / `.count()` on lent rows,
// and `std::testing::all_close` checking the in-place scaling against a by-value one.
import std::testing::{all_close}
struct Running {
sum: Tensor<f64, [3]>,
peak: Tensor<f64, [3]>,
rows: i32
}
impl Running {
func new() -> Running {
Running {
sum: Tensor::<f64, [3]>::zeros(),
peak: Tensor::<f64, [3]>::zeros(),
rows: 0
}
}
// Every row of a batch is lent in turn. A row holding a negative value stops the
// batch with its position, and the rows before it stay counted.
func absorb(&mut self, batch: &Tensor<f64, [?B, 3]>) -> Result<i32, i32> {
for (i, row) in batch.enumerate() {
if (row < 0.0).any() {
return Result::Err(i as i32)
}
self.sum += row
for (c, peak) in (&mut self.peak).enumerate() {
if row[c as i32] > *peak {
*peak = row[c as i32]
}
}
self.rows += 1
}
Result::Ok(self.rows)
}
}
// Divides every row by `scale` in place, whatever float the tensor holds.
func shrink<T: Float, R, C>(m: &mut Tensor<T, [R, C]>, scale: T) {
for row in m {
for x in row {
*x = *x / scale
}
}
}
func absorb_both(stats: &mut Running, first: &Tensor<f64, [?B, 3]>, second: &Tensor<f64, [?C, 3]>) -> Result<i32, i32> {
val _after_first = stats.absorb(first)?
stats.absorb(second)
}
func main() -> i32 {
val first: Tensor<f64, [2, 3]> = [[1.0, 8.0, 3.0], [4.0, 2.0, 9.0]]
val second: Tensor<f64, [3, 3]> = [[7.0, 1.0, 1.0], [2.0, -1.0, 2.0], [100.0, 100.0, 100.0]]
mut stats = Running::new()
match absorb_both(&mut stats, &first, &second) {
Result::Ok(rows) => println("absorbed {rows} rows"),
Result::Err(at) => println("stopped at row {at} after {stats.rows} rows")
}
println("sum = {stats.sum[0]} {stats.sum[1]} {stats.sum[2]}")
println("peak = {stats.peak[0]} {stats.peak[1]} {stats.peak[2]}")
mut scaled = first.clone()
shrink(&mut scaled, 2.0)
// The scratch tensor each row needs lives in the arena, and only a number leaves it.
mut energy = 0.0
mut above_one: u64 = 0
for row in &scaled {
pool {
val squares = row * row
energy += squares.sum()
above_one += (&squares > 1.0).count()
}
}
println("energy of the halved batch = {energy}, {above_one} squares above 1")
println("halved in place matches halved by value: {all_close(&scaled, &(first.clone() * 0.5), 0.0)}")
// A closure reads the row it is built over, and the by-value head consumes `first`.
mut spread = 0.0
for row in first {
val range_of = |scale: f64| -> f64 { (row.max() - row.min()) * scale }
spread += range_of(2.0)
}
println("spread = {spread}")
(spread + energy) as i32
}
neuroc run streaming_stats.nr
stopped at row 1 after 3 rows
sum = 12.0 11.0 13.0
peak = 7.0 8.0 9.0
energy of the halved batch = 43.75, 4 squares above 1
halved in place matches halved by value: true
spread = 28.0