diff --git a/infra/docs/runbook.md b/infra/docs/runbook.md index 4b5e9f3..4d6aa75 100644 --- a/infra/docs/runbook.md +++ b/infra/docs/runbook.md @@ -1182,13 +1182,24 @@ loud which backend is configured. Two separate switches, deliberately: | build | `FLY_CARGO_FEATURES=cuda` | `build-flysim.sh` | the backend is *compiled in*, `libcuda` still only `dlopen`ed | | run | `FLY_LIF_CUDA=1` | the env file → `/etc/fly/fly.env` | the backend is *attached* | -A binary without the feature ignores `FLY_LIF_CUDA=1` **silently**, so confirm the +A `flysim` binary without the feature ignores `FLY_LIF_CUDA=1` **silently**, so confirm the backend from flysim's own log, not from the env file: ```sh pct exec -- journalctl -u flysim -b --no-pager | grep -i 'cuda\|lif backend' ``` +The session runtime (`flysim-session`, `fly-shadow`, GPU-02) reads the same two variables +(`FLY_LIF_CUDA`, `FLY_LIF_CUDA_DEVICE`, a device ordinal) in its agent worker and does **not** +ignore them: without the feature, or when the backend cannot start, `Agent.Initialize` fails +with `BACKEND_FAILURE`, and the worker logs `LIF backend cuda: attached, device-owned state` +when it starts. It steps one game frame per GPU call and keeps `membrane` and `refractory` on the +card, copying them back only for a checkpoint, so per frame only the inputs (noise draws, visual +drive, plastic gains, about 110 KB) go up and the spike lists come down. A CUDA failure mid-run +fails the agent; a restore into that worker runs on the CPU from the last checkpoint (bit-exact, so nothing is +migrated). Build all binaries with the feature: `FLY_CARGO_FEATURES=cuda` now reaches +`flysim-session`, `fly-shadow` and `fly-session` too. + It needs `GPU=1` (the `/dev/nvidia*` device block plus the userspace driver in the container — `docs/design/gpu.md` sections 1 and 2) and the card the committed PTX targets, `sm_75`. diff --git a/services/flysim/crates/fly-legacy-session/Cargo.toml b/services/flysim/crates/fly-legacy-session/Cargo.toml index 56d86a8..dbdb5fb 100644 --- a/services/flysim/crates/fly-legacy-session/Cargo.toml +++ b/services/flysim/crates/fly-legacy-session/Cargo.toml @@ -21,6 +21,11 @@ path = "src/bin/flysim-session.rs" name = "fly-shadow" path = "src/bin/fly-shadow.rs" +[features] +# The LIF tick on the GPU (GPU-02), for `flysim-session` and `fly-shadow`: the same switch as +# flysim's, so `FLY_CARGO_FEATURES=cuda infra/build/build-flysim.sh` builds every binary with it. +cuda = ["fly-session/cuda", "flysim/cuda"] + [dependencies] # The session framework and its legacy workers (AGENT-01, ENV-01). fly-session = { path = "../fly-session" } diff --git a/services/flysim/crates/fly-session/Cargo.toml b/services/flysim/crates/fly-session/Cargo.toml index 1af661b..80ba089 100644 --- a/services/flysim/crates/fly-session/Cargo.toml +++ b/services/flysim/crates/fly-session/Cargo.toml @@ -18,6 +18,11 @@ path = "src/lib.rs" name = "fly-session" path = "src/bin/fly-session.rs" +[features] +# The LIF tick on the GPU (GPU-02), a passthrough to `flybrain-core/cuda`. Compiling it in does not +# turn it on: the agent worker attaches the backend only when `FLY_LIF_CUDA=1` reaches it. +cuda = ["flybrain-core/cuda"] + [dependencies] # The domain contract (scalars, payloads, canonical digests, the trace format) and the bus. # Everything else this crate needs is std or Tokio. diff --git a/services/flysim/crates/fly-session/src/launcher.rs b/services/flysim/crates/fly-session/src/launcher.rs index d1e2a51..e433fbb 100644 --- a/services/flysim/crates/fly-session/src/launcher.rs +++ b/services/flysim/crates/fly-session/src/launcher.rs @@ -1671,6 +1671,9 @@ pub(crate) fn legacy_agent_config(spec: &LegacyAgentLaunch, worker_threads: usiz dataset_dir: spec.dataset_dir.clone(), profile: spec.profile, macro_channels: spec.macro_channels.clone(), + // The deployment's switch, read where the worker runs: a thread, or a child process + // that inherited the launcher's environment. + lif_backend: flybrain_core::lif::LifBackend::from_env(), } } diff --git a/services/flysim/crates/fly-session/src/legacy_agent.rs b/services/flysim/crates/fly-session/src/legacy_agent.rs index 595a5ac..79174b0 100644 --- a/services/flysim/crates/fly-session/src/legacy_agent.rs +++ b/services/flysim/crates/fly-session/src/legacy_agent.rs @@ -42,7 +42,7 @@ use flybrain_core::envelope::{ agent_from_chunks, agent_to_chunks, decode_envelope, encode_envelope, }; use flybrain_core::json::JsonValue; -use flybrain_core::lif::{LifConfig, SweepPlan, kernel_version}; +use flybrain_core::lif::{LifBackend, LifConfig, SweepPlan, kernel_version}; use serde_json::{Value, json}; use crate::clock::TickAccumulator; @@ -460,6 +460,10 @@ pub struct LegacyAgentConfig { pub profile: LegacyProfileKind, /// The composition's `executor.macroChannels`, in composition order; empty in raw mode. pub macro_channels: Vec, + /// Where the LIF tick runs (GPU-02): `FLY_LIF_CUDA` / `FLY_LIF_CUDA_DEVICE` as the launcher + /// read them, or why they could not be read. Never identity: the GPU tick is bit-exact, so + /// the compatibility digest and every checkpoint are the CPU's. + pub lif_backend: Result, } #[derive(Clone, Debug, PartialEq, Eq)] @@ -511,12 +515,15 @@ pub struct LegacyAgentWorker { /// The brain time before the in-flight transition's ticks: the spike window's start. transition_start_ms: f64, /// The in-flight transition's spike bitset, gathered tick by tick from the kernel's spike - /// lists during Prepare (PERF-01). It is the bitset `spike_bitset` would scan out of - /// `last_spike_ms` for the same window, without the 139,255-neuron scan. `None` when the - /// kernel keeps no per-tick list (the GPU backend): Commit scans as before. + /// lists during Prepare (PERF-01; on the GPU too since GPU-02). It is the bitset + /// `spike_bitset` would scan out of `last_spike_ms` for the same window, without the + /// 139,255-neuron scan. `None` only before a Prepare: Commit then scans. tick_spikes: Option>, staged: Option, activated: BTreeSet, + /// Set once the GPU backend has failed in this worker: every agent it builds from then on + /// (a restore after the failure) runs on the CPU. + backend_fault: Option, /// Every mutation this worker applied, reported as its progress counter. mutations: u64, /// Reinforcement calls applied since the fly's fresh start; captured. @@ -715,6 +722,7 @@ impl LegacyAgentWorker { prepared: None, transition_start_ms: 0.0, tick_spikes: None, + backend_fault: None, staged: None, activated: BTreeSet::new(), mutations: 0, @@ -933,7 +941,28 @@ impl LegacyAgentWorker { if self.config.worker_threads > 1 { let plan = SweepPlan::with_threads(self.config.worker_threads) .map_err(|e| DomainError::invalid(format!("sweep plan: {e}")))?; - agent.set_sweep_plan(plan); + // Without the core's `FLY_LIF_CUDA` test hook: the backend is this worker's choice. + agent.network.configure_sweep(plan); + } + let backend = self.config.lif_backend.clone().map_err(|e| { + DomainError::before(ErrorCode::BackendFailure, format!("LIF backend: {e}")) + })?; + let backend = match (&self.backend_fault, backend) { + (Some(_), LifBackend::Cuda { .. }) => LifBackend::Cpu, + (_, backend) => backend, + }; + agent.network.set_backend(backend).map_err(|e| { + DomainError::before( + ErrorCode::BackendFailure, + format!("LIF backend {}: {e}", backend.label()), + ) + })?; + if backend != LifBackend::Cpu { + eprintln!( + "legacy agent {}: LIF backend {} attached, device-owned state", + self.config.agent_id, + backend.label() + ); } let fingerprint = self.profile.dataset_fingerprint.clone(); let graph = AgentGraph { @@ -1169,22 +1198,27 @@ impl LegacyAgentWorker { let phase_before = agent.network.timings().total_ns(); let phases_before = agent.network.timings(); let ticks_span = crate::profile::span("agent.ticks"); - // One tick at a time is the loop `step(ticks)` runs; after each, the neurons it stamped - // are its spike list, so the transition's bitset is their union. + // The frame's ticks in one call (GPU-02): on the CPU the one-tick loop `step(ticks)` + // runs, on the GPU one batch with the state left on the device. Either way each tick's + // spike list is OR-ed into the transition's bitset, which is the window `spike_bitset` + // would scan out of `last_spike_ms`. let mut bits = vec![0u8; agent.network.last_spike_ms.len().div_ceil(8)]; - let mut listed = true; - for _ in 0..ticks { - let count = agent.network.step(1) as usize; - match agent.network.tick_spikes(count) { - Some(list) if listed => { - for &neuron in list { - bits[neuron as usize >> 3] |= 1 << (neuron & 7); - } - } - _ => listed = false, - } + if let Err(e) = agent.network.step_frame(ticks, &mut bits) { + eprintln!( + "legacy agent {}: {e}; the agent fails and the next restore runs on the CPU", + self.config.agent_id + ); + self.backend_fault = Some(e.to_string()); + return Err(applied( + ErrorCode::BackendFailure, + format!("the brain ticks failed: {e}"), + )); } - self.tick_spikes = listed.then_some(bits); + if let Some(fault) = agent.network.take_backend_fault() { + eprintln!("legacy agent {}: {fault}", self.config.agent_id); + self.backend_fault = Some(fault); + } + self.tick_spikes = Some(bits); drop(ticks_span); crate::profile::record( "agent.ticks.phase_clock", @@ -1551,6 +1585,19 @@ impl LegacyAgentWorker { )); } let params: CaptureParams = ctx.params()?; + // With a device-owned GPU backend this is where `membrane` and `refractory` come back + // over PCIe: at checkpoints only (GPU-02). A no-op on the CPU. + { + let _span = crate::profile::span("agent.capture.sync_host"); + let agent = self.agent.as_mut().expect("initialized"); + if let Err(e) = agent.network.sync_host() { + self.backend_fault = Some(e.to_string()); + return Err(applied( + ErrorCode::BackendFailure, + format!("the device state cannot be read back: {e}"), + )); + } + } // The boundary's state, taken under the endpoint's lock: a copy, as the legacy loop's // `export_state` is. Encoding, digesting and sealing it -- milliseconds on the full // connectome -- run after the lock is released (`HandlerReply::deferred`), so the next diff --git a/services/flysim/crates/fly-session/tests/cuda_session.rs b/services/flysim/crates/fly-session/tests/cuda_session.rs new file mode 100644 index 0000000..445180f --- /dev/null +++ b/services/flysim/crates/fly-session/tests/cuda_session.rs @@ -0,0 +1,169 @@ +//! GPU-02: the legacy agent worker on the CUDA LIF backend, against the CPU reference, on the real +//! connectome. +//! +//! The worker steps a frame per `step_frame` call with the state left on the device, and syncs it +//! back only for `State.Capture`. This runs a FAFB scenario with every kind of step the session +//! takes -- frames with sugar, reward pulses and reinforcement, a rollback, a restore into a +//! fresh worker (and so a fresh backend fed by an imported checkpoint), full-state checkpoints -- +//! through the worker on the GPU, in-process and as a process, at one and two sweep threads, and +//! requires every record (decision, telemetry, the transition's spike bitset digest, the full +//! state digest at each checkpoint) to equal `NeuralAgent` driven directly on the CPU. +//! +//! An explicit job: `--features cuda`, `FLY_GPU02_CUDA=1`, a visible device and `data/fafb-v783`. +//! `FLY_GPU02_FRAMES` sets the length (default 300 frames, about 5,000 ticks). The worker picks the +//! GPU up from `FLY_LIF_CUDA=1`, set here before any worker starts; a build or a host that cannot +//! attach the backend fails `Agent.Initialize` rather than passing on the CPU. +#![cfg(feature = "cuda")] + +use std::sync::Arc; + +use fly_session::ExecutionMode; +use fly_session::legacy_agent::LegacyProfileKind; +use fly_session::legacy_parity::{ + self, DirectSource, LegacyRig, LegacyScript, ReferenceSource, RewardEvent, RigAgent, + ScriptStep, fafb_dir, frame_pool, +}; +use fly_session::types::id; +use fly_session_types::gameboy::{Location, ReadoutContext}; +use flybrain_core::dataset::load_brain_dataset_from_dir; + +fn pokered_channels() -> Vec { + let file = fly_session_types::fixtures::load("gameboy-decoder-config.json").expect("vectors"); + file["cases"][1]["macroChannels"] + .as_array() + .expect("the Pokemon Red macro group") + .iter() + .map(|c| c.as_str().expect("a channel").to_owned()) + .collect() +} + +fn script(frames: usize) -> LegacyScript { + let channels = pokered_channels(); + let bound = |k: usize| -> Vec { + let take: &[usize] = match k % 120 { + 0..20 => &[], + 20..50 => &[0, 1, 9], + _ => &[1, 4, 5, 6], + }; + take.iter().map(|i| channels[*i].clone()).collect() + }; + let rollback_at = frames * 2 / 5; + let restore_at = frames * 7 / 10; + let mut steps = Vec::new(); + for k in 1..=frames { + steps.push(ScriptStep::Frame { + sugar: if k % 97 == 12 { vec![400.0] } else { vec![] }, + frame: k % 6, + rewards: if k % 11 == 0 { + vec![RewardEvent { + value: 0.5, + stimulation_ms: 120.0, + }] + } else { + vec![] + }, + next_context: ReadoutContext { + boot: k < 10, + bound: bound(k), + location: (k > 5).then_some(Location { + area: 12, + x: 3 + (k / 40) as u32, + y: 7, + }), + }, + }); + if k == rollback_at { + steps.push(ScriptStep::Rollback { + frame: 2, + context: ReadoutContext { + boot: false, + bound: bound(k), + location: None, + }, + }); + } + if k == restore_at { + steps.push(ScriptStep::Restore); + } + } + let last = steps.len() - 1; + let checkpoints = (0..steps.len()) + .filter(|i| i % 50 == 49) + .chain([last]) + .collect(); + LegacyScript { + name: "gpu02-fafb".to_owned(), + macro_channels: channels, + frames: Arc::new(frame_pool(6, 783)), + initial_frame: 0, + initial_context: ReadoutContext { + boot: true, + bound: vec![], + location: None, + }, + steps, + checkpoints, + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn the_gpu_worker_matches_the_cpu_reference_on_fafb() { + if std::env::var_os("FLY_GPU02_CUDA").is_none() { + eprintln!("skipping: FLY_GPU02_CUDA is not set"); + return; + } + let Some(dir) = fafb_dir() else { + eprintln!("skipping: data/fafb-v783 is not present in this checkout"); + return; + }; + let frames = std::env::var("FLY_GPU02_FRAMES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(300); + let script = script(frames); + let dataset = Arc::new(load_brain_dataset_from_dir(&dir).expect("the dataset loads")); + let started = std::time::Instant::now(); + let want = DirectSource { dataset } + .records(&script) + .expect("the CPU reference runs"); + eprintln!( + "cpu reference: {} records in {:?}, digest {}", + want.len(), + started.elapsed(), + legacy_parity::golden_json(&script, &want)["digest"] + ); + // SAFETY: the only test in this binary, and no worker (thread or child) exists yet; every + // worker started from here on reads the switch through `LifBackend::from_env`. + unsafe { std::env::set_var("FLY_LIF_CUDA", "1") }; + for (mode, threads) in [ + (ExecutionMode::InProcess, 1), + (ExecutionMode::InProcess, 2), + (ExecutionMode::Process, 2), + ] { + let started = std::time::Instant::now(); + let root = tempfile::tempdir().expect("tmp"); + let agent = RigAgent { + agent_id: id("fly-a"), + port_id: id("p1"), + dataset_dir: dir.clone(), + profile: LegacyProfileKind::Production, + macro_channels: script.macro_channels.clone(), + worker_threads: threads, + }; + let mut rig = LegacyRig::start(root.path(), mode, &[agent]) + .await + .expect("the rig"); + let got = legacy_parity::run_on_worker(&mut rig, &id("fly-a"), &script) + .await + .unwrap_or_else(|e| panic!("{} x{threads}: {e}", mode.label())); + rig.stop().await; + legacy_parity::compare(&want, &got) + .unwrap_or_else(|e| panic!("{} x{threads}: {e}", mode.label())); + eprintln!( + "gpu worker {} x{threads}: {} records identical to the CPU in {:?}", + mode.label(), + got.len(), + started.elapsed() + ); + } +} diff --git a/services/flysim/crates/flybrain-core/examples/cuda_exact.rs b/services/flysim/crates/flybrain-core/examples/cuda_exact.rs index 22bd083..cec0798 100644 --- a/services/flysim/crates/flybrain-core/examples/cuda_exact.rs +++ b/services/flysim/crates/flybrain-core/examples/cuda_exact.rs @@ -21,13 +21,23 @@ //! ``` //! //! Optional arguments: a dataset directory, then the tick count, then the CPU thread count for the -//! reference run (default 4). +//! reference run (default 4), then the mode: `tick` (the default, above) or `frame`. +//! +//! `frame` is the session runtime's shape since GPU-02: both sides step a game frame (16 or 17 +//! ticks) per [`LifNetwork::step_frame`] call, the GPU with device-owned state, so `membrane` and +//! `refractory` stay on the card. After every frame the frame's spike bitset and everything the +//! host keeps (the spike stamps, the RNG, the clock, the rates, the plasticity) are compared; +//! `membrane` and `refractory` only at the checkpoints the session would take: every 60 frames +//! through `export_state` while the host copy is stale (the download path), and every 300 frames +//! after `sync_host` (the capture path), plus a checkpoint round trip (the GPU network imports the +//! CPU's exported state halfway). The device-owned run's PCIe traffic per frame is printed. +//! `FLY_LIF_CUDA_DEVICE` picks the card in both modes (default 0). use std::sync::Arc; use std::time::Instant; use flybrain_core::dataset::load_brain_dataset_from_dir; -use flybrain_core::lif::{LifConfig, LifNetwork, SweepPlan}; +use flybrain_core::lif::{LifBackend, LifConfig, LifNetwork, LifState, SweepPlan}; use flybrain_core::plasticity::PlasticityConfig; #[cfg(feature = "cuda")] @@ -101,6 +111,95 @@ fn scalar(what: &str, tick: u64, cpu: f64, gpu: f64) -> Option { }) } + +/// Every field of two exported states, in a fixed order; the first difference. +fn compare_states( + tick: u64, + role_names: &[String], + left: &LifState, + right: &LifState, +) -> Option { + compare_f32("membrane", tick, &left.membrane, &right.membrane) + .or_else(|| { + left.refractory + .iter() + .zip(right.refractory.iter()) + .position(|(a, b)| a != b) + .map(|index| Divergence { + tick, + what: format!( + "refractory[{index}]: cpu {} vs gpu {}", + left.refractory[index], right.refractory[index] + ), + }) + }) + .or_else(|| { + compare_f64( + "lastSpikeMs", + tick, + &left.last_spike_ms, + &right.last_spike_ms, + ) + }) + .or_else(|| scalar("ms", tick, left.ms, right.ms)) + .or_else(|| { + scalar( + "populationRate", + tick, + left.population_rate, + right.population_rate, + ) + }) + .or_else(|| { + scalar( + "rewardRemaining", + tick, + left.reward_remaining, + right.reward_remaining, + ) + }) + .or_else(|| { + (left.rng != right.rng).then(|| Divergence { + tick, + what: format!("rng: cpu {} vs gpu {}", left.rng, right.rng), + }) + }) + .or_else(|| { + role_names.iter().find_map(|name| { + scalar( + &format!("rate {name}"), + tick, + left.rates.get_or_zero(name), + right.rates.get_or_zero(name), + ) + }) + }) + .or_else(|| { + compare_f32( + "plasticity.gains", + tick, + &left.plasticity.gains, + &right.plasticity.gains, + ) + }) + .or_else(|| { + compare_f32( + "plasticity.traces", + tick, + &left.plasticity.traces, + &right.plasticity.traces, + ) + }) + .or_else(|| { + compare_f64( + "plasticity.touched", + tick, + &left.plasticity.touched, + &right.plasticity.touched, + ) + }) +} + #[cfg(not(feature = "cuda"))] fn main() { eprintln!("cuda_exact: build with --features cuda"); @@ -121,6 +220,14 @@ fn main() { .next() .and_then(|value| value.parse().ok()) .unwrap_or(4); + let mode = args.next().unwrap_or_else(|| "tick".to_string()); + let device = match LifBackend::from_values( + Some("1"), + std::env::var("FLY_LIF_CUDA_DEVICE").ok().as_deref(), + ) { + Ok(LifBackend::Cuda { device }) => device, + other => panic!("FLY_LIF_CUDA_DEVICE: {other:?}"), + }; let data = Arc::new(load_brain_dataset_from_dir(&dir).expect("the dataset must load")); println!( @@ -129,6 +236,11 @@ fn main() { data.meta.neurons, data.targets.len() ); + match mode.as_str() { + "tick" => {} + "frame" => return frame_mode(&data, ticks, threads, device), + other => panic!("mode {other}: expected tick or frame"), + } let build = || { LifNetwork::new( @@ -142,7 +254,7 @@ fn main() { let mut gpu = build(); cpu.set_sweep_plan(SweepPlan::with_threads(threads).expect("a pool")); - let backend = CudaLif::new(&gpu, 0).expect("the CUDA backend must start"); + let backend = CudaLif::new(&gpu, device).expect("the CUDA backend must start"); println!( "cuda backend up: {:.1} MiB of device memory, max {} ticks per call", backend.device_bytes as f64 / (1024.0 * 1024.0), @@ -213,85 +325,7 @@ fn main() { let left = cpu.export_state(); let right = gpu.export_state(); - divergence = compare_f32("membrane", tick, &left.membrane, &right.membrane) - .or_else(|| { - left.refractory - .iter() - .zip(right.refractory.iter()) - .position(|(a, b)| a != b) - .map(|index| Divergence { - tick, - what: format!( - "refractory[{index}]: cpu {} vs gpu {}", - left.refractory[index], right.refractory[index] - ), - }) - }) - .or_else(|| { - compare_f64( - "lastSpikeMs", - tick, - &left.last_spike_ms, - &right.last_spike_ms, - ) - }) - .or_else(|| scalar("ms", tick, left.ms, right.ms)) - .or_else(|| { - scalar( - "populationRate", - tick, - left.population_rate, - right.population_rate, - ) - }) - .or_else(|| { - scalar( - "rewardRemaining", - tick, - left.reward_remaining, - right.reward_remaining, - ) - }) - .or_else(|| { - (left.rng != right.rng).then(|| Divergence { - tick, - what: format!("rng: cpu {} vs gpu {}", left.rng, right.rng), - }) - }) - .or_else(|| { - cpu.role_names.iter().find_map(|name| { - scalar( - &format!("rate {name}"), - tick, - left.rates.get_or_zero(name), - right.rates.get_or_zero(name), - ) - }) - }) - .or_else(|| { - compare_f32( - "plasticity.gains", - tick, - &left.plasticity.gains, - &right.plasticity.gains, - ) - }) - .or_else(|| { - compare_f32( - "plasticity.traces", - tick, - &left.plasticity.traces, - &right.plasticity.traces, - ) - }) - .or_else(|| { - compare_f64( - "plasticity.touched", - tick, - &left.plasticity.touched, - &right.plasticity.touched, - ) - }); + divergence = compare_states(tick, &cpu.role_names, &left, &right); if divergence.is_some() { break; } @@ -327,3 +361,147 @@ fn main() { } } } + +/// The session's shape: a frame per call, device-owned state, full state only at checkpoints. +#[cfg(feature = "cuda")] +fn frame_mode(data: &Arc, ticks: u64, threads: usize, device: usize) { + const EXPORT_EVERY: u64 = 60; + const SYNC_EVERY: u64 = 300; + let build = || { + LifNetwork::new( + Arc::clone(data), + LifConfig::default(), + PlasticityConfig::default(), + ) + .expect("a network") + }; + let mut cpu = build(); + let mut gpu = build(); + cpu.configure_sweep(SweepPlan::with_threads(threads).expect("a pool")); + gpu.set_backend(LifBackend::Cuda { device }) + .expect("the CUDA backend must start"); + println!("frame mode: gpu backend {}, device-owned state", gpu.backend().label()); + + let frames = frame_pool(24, 9_781); + let neurons = data.meta.neurons; + let count = ticks.div_ceil(FRAME_TICKS); + let started = Instant::now(); + let mut divergence: Option = None; + let mut total_spikes = 0u64; + let mut gpu_ns = 0u128; + let mut cpu_ns = 0u128; + let mut tick = 0u64; + let mut exports = 0u64; + let mut syncs = 0u64; + for frame in 0..count { + let image = &frames[frame as usize % frames.len()]; + cpu.set_visual_frame(image, FRAME_WIDTH, FRAME_HEIGHT); + gpu.set_visual_frame(image, FRAME_WIDTH, FRAME_HEIGHT); + if frame % (STIMULATE_EVERY / FRAME_TICKS) == 0 { + cpu.stimulate(12.0); + gpu.stimulate(12.0); + } + if frame > 0 && frame % (REWARD_EVERY / FRAME_TICKS) == 0 { + let ms = cpu.ms; + cpu.plasticity.reinforce(0.75, ms); + gpu.plasticity.reinforce(0.75, ms); + } + if frame == count / 2 { + // A checkpoint carried from the CPU into the GPU network mid-run. + let state = cpu.export_state(); + gpu.import_state(&state).expect("the CPU's state imports"); + } + // The session's tick count alternates 16 and 17 (548625/32768 ms per frame). + let step = if frame % 2 == 0 { FRAME_TICKS } else { FRAME_TICKS - 1 }; + let mut want = vec![0u8; neurons.div_ceil(8)]; + let mut got = vec![0u8; neurons.div_ceil(8)]; + let at = Instant::now(); + let cpu_spikes = cpu.step_frame(step, &mut want).expect("the CPU"); + cpu_ns += at.elapsed().as_nanos(); + let at = Instant::now(); + let gpu_spikes = gpu.step_frame(step, &mut got).expect("the GPU frame"); + gpu_ns += at.elapsed().as_nanos(); + if let Some(fault) = gpu.take_backend_fault() { + panic!("the GPU backend detached itself: {fault}"); + } + total_spikes += cpu_spikes; + tick += step; + if cpu_spikes != gpu_spikes || want != got { + let at = want.iter().zip(&got).position(|(a, b)| a != b); + divergence = Some(Divergence { + tick, + what: format!( + "frame {frame}: spikes cpu {cpu_spikes} vs gpu {gpu_spikes}, first bitset byte \ + differing {at:?}" + ), + }); + break; + } + // What the host keeps, every frame, without touching the device's arrays. + let left = cpu.export_state(); + let host = { + let mut copy = left.clone(); + copy.last_spike_ms = gpu.last_spike_ms.clone(); + copy.ms = gpu.ms; + copy.population_rate = gpu.population_rate; + copy.reward_remaining = gpu.reward_remaining(); + copy.rng = gpu.rng_state(); + copy.rates = gpu.rates.clone(); + copy.plasticity = gpu.plasticity.export_state(); + copy.visual_drive = gpu.visual_drive().to_vec(); + copy + }; + divergence = compare_states(tick, &cpu.role_names, &left, &host); + if divergence.is_some() { + break; + } + if frame % EXPORT_EVERY == EXPORT_EVERY - 1 { + assert!(!gpu.host_state_current(), "device-owned: the host lags between syncs"); + divergence = compare_states(tick, &cpu.role_names, &left, &gpu.export_state()); + exports += 1; + } + if divergence.is_none() && frame % SYNC_EVERY == SYNC_EVERY - 1 { + gpu.sync_host().expect("the capture sync"); + assert!(gpu.host_state_current()); + divergence = compare_f32("membrane (synced)", tick, &cpu.membrane, &gpu.membrane) + .or_else(|| { + (cpu.refractory != gpu.refractory).then(|| Divergence { + tick, + what: "refractory (synced) differs".to_string(), + }) + }); + syncs += 1; + } + if divergence.is_some() { + break; + } + } + let elapsed = started.elapsed().as_secs_f64(); + let backend = gpu.cuda().expect("still attached"); + let (up, down) = (backend.uploaded_bytes, backend.downloaded_bytes); + match divergence { + None => { + println!( + "PASS: {count} frames ({tick} ticks) bit-exact, {total_spikes} spikes, {elapsed:.1} s \ + wall (frame per call, device-owned state; host state every frame, {exports} \ + exports through the device download, {syncs} host syncs, one CPU->GPU import)" + ); + println!( + " step_frame: cpu ({threads} threads) {:.3} ms/frame, gpu {:.3} ms/frame; PCIe \ + {:.1} KB/frame up, {:.1} KB/frame down (syncs and the import included)", + cpu_ns as f64 / 1e6 / count as f64, + gpu_ns as f64 / 1e6 / count as f64, + up as f64 / 1024.0 / count as f64, + down as f64 / 1024.0 / count as f64, + ); + } + Some(divergence) => { + println!( + "FAIL: first divergence at tick {} after {:.1} s", + divergence.tick, elapsed + ); + println!(" {}", divergence.what); + std::process::exit(1); + } + } +} diff --git a/services/flysim/crates/flybrain-core/src/agent.rs b/services/flysim/crates/flybrain-core/src/agent.rs index f5cf4b6..19d83fb 100644 --- a/services/flysim/crates/flybrain-core/src/agent.rs +++ b/services/flysim/crates/flybrain-core/src/agent.rs @@ -220,8 +220,10 @@ impl NeuralAgent { bail!("Agent is already warmed up"); } self.network.plasticity.enabled = false; - self.network.step(self.warmup_ms); + // `try_step`, so a GPU backend that fails here is an error, not a panic; the CPU cannot. + let stepped = self.network.try_step(self.warmup_ms); self.network.plasticity.enabled = true; + stepped?; let rates = self.network.rates.clone(); self.decoder.calibrate(&rates); if let Some(frame) = first_frame { diff --git a/services/flysim/crates/flybrain-core/src/lif.rs b/services/flysim/crates/flybrain-core/src/lif.rs index 11ebfdf..b761d94 100644 --- a/services/flysim/crates/flybrain-core/src/lif.rs +++ b/services/flysim/crates/flybrain-core/src/lif.rs @@ -57,6 +57,64 @@ pub struct Stimulation { pub drive: f64, } +/// Which hardware runs the per-millisecond tick. +/// +/// A deployment choice, like the sweep's thread count, and never part of the compatibility +/// string: the GPU tick is bit-exact with the CPU one (`lif/cuda.rs`), so a checkpoint moves +/// between the two in either direction. The CUDA variant needs the `cuda` feature; asking for it +/// in a build without the feature is an error from [`LifNetwork::set_backend`], never a silent CPU +/// run. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum LifBackend { + #[default] + Cpu, + /// The CUDA backend on device ordinal `device`, with device-owned state. + Cuda { device: usize }, +} + +impl LifBackend { + /// `FLY_LIF_CUDA=1` asks for the GPU, on device `FLY_LIF_CUDA_DEVICE` (an ordinal, default 0). + /// Any other value of `FLY_LIF_CUDA`, or none, is the CPU, as it always was. + pub fn from_env() -> std::result::Result { + Self::from_values( + std::env::var("FLY_LIF_CUDA").ok().as_deref(), + std::env::var("FLY_LIF_CUDA_DEVICE").ok().as_deref(), + ) + } + + /// [`LifBackend::from_env`] over explicit values. A device that is not an ordinal is refused + /// rather than read as 0. + pub fn from_values( + cuda: Option<&str>, + device: Option<&str>, + ) -> std::result::Result { + if cuda.map(str::trim) != Some("1") { + return Ok(LifBackend::Cpu); + } + let device = match device.map(str::trim) { + None | Some("") => 0, + Some(text) => text.parse::().map_err(|_| { + format!("FLY_LIF_CUDA_DEVICE={text}: expected a device ordinal (0, 1, ...)") + })?, + }; + Ok(LifBackend::Cuda { device }) + } + + /// `cpu` or `cuda:`, for logs. + pub fn label(&self) -> String { + match self { + LifBackend::Cpu => "cpu".to_string(), + LifBackend::Cuda { device } => format!("cuda:{device}"), + } + } + + /// Whether this build carries the CUDA backend at all. + pub const fn cuda_compiled() -> bool { + cfg!(feature = "cuda") + } +} + + #[derive(Debug, Clone, PartialEq)] pub struct LifConfig { /// Membrane decay time constant in milliseconds; decay per tick is `fround(exp(-1/decayMs))`. @@ -311,6 +369,8 @@ pub struct LifNetwork { visual_drive: Vec, reward_remaining: f64, sweep: SweepPlan, + /// Why the GPU backend was detached mid-run, until [`LifNetwork::take_backend_fault`]. + backend_fault: Option, /// When set, [`LifNetwork::step`] runs steps 1-4 and 6 on the GPU; see [`cuda`]. #[cfg(feature = "cuda")] cuda: Option>, @@ -423,6 +483,7 @@ impl LifNetwork { timings: PhaseTimings::default(), data, sweep: SweepPlan::sequential(), + backend_fault: None, #[cfg(feature = "cuda")] cuda: None, }) @@ -435,18 +496,87 @@ impl LifNetwork { /// Choose how the per-tick parallel phases are partitioned. Results do not depend on this. pub fn set_sweep_plan(&mut self, sweep: SweepPlan) { + self.configure_sweep(sweep); + // Test hook: with the `cuda` feature compiled in *and* `FLY_LIF_CUDA=1` in the + // environment, configuring a sweep plan also attaches the GPU backend, syncing the host + // arrays every batch. That is how the existing golden suite is run through the GPU + // without editing a single test. Both conditions are off by default, and with the + // feature absent this line does not exist. A host that picks its backend itself (the + // session runtime) calls `configure_sweep` and `set_backend` instead. + #[cfg(feature = "cuda")] + self.attach_cuda_if_requested(); + } + + /// [`LifNetwork::set_sweep_plan`] without the `FLY_LIF_CUDA` test hook. + pub fn configure_sweep(&mut self, sweep: SweepPlan) { let threads = sweep.threads(); self.target_shards = target_shards(&self.data, threads); self.slot_shards = self.plasticity.slot_shards(threads); self.rows_ascending = threads > 1 && rows_are_target_ascending(&self.data); self.sweep_counts = (0..threads).map(|_| AtomicUsize::new(0)).collect(); self.sweep = sweep; - // Spike hook: with the `cuda` feature compiled in *and* `FLY_LIF_CUDA=1` in the - // environment, configuring a sweep plan also attaches the GPU backend. That is how the - // existing golden suite is run through the GPU without editing a single test. Both - // conditions are off by default, and with the feature absent this line does not exist. + } + + /// Run the tick on `backend` from now on. Results do not depend on this. + /// + /// [`LifBackend::Cuda`] attaches the GPU backend with device-owned state (or switches one the + /// test hook attached to it): the host's `membrane` and `refractory` then lag the device + /// until [`LifNetwork::sync_host`], and [`LifNetwork::export_state`] reads the device itself + /// while they do. [`LifBackend::Cpu`] syncs and detaches. A build without the `cuda` feature + /// refuses `Cuda` rather than running the CPU kernel under a GPU label. + pub fn set_backend(&mut self, backend: LifBackend) -> Result<()> { + match backend { + LifBackend::Cpu => { + #[cfg(feature = "cuda")] + if self.cuda.is_some() { + self.sync_host()?; + self.cuda = None; + } + Ok(()) + } + #[cfg(feature = "cuda")] + LifBackend::Cuda { device } => self.attach_device_owned(device), + #[cfg(not(feature = "cuda"))] + LifBackend::Cuda { device } => bail!( + "the CUDA LIF backend (device {device}) was requested, but this build has no \ + `cuda` feature" + ), + } + } + + /// The backend the tick runs on now. + pub fn backend(&self) -> LifBackend { #[cfg(feature = "cuda")] - self.attach_cuda_if_requested(); + if let Some(backend) = self.cuda.as_deref() { + return LifBackend::Cuda { + device: backend.ordinal(), + }; + } + LifBackend::Cpu + } + + /// Why the GPU backend detached itself during a step, once; `None` if it never did. + pub fn take_backend_fault(&mut self) -> Option { + self.backend_fault.take() + } + + /// Whether the host's `membrane` and `refractory` are current. Always true on the CPU. + pub fn host_state_current(&self) -> bool { + #[cfg(feature = "cuda")] + if let Some(backend) = self.cuda.as_deref() { + return !backend.host_stale(); + } + true + } + + /// Bring the host's `membrane` and `refractory` up to date with the device: a no-op on the + /// CPU or when they already are. The session calls it before a capture, so the full state + /// crosses PCIe only at checkpoints. + pub fn sync_host(&mut self) -> Result<()> { + #[cfg(feature = "cuda")] + return self.sync_host_from_cuda(); + #[cfg(not(feature = "cuda"))] + Ok(()) } pub fn sweep_plan(&self) -> &SweepPlan { @@ -508,11 +638,10 @@ impl LifNetwork { self.stimulate(duration_ms); } - /// Run `milliseconds` ticks and return the total spike count. /// The neurons the last CPU tick emitted, when `count` is what that one-tick /// [`LifNetwork::step`] returned: exactly the neurons whose `last_spike_ms` it stamped, in the /// sweep's order. `None` while the GPU backend runs the ticks, whose host copy of the list is - /// not kept per tick. A read-only view; it changes nothing a tick computes. + /// not kept per tick ([`LifNetwork::step_frame`] gathers the lists either way). A read-only view; it changes nothing a tick computes. pub fn tick_spikes(&self, count: usize) -> Option<&[u32]> { #[cfg(feature = "cuda")] if self.cuda.is_some() { @@ -521,12 +650,18 @@ impl LifNetwork { self.spikes.get(..count) } + /// Run `milliseconds` ticks and return the total spike count. + /// + /// Panics if the GPU backend fails in a way the network cannot continue from; see + /// [`LifNetwork::try_step`]. pub fn step(&mut self, milliseconds: u64) -> u64 { // The GPU backend runs the same ticks in batches and replays the host-side phases; with the // feature off this compiles to nothing and the loop below is the whole method. #[cfg(feature = "cuda")] if self.cuda.is_some() { - return self.step_on_cuda(milliseconds); + return self + .step_on_cuda(milliseconds, None) + .unwrap_or_else(|error| panic!("CUDA LIF batch failed: {error}")); } let mut total = 0u64; for _ in 0..milliseconds { @@ -535,6 +670,59 @@ impl LifNetwork { total } + /// [`LifNetwork::step`], returning a GPU failure the network cannot continue from instead of + /// panicking. On the CPU it cannot fail. + pub fn try_step(&mut self, milliseconds: u64) -> Result { + #[cfg(feature = "cuda")] + if self.cuda.is_some() { + return self.step_on_cuda(milliseconds, None); + } + Ok(self.step(milliseconds)) + } + + /// One frame's `ticks` ticks in one call, with every neuron that spiked in any of them OR-ed + /// into `spiked` (bit `n % 8` of byte `n / 8` for neuron `n`, the legacy feed's layout; the + /// caller zeroes it). Returns the total spike count. + /// + /// On the CPU this is exactly `ticks` one-tick [`LifNetwork::step`] calls with each tick's + /// [`LifNetwork::tick_spikes`] gathered, which is what the session runtime did per frame. On + /// the GPU it is one batch: the inputs go up once, the spike lists come down once, and + /// `membrane` and `refractory` stay on the device (with device-owned state). An error means + /// the backend failed and the device held the only current state: the network has been + /// moved to the CPU kernel and must be restored from a checkpoint before it steps again. A + /// failure it could continue from on the CPU is not an error; see + /// [`LifNetwork::take_backend_fault`]. + pub fn step_frame(&mut self, ticks: u64, spiked: &mut [u8]) -> Result { + let neurons = self.data.meta.neurons; + if spiked.len() < neurons.div_ceil(8) { + bail!( + "a spike bitset of {} bytes cannot hold {neurons} neurons", + spiked.len() + ); + } + #[cfg(feature = "cuda")] + if self.cuda.is_some() { + return self.step_on_cuda(ticks, Some(spiked)); + } + let mut total = 0u64; + for _ in 0..ticks { + total += self.step_one_into(Some(&mut *spiked)) as u64; + } + Ok(total) + } + + /// One CPU tick, with its spike list OR-ed into `spiked` when given. + #[inline] + fn step_one_into(&mut self, spiked: Option<&mut [u8]>) -> usize { + let count = self.step_one(); + if let Some(bits) = spiked { + for &neuron in &self.spikes[..count] { + bits[neuron as usize >> 3] |= 1 << (neuron & 7); + } + } + count + } + fn step_one(&mut self) -> usize { let neurons = self.data.meta.neurons; let threshold = self.config.threshold; @@ -797,10 +985,15 @@ impl LifNetwork { total } + /// A copy of the whole state. With a device-owned GPU backend whose host arrays are stale, + /// `membrane` and `refractory` are downloaded for the copy (and the host left as it is); a + /// caller that can handle the failure calls [`LifNetwork::sync_host`] first. Panics if that + /// download fails, because a checkpoint of stale arrays would be silently wrong. pub fn export_state(&self) -> LifState { + let (membrane, refractory) = self.current_arrays(); LifState { - membrane: self.membrane.clone(), - refractory: self.refractory.clone(), + membrane, + refractory, last_spike_ms: self.last_spike_ms.clone(), visual_drive: self.visual_drive.clone(), rng: self.rng.state(), @@ -812,6 +1005,18 @@ impl LifNetwork { } } + /// Copies of `membrane` and `refractory` as they are now: the host's, or the device's while + /// the host's are stale. + fn current_arrays(&self) -> (Vec, Vec) { + #[cfg(feature = "cuda")] + if let Some(downloaded) = self.stale_device_state() { + return downloaded.unwrap_or_else(|error| { + panic!("the device state cannot be read back for export: {error}") + }); + } + (self.membrane.clone(), self.refractory.clone()) + } + /// Import plasticity first, then validate before writing anything. pub fn import_state(&mut self, state: &LifState) -> Result<()> { if state.membrane.len() != self.membrane.len() diff --git a/services/flysim/crates/flybrain-core/src/lif/cuda.rs b/services/flysim/crates/flybrain-core/src/lif/cuda.rs index c8971e6..2287578 100644 --- a/services/flysim/crates/flybrain-core/src/lif/cuda.rs +++ b/services/flysim/crates/flybrain-core/src/lif/cuda.rs @@ -38,10 +38,19 @@ //! # State ownership //! //! Between batches the device owns `membrane` and `refractory`. With -//! [`CudaLif::sync_host_each_batch`] set (the default) they are copied back at the end of every -//! batch, which keeps `export_state`, the status endpoints and every existing test correct with no -//! further changes. Clear it for throughput work and call [`CudaLif::sync_to_host`] explicitly -//! before a checkpoint. +//! [`CudaLif::sync_host_each_batch`] set (the default for a backend built with [`CudaLif::new`]) +//! they are copied back at the end of every batch, which keeps direct reads of the network's host +//! arrays correct with no further changes: that is what `examples/cuda_exact`'s per-tick mode and +//! the `FLY_LIF_CUDA=1` golden-suite hook rely on. +//! +//! Cleared (what [`LifNetwork::set_backend`] attaches, and what the session runtime runs), the +//! device is the only up-to-date copy between host syncs and the host arrays are *stale* +//! ([`CudaLif::host_stale`]). Per frame only the batch's inputs go up (the noise draws, the visual +//! drive, the plastic gains) and its spike lists come down; [`LifNetwork::sync_host`] copies the +//! two arrays back before a checkpoint, and [`LifNetwork::export_state`] downloads them itself +//! when the host is stale, so a capture can never read old values. That is the difference between +//! about 24 MB and about 0.2 MB over PCIe per frame when the caller steps one tick per call +//! (GPU-01, section 2), and about 1.4 MB vs 0.2 MB when it steps a frame per call. use std::sync::Arc; @@ -89,6 +98,12 @@ const DEFAULT_MAX_TICKS: usize = 32; /// neither the build nor the run needs a CUDA toolkit. const LIF_PTX: &str = include_str!("../../cuda/lif.ptx"); +/// A failed batch, and whether the host phases had already been replayed when it failed. +struct BatchFailure { + error: Error, + replayed: bool, +} + fn driver_error(what: &str, error: impl std::fmt::Display) -> Error { Error::new(format!("CUDA {what} failed: {error}")) } @@ -149,6 +164,7 @@ pub struct CudaLif { bucket_rebase_kernel: CudaFunction, bucket_apply_kernel: CudaFunction, + ordinal: usize, neurons: usize, blocks: u32, max_ticks: usize, @@ -201,7 +217,14 @@ pub struct CudaLif { host_tick_counts: Vec, host_spikes: Vec, stimulation_schedule: Vec, + /// The host arrays were overwritten (an import); upload them before the next batch. host_dirty: bool, + /// The device ran ticks the host arrays have not seen: `membrane` and `refractory` on the + /// host are older than the device's. Never set while `sync_host_each_batch` holds. + host_stale: bool, + /// Bytes copied host to device and device to host by the batches, for the PCIe budget. + pub uploaded_bytes: u64, + pub downloaded_bytes: u64, /// Copy `membrane` and `refractory` back at the end of every batch. On by default, so the rest /// of the crate sees the same host state it would have seen from the CPU kernel. @@ -389,6 +412,7 @@ impl CudaLif { bucket_rebase_kernel: function("lif_bucket_rebase")?, bucket_apply_kernel: function("lif_bucket_apply")?, + ordinal, neurons, blocks, max_ticks, @@ -403,6 +427,9 @@ impl CudaLif { host_spikes: Vec::new(), stimulation_schedule: vec![false; max_ticks], host_dirty: false, + host_stale: false, + uploaded_bytes: 0, + downloaded_bytes: 0, batch_start: context .new_event(Some(CUevent_flags::CU_EVENT_DEFAULT)) .map_err(|error| driver_error("event creation", error))?, @@ -429,15 +456,28 @@ impl CudaLif { Ok(backend) } + /// The device ordinal this backend runs on. + pub fn ordinal(&self) -> usize { + self.ordinal + } + /// Ticks this backend accepts per call. pub fn max_ticks(&self) -> usize { self.max_ticks } /// The host copies of `membrane` and `refractory` have been written; re-upload them before the - /// next batch. Called by [`LifNetwork::import_state`]. + /// next batch. Called by [`LifNetwork::import_state`], which overwrites both arrays whole, so + /// the host is the current copy again. pub fn mark_host_dirty(&mut self) { self.host_dirty = true; + self.host_stale = false; + } + + /// Whether the device holds ticks the network's host `membrane` and `refractory` have not + /// seen. [`LifNetwork::sync_host`] clears it. + pub fn host_stale(&self) -> bool { + self.host_stale } /// Copy `membrane` and `refractory` from the device into the network's host arrays. @@ -450,7 +490,27 @@ impl CudaLif { .map_err(|error| driver_error("refractory download", error))?; self.stream .synchronize() - .map_err(|error| driver_error("synchronize", error)) + .map_err(|error| driver_error("synchronize", error))?; + self.downloaded_bytes += (self.neurons * 5) as u64; + self.host_stale = false; + Ok(()) + } + + /// The device's `membrane` and `refractory`, copied out without touching the network: what + /// [`LifNetwork::export_state`] reads while the host arrays are stale. + pub fn download_state(&self) -> Result<(Vec, Vec)> { + let mut membrane = vec![0.0f32; self.neurons]; + let mut refractory = vec![0u8; self.neurons]; + self.stream + .memcpy_dtoh(&self.membrane, &mut membrane[..]) + .map_err(|error| driver_error("membrane download", error))?; + self.stream + .memcpy_dtoh(&self.refractory, &mut refractory[..]) + .map_err(|error| driver_error("refractory download", error))?; + self.stream + .synchronize() + .map_err(|error| driver_error("synchronize", error))?; + Ok((membrane, refractory)) } fn upload_state(&mut self, network: &LifNetwork) -> Result<()> { @@ -460,12 +520,61 @@ impl CudaLif { self.stream .memcpy_htod(&network.refractory[..], &mut self.refractory) .map_err(|error| driver_error("refractory upload", error))?; + self.uploaded_bytes += (self.neurons * 5) as u64; self.host_dirty = false; Ok(()) } - /// Run `ticks` GPU ticks and replay the host-side phases against the spike lists they produce. - fn run_batch(&mut self, network: &mut LifNetwork, ticks: usize) -> Result { + /// Run `ticks` GPU ticks and replay the host-side phases against the spike lists they produce, + /// OR-ing every tick's spikes into `spiked` (bit `n` of byte `n / 8` for neuron `n`) when given. + /// + /// Every fallible step comes before the replay. A failure therefore leaves the host-side state + /// exactly as it was at the start of the batch except for the RNG and the stimulation + /// countdown, which the caller saved ([`BatchFailure::replayed`] is false); only a failed + /// end-of-batch download in `sync_host_each_batch` mode comes after it. + fn run_batch( + &mut self, + network: &mut LifNetwork, + ticks: usize, + spiked: Option<&mut [u8]>, + ) -> std::result::Result { + let before = |error: Error| BatchFailure { + error, + replayed: false, + }; + let spikes = self.run_device(network, ticks).map_err(before)?; + + // The host phases, per tick, in the sequential kernel's order. From here on the device + // is ahead of the host arrays until the next sync. + self.host_stale = true; + let mut at = 0usize; + let mut spiked = spiked; + for tick in 0..ticks { + let count = self.host_tick_counts[tick] as usize; + let list = &self.host_spikes[at..at + count]; + network.spikes[..count].copy_from_slice(list); + if let Some(bits) = spiked.as_deref_mut() { + for &neuron in list { + bits[neuron as usize >> 3] |= 1 << (neuron & 7); + } + } + at += count; + network.replay_host_phases(count); + } + + if self.sync_host_each_batch { + self.sync_to_host(network).map_err(|error| BatchFailure { + error, + replayed: true, + })?; + } + Ok(spikes) + } + + /// The fallible half of [`CudaLif::run_batch`]: draw, upload, launch, download the spike + /// lists. Touches nothing on the host but the RNG, the stimulation countdown and this + /// backend's own staging buffers. + fn run_device(&mut self, network: &mut LifNetwork, ticks: usize) -> Result { debug_assert!(ticks <= self.max_ticks); let neurons = self.neurons; @@ -508,7 +617,9 @@ impl CudaLif { // Uploads: the batch's noise groups, this frame's visual drive, the plastic gains permuted // into the transposed array's rank order. let used = ticks * self.noise_kicks; + let mut uploaded = 0usize; if used > 0 { + uploaded += used * 8; let mut view = self.noise_neuron.slice_mut(0..used); self.stream .memcpy_htod(&self.host_noise_neuron[..used], &mut view) @@ -519,12 +630,14 @@ impl CudaLif { .map_err(|error| driver_error("noise upload", error))?; } if !network.visual_drive.is_empty() { + uploaded += network.visual_drive.len() * 4; let mut view = self.visual_drive.slice_mut(0..network.visual_drive.len()); self.stream .memcpy_htod(&network.visual_drive[..], &mut view) .map_err(|error| driver_error("visual drive upload", error))?; } if !network.plasticity.gains.is_empty() { + uploaded += network.plasticity.gains.len() * 4; let mut view = self.gains.slice_mut(0..network.plasticity.gains.len()); self.stream .memcpy_htod(&network.plasticity.gains[..], &mut view) @@ -583,22 +696,9 @@ impl CudaLif { self.stream .synchronize() .map_err(|error| driver_error("synchronize", error))?; - - // The host phases, per tick, in the sequential kernel's order. - let mut at = 0usize; - let mut spikes = 0usize; - for tick in 0..ticks { - let count = self.host_tick_counts[tick] as usize; - network.spikes[..count].copy_from_slice(&self.host_spikes[at..at + count]); - at += count; - spikes += count; - network.replay_host_phases(count); - } - - if self.sync_host_each_batch { - self.sync_to_host(network)?; - } - Ok(spikes) + self.uploaded_bytes += uploaded as u64; + self.downloaded_bytes += ((ticks + total) * 4) as u64; + Ok(total) } /// Record phase mark `index` when phase profiling is on. @@ -839,37 +939,110 @@ impl LifNetwork { /// Attach a backend when `FLY_LIF_CUDA=1`, on device `FLY_LIF_CUDA_DEVICE` (default 0). /// + /// The test hook behind [`LifNetwork::set_sweep_plan`]: it attaches in + /// `sync_host_each_batch` mode, so every existing test that reads the host arrays directly runs + /// through the GPU unchanged. A host that chooses its backend itself uses + /// [`LifNetwork::configure_sweep`] and [`LifNetwork::set_backend`] instead. + /// /// Panics on a CUDA failure rather than falling back to the CPU: a run that asked for the GPU /// and silently got the CPU would report a bit-exactness pass that means nothing. pub(super) fn attach_cuda_if_requested(&mut self) { - if self.cuda.is_some() || std::env::var("FLY_LIF_CUDA").as_deref() != Ok("1") { + if self.cuda.is_some() { return; } - let ordinal = std::env::var("FLY_LIF_CUDA_DEVICE") - .ok() - .and_then(|value| value.parse::().ok()) - .unwrap_or(0); - match CudaLif::new(self, ordinal) { + let Ok(super::LifBackend::Cuda { device }) = super::LifBackend::from_env() else { + return; + }; + match CudaLif::new(self, device) { Ok(backend) => self.attach_cuda(backend), Err(error) => panic!("FLY_LIF_CUDA=1 but the CUDA backend would not start: {error}"), } } - /// The batched GPU path behind [`LifNetwork::step`]. - pub(super) fn step_on_cuda(&mut self, milliseconds: u64) -> u64 { + /// Attach a device-owned backend on `device`, or switch an attached one to device-owned state. + pub(super) fn attach_device_owned(&mut self, device: usize) -> Result<()> { + if self.cuda.is_none() { + let backend = CudaLif::new(self, device)?; + self.attach_cuda(backend); + } + let backend = self.cuda.as_deref_mut().expect("attached"); + backend.sync_host_each_batch = false; + Ok(()) + } + + /// Copy the device's `membrane` and `refractory` into the host arrays if they are stale. + pub(super) fn sync_host_from_cuda(&mut self) -> Result<()> { + let Some(mut backend) = self.cuda.take() else { + return Ok(()); + }; + let outcome = if backend.host_stale() { + backend.sync_to_host(self) + } else { + Ok(()) + }; + self.cuda = Some(backend); + outcome + } + + /// The device arrays when the host's are stale; `None` when the host is current. + pub(super) fn stale_device_state(&self) -> Option, Vec)>> { + let backend = self.cuda.as_deref()?; + backend.host_stale().then(|| backend.download_state()) + } + + /// The batched GPU path behind [`LifNetwork::try_step`] and [`LifNetwork::step_frame`]. + /// + /// On a CUDA failure the backend is detached and the network is on the CPU kernel from then + /// on. If the host arrays were current when the failing batch started (the backend syncs + /// every batch, or nothing ran since the last sync or import), the RNG and the stimulation + /// countdown are put back and the remaining ticks run on the CPU: the result is bit-identical + /// to a run that never had a GPU, and the reason is left in + /// [`LifNetwork::take_backend_fault`]. Otherwise the device held the only current copy of + /// `membrane` and `refractory`, so the network is not resumable and the error is returned: + /// the caller restores it from its last checkpoint. + pub(super) fn step_on_cuda( + &mut self, + milliseconds: u64, + mut spiked: Option<&mut [u8]>, + ) -> Result { let mut backend = self.cuda.take().expect("a CUDA backend is attached"); let mut total = 0u64; let mut left = milliseconds; while left > 0 { let ticks = left.min(backend.max_ticks() as u64) as usize; - match backend.run_batch(self, ticks) { + let host_current = !backend.host_stale(); + let (rng, reward_remaining) = (self.rng.state(), self.reward_remaining); + match backend.run_batch(self, ticks, spiked.as_deref_mut()) { Ok(spikes) => total += spikes as u64, - Err(error) => panic!("CUDA LIF batch failed: {error}"), + Err(failure) => { + drop(backend); + if host_current && !failure.replayed { + self.rng.set_state(rng); + self.reward_remaining = reward_remaining; + self.backend_fault = Some(format!( + "CUDA batch failed ({}); the backend is detached and the network \ + continues on the CPU from the current host state", + failure.error + )); + for _ in 0..left { + total += self.step_one_into(spiked.as_deref_mut()) as u64; + } + return Ok(total); + } + let message = format!( + "CUDA batch failed ({}); the backend is detached, and the device held the \ + only current membrane since the last host sync, so this network must be \ + restored from a checkpoint", + failure.error + ); + self.backend_fault = Some(message.clone()); + return Err(Error::new(message)); + } } left -= ticks as u64; } self.cuda = Some(backend); - total + Ok(total) } /// Steps 5, 6 (the spike stamp and role tally only), 7 and 8 of `step_one`, against a spike diff --git a/services/flysim/crates/flybrain-core/tests/tick_spikes.rs b/services/flysim/crates/flybrain-core/tests/tick_spikes.rs index 83c01d6..503043f 100644 --- a/services/flysim/crates/flybrain-core/tests/tick_spikes.rs +++ b/services/flysim/crates/flybrain-core/tests/tick_spikes.rs @@ -1,6 +1,6 @@ //! `LifNetwork::tick_spikes` (PERF-01): after a one-tick `step`, the list is exactly the neurons //! that tick stamped in `last_spike_ms`, so the union of the lists over a window is the window -//! bitset a scan of `last_spike_ms` gives. +//! bitset a scan of `last_spike_ms` gives. GPU-02: `step_frame` gathers the same union in one call. mod common; @@ -52,3 +52,107 @@ fn a_ticks_list_is_the_neurons_it_stamped_and_windows_agree_with_the_scan() { } assert!(spiking_ticks > 0, "the fixture must spike for the test to mean anything"); } + +/// GPU-02: `step_frame` is the session's old per-frame loop -- one-tick `step` calls with each +/// tick's list OR-ed into the bitset -- bit for bit, in the state and in the bitset, at one and +/// at several sweep threads. +#[test] +fn a_frame_step_is_the_one_tick_loop_bit_for_bit() { + use flybrain_core::lif::SweepPlan; + let config = LifConfig { noise_amount: 40.0, ..LifConfig::default() }; + for threads in [1, 3] { + let build = || { + let mut network = LifNetwork::new( + Arc::new(visual_toy_dataset()), + config.clone(), + PlasticityConfig::default(), + ) + .expect("a network"); + network.configure_sweep(SweepPlan::with_threads(threads).expect("a plan")); + network + }; + let (mut looped, mut framed) = (build(), build()); + let neurons = looped.last_spike_ms.len(); + let mut spiking_frames = 0; + for frame in 0..120u64 { + if frame % 25 == 0 { + looped.stimulate(30.0); + framed.stimulate(30.0); + } + if frame % 10 == 9 { + let ms = looped.ms; + looped.plasticity.reinforce(0.5, ms); + framed.plasticity.reinforce(0.5, ms); + } + let ticks = 16 + frame % 2; + let mut want = vec![0u8; neurons.div_ceil(8)]; + let mut want_total = 0u64; + for _ in 0..ticks { + let count = looped.step(1) as usize; + want_total += count as u64; + for &n in looped.tick_spikes(count).expect("the CPU kernel keeps its list") { + want[n as usize >> 3] |= 1 << (n & 7); + } + } + let mut got = vec![0u8; neurons.div_ceil(8)]; + let total = framed.step_frame(ticks, &mut got).expect("the CPU cannot fail"); + assert_eq!(total, want_total, "frame {frame} at {threads} threads"); + assert_eq!(got, want, "frame {frame} at {threads} threads"); + assert_eq!(framed.export_state(), looped.export_state()); + spiking_frames += usize::from(total > 0); + } + assert!(spiking_frames > 0, "the fixture must spike for the test to mean anything"); + assert!(framed.host_state_current()); + assert!(framed.take_backend_fault().is_none()); + } +} + +#[test] +fn a_frame_step_refuses_a_bitset_too_small_for_the_network() { + let mut network = LifNetwork::new( + Arc::new(visual_toy_dataset()), + LifConfig::default(), + PlasticityConfig::default(), + ) + .expect("a network"); + let neurons = network.last_spike_ms.len(); + let mut short = vec![0u8; neurons.div_ceil(8) - 1]; + assert!(network.step_frame(17, &mut short).is_err()); + assert_eq!(network.ms, 0.0, "a refused frame steps nothing"); +} + +/// The deployment switch: only `FLY_LIF_CUDA=1` asks for the GPU, as before GPU-02, and a device +/// that is not an ordinal is refused rather than read as 0. +#[test] +fn the_backend_switch_reads_like_the_old_env_hook() { + use flybrain_core::lif::LifBackend; + assert_eq!(LifBackend::from_values(None, None), Ok(LifBackend::Cpu)); + assert_eq!(LifBackend::from_values(Some("0"), Some("3")), Ok(LifBackend::Cpu)); + assert_eq!(LifBackend::from_values(Some("yes"), None), Ok(LifBackend::Cpu)); + assert_eq!(LifBackend::from_values(Some("1"), None), Ok(LifBackend::Cuda { device: 0 })); + assert_eq!( + LifBackend::from_values(Some("1"), Some("1")), + Ok(LifBackend::Cuda { device: 1 }) + ); + assert!(LifBackend::from_values(Some("1"), Some("GPU-abc")).is_err()); + assert_eq!(LifBackend::Cuda { device: 1 }.label(), "cuda:1"); + assert_eq!(LifBackend::Cpu.label(), "cpu"); +} + +/// Without the feature, asking for the GPU is an error, never a CPU run under a GPU label; the CPU +/// backend is accepted and changes nothing. +#[cfg(not(feature = "cuda"))] +#[test] +fn a_cpu_build_refuses_the_gpu_backend() { + use flybrain_core::lif::LifBackend; + let mut network = LifNetwork::new( + Arc::new(visual_toy_dataset()), + LifConfig::default(), + PlasticityConfig::default(), + ) + .expect("a network"); + assert!(network.set_backend(LifBackend::Cuda { device: 0 }).is_err()); + assert!(network.set_backend(LifBackend::Cpu).is_ok()); + assert_eq!(network.backend(), LifBackend::Cpu); + assert!(!LifBackend::cuda_compiled()); +}