Replay Buffer
replay_buffer.nr78 lines
replay_buffer.nr· neuro
// Range `.rev()` and `.step(n)` driving a replay buffer, alongside earlier
// features. Integration example: `.rev()` and `.step(n)` in a `for` head and on a tensor
// index axis, static tensor types, slicing, `.sum()`, `.enumerate()` with `.rev()`, a
// `.filter(p)` adapter, and a labeled `break`. A replay buffer is written oldest first and
// read newest first, and `.rev()` is the only change between the two. The reversed index
// produces a fresh tensor, so the buffer keeps its own order.
@derive(Copy, Clone)
struct Frame {
reward: i32,
step: i32
}
impl Frame {
// Later frames count for more: the discount is undone by how recent it is.
func weighted(&self) -> i32 {
self.reward * (self.step + 1)
}
}
func main() -> i32 {
// Written in the order the episode happened.
val episode: Tensor<i32, [6]> = [2, 4, 6, 8, 10, 12]
val total = episode.sum()
println("episode = {episode[0]} .. {episode[5]} (sum {total})")
// Reading it back newest-first is one `.rev()` on the axis, and it copies:
// `episode` is untouched, which the second reduction below proves.
val replay: Tensor<i32, [6]> = episode[(0..6).rev()]
println("replay[0] = {replay[0]} (episode[0] still {episode[0]})")
// The tail three frames, themselves newest-first.
val tail: Tensor<i32, [3]> = episode[(3..6).rev()]
println("tail newest-first = {tail[0]} {tail[1]} {tail[2]}")
// Walking the buffer backwards while the position climbs: the position is a
// recency rank, the value is the frame index it names.
mut weighted = 0
for (rank, index) in (0..6).rev().enumerate() {
val frame = Frame { reward: replay[rank as i32], step: index }
weighted += frame.weighted()
}
println("weighted replay = {weighted}")
// Adapters ride above the reversal: descending frames, odd ones dropped.
mut kept = ""
for v in (0..6).rev().filter(|n: i32| -> bool { n % 2 == 0 }) {
kept += "{v} "
}
println("even frames = {kept}")
// A descending scan that stops early. `break` leaves a reversed loop the way
// it leaves any other.
mut first_small = -1
'scan: for i in (0..6).rev() {
if replay[i] < 6 {
first_small = i
break 'scan
}
}
println("first below six = index {first_small}")
// Frame skipping. `.step(2)` keeps every other frame; under `.rev()` it starts
// from the newest one, so the skipped replay is 12, 8, 4 and not 10, 6, 2.
val skipped: Tensor<i32, [3]> = episode[(0..6).rev().step(2)]
println("every other frame = {skipped[0]} {skipped[1]} {skipped[2]}")
mut sampled = 0
for i in (0..6).step(2) {
val frame = Frame { reward: episode[i], step: i }
sampled += frame.weighted()
}
println("sampled weighted = {sampled}")
val answer = total + first_small + (weighted % 50)
println("answer = {answer}")
answer
}
neuroc run replay_buffer.nr
episode = 2 .. 12 (sum 42)
replay[0] = 12 (episode[0] still 2)
tail newest-first = 12 10 8
weighted replay = 182
even frames = 4 2 0
first below six = index 5
every other frame = 12 8 4
sampled weighted = 70
answer = 79