From 7d817d8cee75dbdb79aa45ac06839ab6ac616451 Mon Sep 17 00:00:00 2001 From: acamilo Date: Fri, 2 Oct 2026 07:49:17 +0000 Subject: [PATCH 1/2] GPU-02: the session steps a frame per call, the CUDA backend keeps its state on the device LifNetwork::step_frame runs a game frame's ticks in one call and ORs every tick's spikes into the transition's bitset. On the CPU it is exactly the one-tick loop the session ran; on the GPU it is one batch, with membrane and refractory left on the device (device-owned state): per frame only the noise draws, visual drive and plastic gains go up and the spike lists come down, instead of 1.4 MB per tick (about 24 MB per frame) with the old step(1) loop and per-batch host sync. - LifBackend (cpu / cuda:) from FLY_LIF_CUDA / FLY_LIF_CUDA_DEVICE, set_backend, configure_sweep (set_sweep_plan without the test hook), sync_host, host_state_current, try_step, take_backend_fault. - export_state downloads the device arrays itself while the host copy is stale, so no capture can read old values; the session syncs before State.Capture. - A CUDA failure detaches the backend: if the host state was current the frame continues bit-exactly on the CPU, otherwise the agent fails and a restore in that worker runs on the CPU. Warm-up no longer panics. - The legacy agent worker picks its backend explicitly and refuses a GPU it cannot have (no feature, no device) at Agent.Initialize instead of running the CPU under a GPU label. The FLY_LIF_CUDA hook in set_sweep_plan stays for the golden suite and the legacy loop. - cuda passthrough features on fly-session and fly-legacy-session, so FLY_CARGO_FEATURES=cuda reaches flysim-session, fly-shadow, fly-session. - Tests: step_frame vs the one-tick loop (state and bitset, 1 and 3 threads), the backend switch; cuda_exact frame mode; a cuda-feature session test (FAFB, rollback, restore, checkpoints) against the CPU reference. --- infra/docs/runbook.md | 13 +- .../crates/fly-legacy-session/Cargo.toml | 5 + services/flysim/crates/fly-session/Cargo.toml | 5 + .../flysim/crates/fly-session/src/launcher.rs | 3 + .../crates/fly-session/src/legacy_agent.rs | 85 ++++- .../crates/fly-session/tests/cuda_session.rs | 169 +++++++++ .../flybrain-core/examples/cuda_exact.rs | 342 +++++++++++++----- .../flysim/crates/flybrain-core/src/agent.rs | 4 +- .../flysim/crates/flybrain-core/src/lif.rs | 225 +++++++++++- .../crates/flybrain-core/src/lif/cuda.rs | 243 +++++++++++-- .../crates/flybrain-core/tests/tick_spikes.rs | 106 +++++- 11 files changed, 1051 insertions(+), 149 deletions(-) create mode 100644 services/flysim/crates/fly-session/tests/cuda_session.rs 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()); +} From 7d2650ae5e980c82f114ef8729d4f0bf303e4a54 Mon Sep 17 00:00:00 2001 From: acamilo Date: Fri, 2 Oct 2026 10:14:59 +0000 Subject: [PATCH 2/2] gpu-02 notes: a GPU failure falls back to the CPU for the process lifetime A CUDA failure (a failed batch or read-back, or an attach that fails at a restart) now marks the GPU unusable for the process: the replacement agent worker is created on the CPU and restores the last checkpoint, so a lost device no longer leaves the session unable to restore and a flaky one is never re-attached in a loop. Worker processes share the record through a marker file the launcher owns and empties when it starts. Exposed as the LIF_GPU_FALLBACK log line, fly_brain_backend{backend}, fly_brain_backend_wanted and fly_brain_backend_fallbacks_total, and fly-watchdog check 11 (report only). Adds a committed fault-injection hook for the cuda feature (FLY_LIF_CUDA_FAULT or the inject setters), the recovery harness in legacy_parity, and the cuda_fallback test: init failure, transient (host current) and permanent (in-process and process) faults, each equal to the CPU reference. Corrects the runbook, documents the stale host arrays on LifNetwork, and has cuda_session assert that no fallback hid a CPU pass. --- infra/05-deploy.sh | 4 + infra/bin/fly-watchdog | 39 +++ infra/docs/runbook.md | 41 ++- services/flysim/Cargo.lock | 1 + .../flysim/crates/fly-session/src/launcher.rs | 15 + .../crates/fly-session/src/legacy_agent.rs | 92 +++++-- .../crates/fly-session/src/legacy_parity.rs | 91 ++++++- .../crates/fly-session/tests/cuda_fallback.rs | 256 ++++++++++++++++++ .../crates/fly-session/tests/cuda_session.rs | 11 +- .../flysim/crates/flybrain-core/Cargo.toml | 1 + .../flysim/crates/flybrain-core/src/lif.rs | 8 + .../crates/flybrain-core/src/lif/cuda.rs | 86 ++++++ .../crates/flybrain-core/src/lif/health.rs | 145 ++++++++++ .../crates/flybrain-core/tests/gpu_health.rs | 57 ++++ 14 files changed, 811 insertions(+), 36 deletions(-) create mode 100644 services/flysim/crates/fly-session/tests/cuda_fallback.rs create mode 100644 services/flysim/crates/flybrain-core/src/lif/health.rs create mode 100644 services/flysim/crates/flybrain-core/tests/gpu_health.rs diff --git a/infra/05-deploy.sh b/infra/05-deploy.sh index 039b8d0..7989f83 100644 --- a/infra/05-deploy.sh +++ b/infra/05-deploy.sh @@ -589,6 +589,10 @@ trap 'rm -f "$tmp_fly_env" "$tmp_flypush_env"' EXIT # so FLY_ENCODER-style flipping between backends across restarts keeps the # checkpoint: the compatibility string this script gates on does not move. echo "FLY_LIF_CUDA=${FLY_LIF_CUDA:-0}" + # Where the session worker writes fly_brain_backend (which hardware runs the + # LIF tick, and the GPU fallback count): the same textfile directory as + # fly_encoder.prom, read by fly-watchdog check 11 (runbook, "FLY_LIF_CUDA"). + echo "FLY_BRAIN_BACKEND_PROM=${TEXTFILE_DIR:-/var/lib/node_exporter/textfile}/fly_brain_backend.prom" # On-screen chat (docs/control-api.md [chat]). FLY_CHAT_ENABLED=0 is the # kill switch: POST /chat answers 403 and the feed header omits `chat`, so # the CHAT panel blanks without touching flybridge or the page. flysim reads diff --git a/infra/bin/fly-watchdog b/infra/bin/fly-watchdog index 2166b49..46cb64d 100755 --- a/infra/bin/fly-watchdog +++ b/infra/bin/fly-watchdog @@ -48,6 +48,8 @@ log_info() { # encoder actually opened (docs/design/gpu.md section 5). : "${FLY_ENCODER_METRIC:=${TEXTFILE_DIR}/fly_encoder.prom}" : "${FLY_ENV_FILE:=/etc/fly/fly.env}" +# Written by the session worker (flybrain_core::lif::health): which hardware runs the LIF tick. +: "${FLY_BRAIN_BACKEND_METRIC:=${TEXTFILE_DIR}/fly_brain_backend.prom}" : "${FLY_PROC_DIR:=/proc}" # --- check 9 (capture freeze) inputs, infra/docs/capture-freeze.md --------- : "${FLY_REC_DIR:=/srv/fly/media/rec}" # flycast's 10-minute mpegts segments @@ -175,6 +177,9 @@ write_textfile_metrics() { echo "# HELP fly_watchdog_encoder_degraded 1 when flycast is running on a different video encoder than /etc/fly/fly.env asked for (i.e. the nvenc -> x264 fallback fired). -1 when the encoder state could not be read at all." echo "# TYPE fly_watchdog_encoder_degraded gauge" echo "fly_watchdog_encoder_degraded $(cat "${WD_RUN_DIR}/encoder_degraded" 2>/dev/null || echo -1)" + echo "# HELP fly_watchdog_backend_degraded 1 when FLY_LIF_CUDA=1 asks for the GPU and the LIF tick runs on the CPU (the GPU fell back). -1 when no session worker has written fly_brain_backend." + echo "# TYPE fly_watchdog_backend_degraded gauge" + echo "fly_watchdog_backend_degraded $(cat "${WD_RUN_DIR}/backend_degraded" 2>/dev/null || echo -1)" # Check 9 (infra/docs/capture-freeze.md). fly_capture_identical_frames # is -1 until the first probe completes, the same "unknown, not # broken" convention fly_watchdog_encoder_degraded uses; a value at or @@ -711,6 +716,39 @@ check_encoder() { "and check: nvidia-smi --query-gpu=memory.used,utilization.encoder --format=csv" } +# ============================================================================ +# Check 11: LIF backend (GPU-02 notes, runbook "FLY_LIF_CUDA"). Reads the +# fly_brain_backend series the session worker writes: when FLY_LIF_CUDA=1 asks +# for the card and the CPU is what runs, the GPU fell back (operator decision +# 2026-10-02: automatic, the stream keeps going, logged here, no paging). +# +# Like check 8 this takes NO remediation. A restart cannot repair a dead card +# and costs the run its in-memory state; the fallback is a CPU run from the +# last checkpoint, which is bit-exact. It logs, exports a gauge and leaves the +# card to a human. fly_brain_backend is not duplicated into this file's own +# .prom, for the reason check 8 gives. +# ============================================================================ +check_backend() { + local wanted live fallbacks + if [ ! -f "$FLY_BRAIN_BACKEND_METRIC" ]; then + # No session worker has written it (the legacy loop, a CPU deploy, or not started yet). + echo -1 > "${WD_RUN_DIR}/backend_degraded" + return 0 + fi + wanted="$(awk '/^fly_brain_backend_wanted / { print $2; exit }' "$FLY_BRAIN_BACKEND_METRIC" 2>/dev/null || true)" + live="$(awk '/^fly_brain_backend\{/ && $NF == 1 { + if (match($0, /backend="[^"]+"/)) { print substr($0, RSTART + 9, RLENGTH - 10); exit } }' \ + "$FLY_BRAIN_BACKEND_METRIC" 2>/dev/null || true)" + fallbacks="$(awk '/^fly_brain_backend_fallbacks_total / { print $2; exit }' "$FLY_BRAIN_BACKEND_METRIC" 2>/dev/null || true)" + if [ "$wanted" = 1 ] && [ "$live" = cpu ]; then + echo 1 > "${WD_RUN_DIR}/backend_degraded" + log_err "GPU backend degraded: FLY_LIF_CUDA=1 asks for the card but the LIF tick runs on the CPU (${fallbacks:-?} fallback(s) since flysim started)." \ + "Automatic and bit-exact, from the last checkpoint; not restarting. Reason: journalctl -u flysim | grep LIF_GPU_FALLBACK. See docs/runbook.md 'FLY_LIF_CUDA'" + else + echo 0 > "${WD_RUN_DIR}/backend_degraded" + fi +} + # ============================================================================ # Check 9: capture freeze (infra/docs/capture-freeze.md). # @@ -1333,6 +1371,7 @@ main() { check_flystage check_flycast check_encoder + check_backend check_mediamtx check_flypush check_disk diff --git a/infra/docs/runbook.md b/infra/docs/runbook.md index 4d6aa75..9d4a0a0 100644 --- a/infra/docs/runbook.md +++ b/infra/docs/runbook.md @@ -1190,15 +1190,40 @@ pct exec -- journalctl -u flysim -b --no-pager | grep -i 'cuda\|lif backe ``` 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 +(`FLY_LIF_CUDA`, `FLY_LIF_CUDA_DEVICE`, a device ordinal) in its agent worker. A build without +the feature that is asked for the GPU is a misconfiguration and fails `Agent.Initialize` with +`BACKEND_FAILURE`; a build with it logs `LIF backend cuda: attached, device-owned state` when +the worker 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. +drive, plastic gains, about 110 KB) go up and the spike lists come down. Build all binaries with the +feature: `FLY_CARGO_FEATURES=cuda` now reaches `flysim-session`, `fly-shadow` and `fly-session` too. + +**A GPU failure falls back to the CPU and the stream keeps going** (operator, 2026-10-02; no +paging). The first failure makes the GPU unusable for that process's lifetime, so nothing re-attaches +a dead card in a loop: + +- A CUDA error on a frame whose host state was current (the first frame after a start or a + restore) finishes that frame on the CPU in place, bit-exact, and the agent goes on there. +- Any other CUDA error mid-run fails the agent (the device held the only current copy of the + membrane). Recovery restores the last checkpoint into a **replacement worker, which is created on + the CPU**, and replays from there. Checkpoints are backend-neutral and the GPU tick is bit-exact, + so the CPU run equals one that never had a GPU. +- A CUDA init that fails (a lost device, or a driver that is gone after a restart) is a warning and + a CPU worker, not a failed `Agent.Initialize`. +- The fallback lasts until `flysim.service` restarts, which tries the card again; if it is still + dead, that attach is another fallback. Restart is therefore also the way back onto a repaired GPU. + +Where it shows: the journal line `LIF_GPU_FALLBACK: the GPU is unusable ...` (once per failure, +with the reason); `fly_brain_backend{backend="cpu|cuda"}` (1 on the backend that runs), +`fly_brain_backend_wanted` and `fly_brain_backend_fallbacks_total`, written by the worker to the +textfile `FLY_BRAIN_BACKEND_PROM` points at (the deploy sets it beside `fly_encoder.prom`); and +`fly-watchdog` check 11, which logs `GPU backend degraded:` and raises +`fly_watchdog_backend_degraded` when `FLY_LIF_CUDA=1` asks for the card and the CPU is running. It +takes no remediation and pages no one (a restart cannot fix a dead card and would cost the +run a rollback); look at `journalctl -u flysim | grep LIF_GPU_FALLBACK`, `nvidia-smi` on the host, +and the driver-lockstep section below. The CPU run is slower per thread count, so `RAYON_THREADS=2` +(see below) is below real time on the CPU: after a fallback, set it back to 3 with `FLY_LIF_CUDA=0` +and redeploy if the card is not coming back soon. 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 diff --git a/services/flysim/Cargo.lock b/services/flysim/Cargo.lock index a04a63d..5a27e8a 100644 --- a/services/flysim/Cargo.lock +++ b/services/flysim/Cargo.lock @@ -535,6 +535,7 @@ dependencies = [ "serde", "serde_json", "sha2", + "tempfile", ] [[package]] diff --git a/services/flysim/crates/fly-session/src/launcher.rs b/services/flysim/crates/fly-session/src/launcher.rs index e414126..89f4e26 100644 --- a/services/flysim/crates/fly-session/src/launcher.rs +++ b/services/flysim/crates/fly-session/src/launcher.rs @@ -417,6 +417,10 @@ struct Endpoints { own: Via, store_root: PathBuf, sockets: PathBuf, + /// The GPU fallback record the worker processes share (`flybrain_core::lif::health`): a + /// replacement worker that is a new process must not re-attach a GPU that failed in an + /// earlier one. Emptied when this launcher starts. + gpu_marker: PathBuf, next_socket: AtomicU64, listeners: Mutex>, } @@ -575,6 +579,13 @@ pub fn die_with_parent(command: &mut std::process::Command) { } impl Launcher { + /// GPU failures that moved the LIF tick to the CPU under this launcher: its worker + /// processes' (the marker) and, for workers in this process, this process's. + pub fn gpu_fallbacks(&self) -> u64 { + flybrain_core::lif::health::marker_fallbacks(&self.endpoints.gpu_marker) + .max(flybrain_core::lif::health::fallbacks()) + } + /// Connects the supervisor and prepares the launcher. Nothing is started yet. pub async fn start( router: Router, @@ -588,6 +599,8 @@ impl Launcher { std::fs::create_dir_all(&sockets).map_err(|e| { flybus::BusError::new(flybus::ErrorCode::StoreFailure, format!("sockets: {e}")) })?; + let gpu_marker = sockets.join("lif-gpu-fallbacks"); + flybrain_core::lif::health::reset_marker(&gpu_marker); let endpoints = Endpoints { router, via: mode.transport(via), @@ -597,6 +610,7 @@ impl Launcher { }, store_root: store_root.into(), sockets, + gpu_marker, next_socket: AtomicU64::new(0), listeners: Mutex::new(Vec::new()), }; @@ -1036,6 +1050,7 @@ impl Launcher { .arg(flybrain_core::pool::format_cpu_list(&cpus.sweep)); } } + command.env(flybrain_core::lif::health::MARKER_ENV, &self.endpoints.gpu_marker); command.stdin(std::process::Stdio::null()); die_with_parent(&mut command); let child = command.spawn().map_err(|e| { diff --git a/services/flysim/crates/fly-session/src/legacy_agent.rs b/services/flysim/crates/fly-session/src/legacy_agent.rs index 79174b0..f7d4a02 100644 --- a/services/flysim/crates/fly-session/src/legacy_agent.rs +++ b/services/flysim/crates/fly-session/src/legacy_agent.rs @@ -42,6 +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::health as lif_health; use flybrain_core::lif::{LifBackend, LifConfig, SweepPlan, kernel_version}; use serde_json::{Value, json}; @@ -521,9 +522,6 @@ pub struct LegacyAgentWorker { 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. @@ -722,7 +720,6 @@ impl LegacyAgentWorker { prepared: None, transition_start_ms: 0.0, tick_spikes: None, - backend_fault: None, staged: None, activated: BTreeSet::new(), mutations: 0, @@ -877,6 +874,63 @@ impl LegacyAgentWorker { /// Builds a network and readout over `dataset`, before any state is installed, and checks /// every identity the profile pins: kernel and plasticity versions, frame size, rate roles. + /// The backend this agent runs on, attached. A GPU that already failed in this process is + /// not tried again, and one that cannot be attached now (a lost device, a failed CUDA init + /// after a restart) is a fallback to the CPU with a warning, never a failed worker + /// (operator decision, 2026-10-02): the stream keeps going from the same checkpoint, which + /// is backend-neutral. A build without the `cuda` feature that is asked for the GPU is a + /// misconfiguration and still fails `Agent.Initialize`. + /// + /// Each attach builds a new backend (about 57 MiB of device memory) while the agent it + /// replaces may still be alive; harmless on a 24 GB card, to be budgeted when GPU-03 batches + /// flies onto an 8 GB one. + fn attach_backend( + &self, + agent: &mut NeuralAgent, + wanted: LifBackend, + ) -> Result { + let LifBackend::Cuda { .. } = wanted else { + agent.network.set_backend(LifBackend::Cpu).map_err(|e| { + DomainError::before(ErrorCode::BackendFailure, format!("LIF backend cpu: {e}")) + })?; + return Ok(LifBackend::Cpu); + }; + if LifBackend::cuda_compiled() { + if lif_health::gpu_unusable() { + eprintln!( + "legacy agent {}: LIF backend cpu (the GPU failed earlier in this process: {})", + self.config.agent_id, + lif_health::last_reason().unwrap_or_default() + ); + return Ok(LifBackend::Cpu); + } + return match agent.network.set_backend(wanted) { + Ok(()) => Ok(wanted), + Err(e) => { + lif_health::record_fallback(&format!( + "agent {}: attaching {} failed: {e}", + self.config.agent_id, + wanted.label() + )); + Ok(LifBackend::Cpu) + } + }; + } + agent.network.set_backend(wanted).map_err(|e| { + DomainError::before( + ErrorCode::BackendFailure, + format!("LIF backend {}: {e}", wanted.label()), + ) + })?; + Ok(wanted) + } + + /// A GPU failure in this worker: the GPU is out for the process, and the metric says so. + fn gpu_failed(config: &LegacyAgentConfig, reason: &str) { + lif_health::record_fallback(&format!("agent {}: {reason}", config.agent_id)); + lif_health::write_textfile(LifBackend::Cpu, config.lif_backend.clone().unwrap_or_default()); + } + fn build_agent( &self, dataset: Arc, @@ -944,19 +998,10 @@ impl LegacyAgentWorker { // 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| { + let wanted = 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()), - ) - })?; + let backend = self.attach_backend(&mut agent, wanted)?; if backend != LifBackend::Cpu { eprintln!( "legacy agent {}: LIF backend {} attached, device-owned state", @@ -964,6 +1009,7 @@ impl LegacyAgentWorker { backend.label() ); } + lif_health::write_textfile(backend, wanted); let fingerprint = self.profile.dataset_fingerprint.clone(); let graph = AgentGraph { dataset_digest: dataset_digest(&fingerprint), @@ -1204,19 +1250,19 @@ impl LegacyAgentWorker { // would scan out of `last_spike_ms`. let mut bits = vec![0u8; agent.network.last_spike_ms.len().div_ceil(8)]; 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()); + // The device state was the only current copy, so this worker cannot go on: it fails + // and the replacement restores the last checkpoint on the CPU (the GPU is out for + // the process). + Self::gpu_failed(&self.config, &format!("{e}; the agent fails, a replacement restores the last checkpoint on the CPU")); return Err(applied( ErrorCode::BackendFailure, format!("the brain ticks failed: {e}"), )); } if let Some(fault) = agent.network.take_backend_fault() { - eprintln!("legacy agent {}: {fault}", self.config.agent_id); - self.backend_fault = Some(fault); + // The host state was current: the frame finished on the CPU in this call, and this + // worker continues there. + Self::gpu_failed(&self.config, &fault); } self.tick_spikes = Some(bits); drop(ticks_span); @@ -1591,7 +1637,7 @@ impl LegacyAgentWorker { 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()); + Self::gpu_failed(&self.config, &format!("device state read-back: {e}")); return Err(applied( ErrorCode::BackendFailure, format!("the device state cannot be read back: {e}"), diff --git a/services/flysim/crates/fly-session/src/legacy_parity.rs b/services/flysim/crates/fly-session/src/legacy_parity.rs index 24d5f41..09ec40c 100644 --- a/services/flysim/crates/fly-session/src/legacy_parity.rs +++ b/services/flysim/crates/fly-session/src/legacy_parity.rs @@ -991,6 +991,11 @@ impl LegacyRig { self.launch(agent_id).await } + /// GPU failures so far that moved a worker's LIF tick to the CPU ([`Launcher::gpu_fallbacks`]). + pub fn gpu_fallbacks(&self) -> u64 { + self.launcher.gpu_fallbacks() + } + pub async fn stop(mut self) { self.launcher.reap_all(&id("done")).await; } @@ -1577,12 +1582,53 @@ pub async fn run_on_worker_from_then_capture( Ok((records, captured.expect("a capture was asked for"))) } +/// [`run_on_worker`] with the coordinator's recovery for a failed frame (GPU-02): the agent is +/// Failed, so the last checkpoint (the script's `checkpoints`) is restored into a replacement +/// worker, and the script goes on from the step after it. Returns the records and, for each +/// recovery, the index of the step whose checkpoint was restored. The restore resets the +/// readout's transients by design, so the matching CPU reference is the script with a +/// `ScriptStep::Restore` after that step ([`script_with_restore_after`]). +pub async fn run_on_worker_recovering( + rig: &mut LegacyRig, + agent_id: &Id, + script: &LegacyScript, +) -> Result<(Vec, Vec), String> { + let mut recovered = Vec::new(); + let (records, _) = run_script_with(rig, agent_id, script, None, false, Some(&mut recovered)).await?; + Ok((records, recovered)) +} + +/// `script` with a restore into a fresh agent right after step `at` (an index into `steps`), and +/// its checkpoints moved onto the steps' new positions: the CPU reference for a run that +/// recovered from the checkpoint at `at`. +pub fn script_with_restore_after(script: &LegacyScript, at: usize) -> LegacyScript { + let mut alt = script.clone(); + alt.steps.insert(at + 1, ScriptStep::Restore); + alt.checkpoints = script + .checkpoints + .iter() + .map(|&i| if i > at { i + 1 } else { i }) + .collect(); + alt +} + async fn run_script( rig: &mut LegacyRig, agent_id: &Id, script: &LegacyScript, start: Option<(&flybrain_core::agent::AgentState, u64)>, capture_at_end: bool, +) -> Result<(Vec, Option>), String> { + run_script_with(rig, agent_id, script, start, capture_at_end, None).await +} + +async fn run_script_with( + rig: &mut LegacyRig, + agent_id: &Id, + script: &LegacyScript, + start: Option<(&flybrain_core::agent::AgentState, u64)>, + capture_at_end: bool, + mut recovered: Option<&mut Vec>, ) -> Result<(Vec, Option>), String> { let mut driver = rig.driver(agent_id, script); let first = match start { @@ -1594,7 +1640,12 @@ async fn run_script( } }; let mut records = vec![first]; - for (index, step) in script.steps.iter().enumerate() { + // The last checkpoint, for a recovery: (step, records so far, the capture, and the driver + // state a restore returns to). + let mut last_checkpoint: Option<(usize, usize, Captured, u64, TypedValue, RationalNs)> = None; + let mut index = 0usize; + while index < script.steps.len() { + let step = &script.steps[index]; let mut record = match step { ScriptStep::Frame { sugar, @@ -1602,9 +1653,31 @@ async fn run_script( rewards, next_context, } => { - driver + match driver .frame(index + 1, sugar, *frame, rewards, next_context) - .await? + .await + { + Ok(record) => record, + Err(e) if recovered.is_some() && last_checkpoint.is_some() => { + let (at, kept, captured, boundary, context, remainder) = + last_checkpoint.take().expect("checked"); + eprintln!( + "recovery: step {} failed ({e}); restoring the checkpoint after step {at} into a replacement", + index + 1 + ); + driver.boundary = boundary; + driver.context = context.clone(); + driver.remainder = remainder; + let target = rig.replace(agent_id).await?; + driver.restore_into(target, &captured).await?; + records.truncate(kept); + recovered.as_mut().expect("checked").push(at); + last_checkpoint = Some((at, kept, captured, boundary, context, remainder)); + index = at + 1; + continue; + } + Err(e) => return Err(e), + } } ScriptStep::Rollback { frame, context } => { driver.rollback(index + 1, *frame, context).await? @@ -1632,8 +1705,20 @@ async fn run_script( if script.checkpoints.contains(&index) { let captured = driver.capture().await?; record.state = Some(payload_state_digest(&captured.bytes)?); + records.push(record); + last_checkpoint = Some(( + index, + records.len(), + captured, + driver.boundary, + driver.context.clone(), + driver.remainder, + )); + index += 1; + continue; } records.push(record); + index += 1; } let captured = if capture_at_end { Some(driver.capture().await?.bytes) diff --git a/services/flysim/crates/fly-session/tests/cuda_fallback.rs b/services/flysim/crates/fly-session/tests/cuda_fallback.rs new file mode 100644 index 0000000..30e5339 --- /dev/null +++ b/services/flysim/crates/fly-session/tests/cuda_fallback.rs @@ -0,0 +1,256 @@ +//! GPU-02 notes round (N2, operator decision 2026-10-02): a GPU failure on the live brain falls +//! back to the CPU and the session keeps going from the last checkpoint, with no loop re-attaching +//! a dead device. +//! +//! The fault-injection hook (`flybrain_core::lif::cuda::inject`, or `FLY_LIF_CUDA_FAULT` for a +//! worker process) raises a CUDA error where a real one would surface. Against the CPU reference +//! on the real connectome: +//! +//! - **Permanent, mid-run** (the device held the only current state): the agent fails, a +//! replacement worker restores the last checkpoint on the CPU and the records are those of the CPU +//! reference with a restore at that checkpoint -- in-process, and as a process, where the +//! replacement is a new process that must not re-attach the GPU (no second failure). +//! - **Init failure** (a lost device at a restart): `Agent.Initialize` succeeds on the CPU, with +//! a warning and a counted fallback, and a restore into a replacement stays on the CPU. +//! - **Transient** (the host state was current: the first batch): the frame finishes on the CPU in +//! the call, bit-exact, and no recovery is needed; the fallback is counted and the GPU is not +//! re-attached by a later restore. +//! +//! Needs `--features cuda` and `data/fafb-v783`. The cases that run a real device also need +//! `FLY_GPU02_CUDA=1` and a visible card; the init-failure case needs neither. +#![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, ParityRecord, 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; +use flybrain_core::lif::cuda::inject; +use flybrain_core::lif::health; + +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() +} + +/// Frames with sugar and reward pulses, a checkpoint every 25 steps, an optional restore. +fn script(frames: usize, restore_at: Option) -> 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 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 restore_at == Some(k) { + steps.push(ScriptStep::Restore); + } + } + let last = steps.len() - 1; + let checkpoints = (0..steps.len()) + .filter(|i| i % 25 == 24) + .chain([last]) + .collect(); + LegacyScript { + name: "gpu02-fallback".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, + } +} + +fn agent(dir: &std::path::Path, script: &LegacyScript) -> RigAgent { + RigAgent { + agent_id: id("fly-a"), + port_id: id("p1"), + dataset_dir: dir.to_path_buf(), + profile: LegacyProfileKind::Production, + macro_channels: script.macro_channels.clone(), + worker_threads: 1, + } +} + +fn reset() { + inject::clear(); + health::reset_for_tests(); +} + +struct Outcome { + records: Vec, + recovered: Vec, + fallbacks: u64, +} + +async fn run(dir: &std::path::Path, script: &LegacyScript, mode: ExecutionMode) -> Outcome { + let root = tempfile::tempdir().expect("tmp"); + let mut rig = LegacyRig::start(root.path(), mode, &[agent(dir, script)]) + .await + .expect("the rig"); + let (records, recovered) = + legacy_parity::run_on_worker_recovering(&mut rig, &id("fly-a"), script) + .await + .unwrap_or_else(|e| panic!("{}: {e}", mode.label())); + let fallbacks = rig.gpu_fallbacks(); + rig.stop().await; + Outcome { + records, + recovered, + fallbacks, + } +} + +fn reference(dir: &std::path::Path, script: &LegacyScript) -> Vec { + let dataset = Arc::new(load_brain_dataset_from_dir(dir).expect("the dataset loads")); + DirectSource { dataset } + .records(script) + .expect("the CPU reference runs") +} + +/// The records of the CPU reference with a restore after step `at`, minus that restore's own +/// record (the recovery has none), against what the recovered run recorded. +fn assert_recovered_equals_reference( + dir: &std::path::Path, + script: &LegacyScript, + at: usize, + got: &[ParityRecord], + case: &str, +) { + let alt = legacy_parity::script_with_restore_after(script, at); + let mut want = reference(dir, &alt); + want.remove(at + 2); // records[0] is the first record, step i is records[i + 1] + assert_eq!(want.len(), got.len(), "{case}: record count"); + for (i, (w, g)) in want.iter().zip(got).enumerate() { + let (mut w, mut g) = (w.clone(), g.clone()); + w.index = 0; + g.index = 0; + assert_eq!(w, g, "{case}: record {i} differs from the CPU reference"); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_gpu_failure_falls_back_to_the_cpu_and_the_session_continues() { + let Some(dir) = fafb_dir() else { + eprintln!("skipping: data/fafb-v783 is not present in this checkout"); + return; + }; + let device = std::env::var_os("FLY_GPU02_CUDA").is_some(); + let frames = 120; + // SAFETY: the only test in this binary; no worker (thread or child) exists yet. + unsafe { std::env::set_var("FLY_LIF_CUDA", "1") }; + let plain = script(frames, None); + + // Init failure: a restart whose CUDA init fails. No device needed. + reset(); + inject::fail_attach(true); + let with_restore = script(frames, Some(60)); + let got = run(&dir, &with_restore, ExecutionMode::InProcess).await; + assert!(got.recovered.is_empty(), "nothing failed mid-run"); + assert_eq!(got.fallbacks, 1, "one failed attach; the restore did not try the GPU again"); + legacy_parity::compare(&reference(&dir, &with_restore), &got.records) + .unwrap_or_else(|e| panic!("init failure: {e}")); + assert!(health::gpu_unusable()); + eprintln!("init failure: continued on the CPU, {} records identical", got.records.len()); + + if !device { + eprintln!("skipping the device cases: FLY_GPU02_CUDA is not set"); + reset(); + return; + } + + // Control: the GPU, no fault, no fallback. + reset(); + let started = inject::batches(); + let got = run(&dir, &plain, ExecutionMode::InProcess).await; + // A game frame is one batch; the warm-up before the first frame is many. The faults below + // go off `frames - 50` batches from the run's end: mid-run, never in the warm-up. + let run_batches = inject::batches() - started; + assert!(run_batches > frames as u64); + assert_eq!(got.fallbacks, 0, "the GPU attached"); + legacy_parity::compare(&reference(&dir, &plain), &got.records) + .unwrap_or_else(|e| panic!("control: {e}")); + + // Transient: the first batch (the warm-up) fails with the host state current. The frame + // finishes on the CPU in the call: no recovery, bit-exact, and the GPU stays out. + reset(); + inject::fail_batch_after(0); + let got = run(&dir, &with_restore, ExecutionMode::InProcess).await; + assert!(got.recovered.is_empty(), "the call finished on the CPU"); + assert_eq!(got.fallbacks, 1, "counted once; the restore did not re-attach the GPU"); + legacy_parity::compare(&reference(&dir, &with_restore), &got.records) + .unwrap_or_else(|e| panic!("transient: {e}")); + eprintln!("transient: finished on the CPU in place, {} records identical", got.records.len()); + + // Permanent, mid-run, in-process: the device held the only current state. + reset(); + inject::fail_batch_after(run_batches - 50); + let got = run(&dir, &plain, ExecutionMode::InProcess).await; + assert_eq!(got.recovered.len(), 1, "one recovery, no loop"); + assert_eq!(got.fallbacks, 1); + assert_recovered_equals_reference(&dir, &plain, got.recovered[0], &got.records, "permanent in-process"); + eprintln!( + "permanent in-process: recovered from the checkpoint after step {}, {} records identical", + got.recovered[0], + got.records.len() + ); + + // Permanent, mid-run, as a process: the replacement is a new process, which must read the + // failure from the launcher's marker. With the fault armed in every process at the same + // batch, a replacement that re-attached the GPU would fail again about 50 frames after the + // restore (its warm-up is the same length, then 50 frames to the same batch). + reset(); + unsafe { std::env::set_var("FLY_LIF_CUDA_FAULT", format!("batch={}", run_batches - 50)) }; + let got = run(&dir, &plain, ExecutionMode::Process).await; + unsafe { std::env::remove_var("FLY_LIF_CUDA_FAULT") }; + assert_eq!(got.recovered.len(), 1, "the replacement process stayed on the CPU"); + assert_eq!(got.fallbacks, 1); + assert_recovered_equals_reference(&dir, &plain, got.recovered[0], &got.records, "permanent process"); + eprintln!( + "permanent process: recovered from the checkpoint after step {}, {} records identical", + got.recovered[0], + got.records.len() + ); + reset(); +} diff --git a/services/flysim/crates/fly-session/tests/cuda_session.rs b/services/flysim/crates/fly-session/tests/cuda_session.rs index 445180f..a8188f3 100644 --- a/services/flysim/crates/fly-session/tests/cuda_session.rs +++ b/services/flysim/crates/fly-session/tests/cuda_session.rs @@ -11,8 +11,9 @@ //! //! 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. +//! GPU up from `FLY_LIF_CUDA=1`, set here before any worker starts. A host that cannot attach the +//! backend now falls back to the CPU (GPU-02 notes, `cuda_fallback.rs`), so this test asserts that +//! no fallback was recorded: a pass on the CPU would mean nothing. #![cfg(feature = "cuda")] use std::sync::Arc; @@ -156,6 +157,12 @@ async fn the_gpu_worker_matches_the_cpu_reference_on_fafb() { let got = legacy_parity::run_on_worker(&mut rig, &id("fly-a"), &script) .await .unwrap_or_else(|e| panic!("{} x{threads}: {e}", mode.label())); + assert_eq!( + rig.gpu_fallbacks(), + 0, + "{} x{threads}: the GPU did not attach, so this ran on the CPU", + mode.label() + ); rig.stop().await; legacy_parity::compare(&want, &got) .unwrap_or_else(|e| panic!("{} x{threads}: {e}", mode.label())); diff --git a/services/flysim/crates/flybrain-core/Cargo.toml b/services/flysim/crates/flybrain-core/Cargo.toml index e8173f7..c28730f 100644 --- a/services/flysim/crates/flybrain-core/Cargo.toml +++ b/services/flysim/crates/flybrain-core/Cargo.toml @@ -29,6 +29,7 @@ libc = "0.2" [dev-dependencies] base64.workspace = true +tempfile = "3" [[example]] name = "bench" diff --git a/services/flysim/crates/flybrain-core/src/lif.rs b/services/flysim/crates/flybrain-core/src/lif.rs index b761d94..53b0d08 100644 --- a/services/flysim/crates/flybrain-core/src/lif.rs +++ b/services/flysim/crates/flybrain-core/src/lif.rs @@ -21,6 +21,9 @@ use crate::version::version_for; #[cfg(feature = "cuda")] pub mod cuda; +/// Whether the GPU may still be used in this process, and the fallback record. +pub mod health; + /// Version of the default configuration; kept verbatim so existing checkpoints stay loadable. pub const NEURAL_KERNEL_VERSION: &str = "lif-1ms-f64-v2"; @@ -333,7 +336,12 @@ pub struct LifNetwork { /// Version string of this configuration; pin it in checkpoints. pub version: String, pub plasticity: RewardModulatedStdp, + /// Membrane potentials. **Stale while a device-owned GPU backend is attached** and + /// `cuda().is_some_and(|b| b.host_stale())`: the device holds the current copy until + /// [`LifNetwork::sync_host`]. Read it only after a `sync_host`, or use + /// [`LifNetwork::export_state`], which reads the device itself. pub membrane: Vec, + /// Refractory counters; stale on the same terms as `membrane`. pub refractory: Vec, pub baseline: Vec, pub last_spike_ms: Vec, diff --git a/services/flysim/crates/flybrain-core/src/lif/cuda.rs b/services/flysim/crates/flybrain-core/src/lif/cuda.rs index 2287578..280b7fb 100644 --- a/services/flysim/crates/flybrain-core/src/lif/cuda.rs +++ b/services/flysim/crates/flybrain-core/src/lif/cuda.rs @@ -64,6 +64,88 @@ use crate::error::{Error, Result}; use super::LifNetwork; +/// Fault injection for the failure path: a CUDA error raised where a real one would surface, so +/// the fallback can be tested and drilled without breaking a card. Off unless armed. Armed by +/// `FLY_LIF_CUDA_FAULT` (read once, by the first backend built) or by the setters; a comma list of +/// `init` (every attach fails, as with a lost device), `batch=N` (the N-th batch of this process, +/// counted from 0, fails after its kernels ran) and `sync=N` (the N-th device download). +pub mod inject { + use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; + use std::sync::OnceLock; + + const NEVER: u64 = u64::MAX; + static INIT: AtomicBool = AtomicBool::new(false); + static BATCH_AT: AtomicU64 = AtomicU64::new(NEVER); + static SYNC_AT: AtomicU64 = AtomicU64::new(NEVER); + static BATCHES: AtomicU64 = AtomicU64::new(0); + static SYNCS: AtomicU64 = AtomicU64::new(0); + static ENV: OnceLock<()> = OnceLock::new(); + + pub(super) fn load_env() { + ENV.get_or_init(|| { + let Ok(spec) = std::env::var("FLY_LIF_CUDA_FAULT") else { + return; + }; + for item in spec.split(',').map(str::trim) { + match item.split_once('=') { + None if item == "init" => INIT.store(true, Ordering::SeqCst), + Some(("batch", n)) => BATCH_AT.store(n.parse().unwrap_or(NEVER), Ordering::SeqCst), + Some(("sync", n)) => SYNC_AT.store(n.parse().unwrap_or(NEVER), Ordering::SeqCst), + _ => eprintln!("FLY_LIF_CUDA_FAULT: ignoring {item:?}"), + } + } + }); + } + + /// Every attach fails from now on (a lost device), or stops failing. + pub fn fail_attach(on: bool) { + INIT.store(on, Ordering::SeqCst); + } + /// The batch that is `after` batches from now fails, once. + pub fn fail_batch_after(after: u64) { + BATCH_AT.store(BATCHES.load(Ordering::SeqCst) + after, Ordering::SeqCst); + } + /// The device download that is `after` downloads from now fails, once. + pub fn fail_sync_after(after: u64) { + SYNC_AT.store(SYNCS.load(Ordering::SeqCst) + after, Ordering::SeqCst); + } + /// Batches this process has launched so far (a warm-up is many; a game frame is one). + pub fn batches() -> u64 { + BATCHES.load(Ordering::SeqCst) + } + /// Disarms everything. + pub fn clear() { + INIT.store(false, Ordering::SeqCst); + BATCH_AT.store(NEVER, Ordering::SeqCst); + SYNC_AT.store(NEVER, Ordering::SeqCst); + } + + pub(super) fn attach() -> super::Result<()> { + load_env(); + if INIT.load(Ordering::SeqCst) { + return Err(super::Error::new( + "CUDA init failed: injected fault (CUDA_ERROR_NO_DEVICE)", + )); + } + Ok(()) + } + fn hit(counter: &AtomicU64, at: &AtomicU64, what: &str) -> super::Result<()> { + let n = counter.fetch_add(1, Ordering::SeqCst); + if n == at.load(Ordering::SeqCst) { + return Err(super::Error::new(format!( + "CUDA {what} failed: injected fault #{n} (CUDA_ERROR_LAUNCH_FAILED)" + ))); + } + Ok(()) + } + pub(super) fn batch() -> super::Result<()> { + hit(&BATCHES, &BATCH_AT, "batch") + } + pub(super) fn sync() -> super::Result<()> { + hit(&SYNCS, &SYNC_AT, "download") + } +} + /// Threads per block, and therefore neurons per block in the sweep and the compaction. Must match /// `LIF_BLOCK` in `cuda/lif.cu`, because the spike bitset words are per-warp ballots. const BLOCK: u32 = 256; @@ -262,6 +344,7 @@ impl CudaLif { } pub fn with_max_ticks(network: &LifNetwork, ordinal: usize, max_ticks: usize) -> Result { + inject::attach()?; let max_ticks = max_ticks.max(1); let neurons = network.data.meta.neurons; if neurons == 0 { @@ -482,6 +565,7 @@ impl CudaLif { /// Copy `membrane` and `refractory` from the device into the network's host arrays. pub fn sync_to_host(&mut self, network: &mut LifNetwork) -> Result<()> { + inject::sync()?; self.stream .memcpy_dtoh(&self.membrane, &mut network.membrane[..]) .map_err(|error| driver_error("membrane download", error))?; @@ -499,6 +583,7 @@ impl CudaLif { /// 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)> { + inject::sync()?; let mut membrane = vec![0.0f32; self.neurons]; let mut refractory = vec![0u8; self.neurons]; self.stream @@ -659,6 +744,7 @@ impl CudaLif { self.stream .synchronize() .map_err(|error| driver_error("synchronize", error))?; + inject::batch()?; self.kernel_ms += f64::from( self.batch_start .elapsed_ms(&self.batch_end) diff --git a/services/flysim/crates/flybrain-core/src/lif/health.rs b/services/flysim/crates/flybrain-core/src/lif/health.rs new file mode 100644 index 0000000..dcdcad7 --- /dev/null +++ b/services/flysim/crates/flybrain-core/src/lif/health.rs @@ -0,0 +1,145 @@ +//! Whether this process may use the GPU for the LIF tick, and the record of why it may not. +//! +//! A GPU failure (a batch, a sync or an attach) is final for the process: [`record_fallback`] +//! marks the GPU unusable and every backend chosen afterwards is the CPU, so a dead or flaky +//! device is never re-attached in a loop. A restart is a new process and tries the device again; +//! if that attach fails it is a fallback too, not a crash. Checkpoints are backend-neutral, so +//! the CPU continues from the same state. +//! +//! The state is per process, and a worker that runs as a child process starts with none. The +//! launcher therefore points its children at a marker file ([`MARKER_ENV`]): each fallback +//! appends a line to it, and the file (not the child's memory) is then the record, shared by the +//! launcher's later workers. The launcher empties the file when it starts, which is what ends +//! the fallback with the process that owns it. +//! +//! [`render_prometheus`] and [`write_textfile`] expose it as `fly_brain_backend{backend=..}` and +//! `fly_brain_backend_fallbacks_total` for the watchdog. + +use std::io::Write as _; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Mutex; + +use super::LifBackend; + +/// The marker file's path, set by the launcher for its worker processes. +pub const MARKER_ENV: &str = "FLY_LIF_GPU_MARKER"; + +/// Where [`write_textfile`] puts the metrics, if set: a node_exporter textfile-collector file. +pub const PROM_ENV: &str = "FLY_BRAIN_BACKEND_PROM"; + +/// The log line's stable prefix: what `fly-watchdog` and `fly-check` grep for. +pub const LOG_PREFIX: &str = "LIF_GPU_FALLBACK"; + +static FALLBACKS: AtomicU64 = AtomicU64::new(0); +static LAST_REASON: Mutex> = Mutex::new(None); + +fn marker() -> Option { + std::env::var_os(MARKER_ENV) + .filter(|path| !path.is_empty()) + .map(PathBuf::from) +} + +fn marker_lines(path: &Path) -> Vec { + std::fs::read_to_string(path) + .map(|text| text.lines().map(str::to_owned).collect()) + .unwrap_or_default() +} + +/// Empties the marker: the launcher calls this when it starts, so a fallback lasts as long as the +/// process that owns the workers and not across a restart. +pub fn reset_marker(path: &Path) { + let _ = std::fs::remove_file(path); +} + +/// Marks the GPU unusable for this process lifetime, counts the fallback and logs it as one +/// `LIF_GPU_FALLBACK` line on stderr (the journal). +pub fn record_fallback(reason: &str) { + let reason = reason.replace(['\n', '\r'], " "); + FALLBACKS.fetch_add(1, Ordering::SeqCst); + *LAST_REASON.lock().unwrap_or_else(|e| e.into_inner()) = Some(reason.clone()); + if let Some(path) = marker() { + if let Ok(mut file) = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&path) + { + let _ = writeln!(file, "{reason}"); + } + } + eprintln!("{LOG_PREFIX}: the GPU is unusable for this process, the LIF tick runs on the CPU from here on: {reason}"); +} + +/// True once any fallback was recorded, here or (with a marker) by a sibling worker. +pub fn gpu_unusable() -> bool { + fallbacks() > 0 +} + +/// Fallbacks recorded: the marker's lines when there is a marker, else this process's count. +pub fn fallbacks() -> u64 { + match marker() { + Some(path) => marker_lines(&path).len() as u64, + None => FALLBACKS.load(Ordering::SeqCst), + } +} + +/// The fallbacks recorded in the marker file at `path` (what a launcher's worker processes wrote). +pub fn marker_fallbacks(path: &Path) -> u64 { + marker_lines(path).len() as u64 +} + +/// The latest fallback's reason. +pub fn last_reason() -> Option { + match marker() { + Some(path) => marker_lines(&path).pop(), + None => LAST_REASON.lock().unwrap_or_else(|e| e.into_inner()).clone(), + } +} + +/// Clears this process's record (tests only; a marker is cleared with [`reset_marker`]). +#[doc(hidden)] +pub fn reset_for_tests() { + FALLBACKS.store(0, Ordering::SeqCst); + *LAST_REASON.lock().unwrap_or_else(|e| e.into_inner()) = None; +} + +/// Prometheus text: which backend runs (`1` on exactly one of the two labels), which one was +/// asked for, and the fallbacks so far. +pub fn render_prometheus(active: LifBackend, wanted: LifBackend) -> String { + let on = |backend: &str, is: bool| { + format!("fly_brain_backend{{backend=\"{backend}\"}} {}\n", u8::from(is)) + }; + let cuda = matches!(active, LifBackend::Cuda { .. }); + let mut out = String::new(); + out.push_str("# HELP fly_brain_backend 1 for the hardware the LIF tick runs on, 0 for the other. cpu while FLY_LIF_CUDA=1 asks for cuda means the GPU fell back.\n# TYPE fly_brain_backend gauge\n"); + out.push_str(&on("cpu", !cuda)); + out.push_str(&on("cuda", cuda)); + out.push_str(&format!( + "# HELP fly_brain_backend_wanted 1 when FLY_LIF_CUDA=1 asks for the GPU.\n# TYPE fly_brain_backend_wanted gauge\nfly_brain_backend_wanted {}\n", + u8::from(matches!(wanted, LifBackend::Cuda { .. })) + )); + out.push_str(&format!( + "# HELP fly_brain_backend_fallbacks_total GPU failures that moved the LIF tick to the CPU (a failed batch or sync, or an attach that failed) since the process started.\n# TYPE fly_brain_backend_fallbacks_total counter\nfly_brain_backend_fallbacks_total {}\n", + fallbacks() + )); + out +} + +/// Writes [`render_prometheus`] to [`PROM_ENV`] (temp file and rename), if set. A failure is +/// reported on stderr and otherwise ignored: a metric must not stop the brain. +pub fn write_textfile(active: LifBackend, wanted: LifBackend) { + let Some(path) = std::env::var_os(PROM_ENV).filter(|p| !p.is_empty()) else { + return; + }; + let path = PathBuf::from(path); + let tmp = path.with_extension(format!("prom.{}", std::process::id())); + let text = render_prometheus(active, wanted); + if let Some(parent) = path.parent() { + let _ = std::fs::create_dir_all(parent); + } + let written = std::fs::write(&tmp, text).and_then(|()| std::fs::rename(&tmp, &path)); + if let Err(error) = written { + let _ = std::fs::remove_file(&tmp); + eprintln!("lif backend metric: cannot write {}: {error}", path.display()); + } +} diff --git a/services/flysim/crates/flybrain-core/tests/gpu_health.rs b/services/flysim/crates/flybrain-core/tests/gpu_health.rs new file mode 100644 index 0000000..557c647 --- /dev/null +++ b/services/flysim/crates/flybrain-core/tests/gpu_health.rs @@ -0,0 +1,57 @@ +//! The GPU fallback record (`lif::health`): one failure makes the GPU unusable for the process, +//! it is counted and logged once per failure, a marker file carries it to sibling worker +//! processes, and the metric text names the backend that runs. + +use flybrain_core::lif::LifBackend; +use flybrain_core::lif::health; + +#[test] +fn a_failure_marks_the_gpu_unusable_and_is_exported() { + // The only test in this binary: it owns the process-wide record and the environment. + health::reset_for_tests(); + assert!(!health::gpu_unusable()); + assert_eq!(health::fallbacks(), 0); + + let cuda = LifBackend::Cuda { device: 0 }; + let before = health::render_prometheus(cuda, cuda); + assert!(before.contains("fly_brain_backend{backend=\"cuda\"} 1")); + assert!(before.contains("fly_brain_backend{backend=\"cpu\"} 0")); + assert!(before.contains("fly_brain_backend_fallbacks_total 0")); + + health::record_fallback("device lost\nsecond line"); + assert!(health::gpu_unusable()); + assert_eq!(health::fallbacks(), 1); + assert_eq!(health::last_reason().as_deref(), Some("device lost second line")); + let after = health::render_prometheus(LifBackend::Cpu, cuda); + assert!(after.contains("fly_brain_backend{backend=\"cpu\"} 1")); + assert!(after.contains("fly_brain_backend{backend=\"cuda\"} 0")); + assert!(after.contains("fly_brain_backend_wanted 1")); + assert!(after.contains("fly_brain_backend_fallbacks_total 1")); + + // With a marker the file is the record: a sibling process's failure counts here, and + // resetting it (a new launcher) ends the fallback. + let dir = tempfile::tempdir().expect("tmp"); + let marker = dir.path().join("lif-gpu-fallbacks"); + let prom = dir.path().join("fly_brain_backend.prom"); + // SAFETY: single test in this binary, no other thread reads the environment. + unsafe { + std::env::set_var(health::MARKER_ENV, &marker); + std::env::set_var(health::PROM_ENV, &prom); + } + assert!(!health::gpu_unusable(), "an empty marker is a clean slate"); + std::fs::write(&marker, "from a worker process\n").expect("marker"); + assert!(health::gpu_unusable()); + assert_eq!(health::fallbacks(), 1); + health::record_fallback("second"); + assert_eq!(health::fallbacks(), 2); + assert_eq!(health::marker_fallbacks(&marker), 2); + health::write_textfile(LifBackend::Cpu, cuda); + let text = std::fs::read_to_string(&prom).expect("textfile"); + assert!(text.contains("fly_brain_backend_fallbacks_total 2"), "{text}"); + health::reset_marker(&marker); + assert!(!health::gpu_unusable()); + unsafe { + std::env::remove_var(health::MARKER_ENV); + std::env::remove_var(health::PROM_ENV); + } +}