Batch Arena
batch_arena.nr141 lines
batch_arena.nr· neuro
// A batched forward pass run inside nested `pool` arenas. Integration example:
// `pool` with a `PoolAware` type, `@` and element-wise tensor operators, tensor reductions,
// and a struct method on `&self`. Weights and totals live outside the arena and survive it.
// Each step's intermediates live inside it and are released together at the closing brace.
// Scalars may cross the block, no tensor declared before it is written inside it, and no
// `break` or `return` leaves it. `StepLog` has a destructor, so it needs `PoolAware`;
// deleting that impl stops the program compiling. The `headline` string is routed to the
// heap because its binding predates the block. `headline = opened_note` would not compile,
// since that buffer came from the arena.
// A running tally, carried across the batches on the stack rather than in the
// arena. Its fields are scalars, so it never allocates at all.
struct Tally {
steps: i32,
total: f32,
last: string
}
impl Tally {
// `&self` reads the tally without consuming it, so the same value can be
// rendered and then kept.
func render(&self) -> string {
return "{self.steps} batches, mean sum {self.total:.3}"
}
// `&mut self` is a channel into memory the CALLER holds. Called from inside the
// arena on a tally declared outside it, this store is only sound because of what
// it is handed: see the note on `summarize` below.
func record(&mut self, note: string) {
self.last = note
}
}
// Called from inside the arena, written outside it. Every allocation this makes is
// emitted with its own body, so the text it hands back is heap memory and may be stored
// into a binding that outlives the pool.
func summarize(step: i32, mean: f32) -> string {
return "kept step {step} at mean {mean:.3}"
}
// A per-step scratch note, built inside the arena. It holds a destructor, so it is
// exactly the shape a pool would otherwise refuse.
struct StepLog {
step: i32
}
impl Drop for StepLog {
func drop(&mut self) {
println(" step {self.step} closed")
}
}
// The opt-in. `register_with_pool` hands the arena the handle this value owns, and
// `bulk_release` is what the arena calls to give it back. Both run: the first at the
// point the value is constructed, the second during the arena's sweep at the closing
// brace: and never the `Drop` above, which is the whole trade the trait offers.
// The sweep walks registrations in reverse, so of the two notes each step builds, the
// one opened last is the one released first.
impl PoolAware for StepLog {
func register_with_pool(&self, arena: &PoolHandle) {
}
func bulk_release(&mut self) {
println(" note {self.step} released")
}
}
func main() -> i32 {
// The weights outlive every pool below: they are what a real training loop
// would keep across batches.
val weights: Tensor<f32, [4, 3]> = [
[0.5, 0.0, 0.25],
[0.0, 0.5, 0.25],
[0.25, 0.0, 0.5],
[0.0, 0.25, 0.5]
]
val bias: Tensor<f32, [3]> = [1.0, 2.0, 3.0]
val batch: Tensor<f32, [2, 4]> = [
[1.0, 2.0, 3.0, 4.0],
[4.0, 3.0, 2.0, 1.0]
]
mut running: f32 = 0.0
mut steps: i32 = 0
// Declared outside every arena, and written from inside the innermost one. The
// compiler routes the concatenation off the bump region because this binding is the
// proven owner, which is what lets the line survive both closing braces below.
mut headline: string = "no batches yet"
// Declared before the arena, so it survives every block below: which is exactly
// what makes `tally.record(...)` inside them a rule the compiler has to check.
mut tally = Tally { steps: 0, total: 0.0, last: "no batches yet" }
pool training {
println("bias total = {bias.sum():.2}")
for step in 0..4 {
pool batch_scratch {
// Every tensor below is allocated in the arena: `@` contracts the
// shared axis of a `[2, 4]` against a `[4, 3]`, the scalar stretches
// across every element, and the `[3]` bias broadcasts down both rows.
val activations = &batch @ &weights
val scaled = &activations * 0.5
val shifted = &scaled + &bias
val mean = shifted.mean()
val top = shifted.max()
val opened = StepLog { step: step }
val queued = StepLog { step: step + 100 }
println("step {opened.step}: mean={mean:.3} max={top:.3}")
// Scalars may cross the arena boundary; the tensors above may not.
running += mean
steps += 1
// A routed store: `headline` outlives the block, so this text is built
// on the heap even though the statement sits two arenas deep.
headline = "step {step} peaked at " + "{top:.3}"
// And so may this string, because the compiler can trace it to the heap.
// Passing it THROUGH a `&mut self` method is checked on the same terms:
// `tally.record("step " + "{step}")` does not compile, because that text
// is arena memory and `tally` outlives the block that allocated it.
tally.record(summarize(step, mean))
}
}
}
// Both arenas are back to their marks by here. The routed line and the line the
// callee stored both still read correctly, for two different reasons: the first was
// built off the arena because its owner was known, the second because the callee's
// body is emitted outside every arena.
println(headline)
println(tally.last)
tally.steps = steps
tally.total = running
println(tally.render())
steps
}
neuroc run batch_arena.nr
bias total = 6.00
step 0: mean=3.250 max=5.125
note 100 released
note 0 released
step 1: mean=3.250 max=5.125
note 101 released
note 1 released
step 2: mean=3.250 max=5.125
note 102 released
note 2 released
step 3: mean=3.250 max=5.125
note 103 released
note 3 released
step 3 peaked at 5.125
kept step 3 at mean 3.250
4 batches, mean sum 13.000