Merge port/gpu-02 (reviewed: APPROVE-WITH-NOTES; N1/N2 fixed: a dead GPU makes the process CPU-only and the replacement restores on the CPU): the GPU brain steps a whole frame per call with state resident on the card (cuda feature, off by default)

This commit is contained in:
acamilo 2026-10-02 11:51:47 +00:00
commit e1f594425e
19 changed files with 1829 additions and 152 deletions

View file

@ -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 # so FLY_ENCODER-style flipping between backends across restarts keeps the
# checkpoint: the compatibility string this script gates on does not move. # checkpoint: the compatibility string this script gates on does not move.
echo "FLY_LIF_CUDA=${FLY_LIF_CUDA:-0}" 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 # 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 # 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 # the CHAT panel blanks without touching flybridge or the page. flysim reads

View file

@ -48,6 +48,8 @@ log_info() {
# encoder actually opened (docs/design/gpu.md section 5). # encoder actually opened (docs/design/gpu.md section 5).
: "${FLY_ENCODER_METRIC:=${TEXTFILE_DIR}/fly_encoder.prom}" : "${FLY_ENCODER_METRIC:=${TEXTFILE_DIR}/fly_encoder.prom}"
: "${FLY_ENV_FILE:=/etc/fly/fly.env}" : "${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}" : "${FLY_PROC_DIR:=/proc}"
# --- check 9 (capture freeze) inputs, infra/docs/capture-freeze.md --------- # --- check 9 (capture freeze) inputs, infra/docs/capture-freeze.md ---------
: "${FLY_REC_DIR:=/srv/fly/media/rec}" # flycast's 10-minute mpegts segments : "${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 "# 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 "# TYPE fly_watchdog_encoder_degraded gauge"
echo "fly_watchdog_encoder_degraded $(cat "${WD_RUN_DIR}/encoder_degraded" 2>/dev/null || echo -1)" 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 # Check 9 (infra/docs/capture-freeze.md). fly_capture_identical_frames
# is -1 until the first probe completes, the same "unknown, not # is -1 until the first probe completes, the same "unknown, not
# broken" convention fly_watchdog_encoder_degraded uses; a value at or # 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" "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). # Check 9: capture freeze (infra/docs/capture-freeze.md).
# #
@ -1333,6 +1371,7 @@ main() {
check_flystage check_flystage
check_flycast check_flycast
check_encoder check_encoder
check_backend
check_mediamtx check_mediamtx
check_flypush check_flypush
check_disk check_disk

View file

@ -1182,13 +1182,49 @@ 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 | | 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* | | 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: backend from flysim's own log, not from the env file:
```sh ```sh
pct exec <ctid> -- journalctl -u flysim -b --no-pager | grep -i 'cuda\|lif backend' pct exec <ctid> -- 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. 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:<n> 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. 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 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 container — `docs/design/gpu.md` sections 1 and 2) and the card the committed PTX
targets, `sm_75`. targets, `sm_75`.

View file

@ -535,6 +535,7 @@ dependencies = [
"serde", "serde",
"serde_json", "serde_json",
"sha2", "sha2",
"tempfile",
] ]
[[package]] [[package]]

View file

@ -21,6 +21,11 @@ path = "src/bin/flysim-session.rs"
name = "fly-shadow" name = "fly-shadow"
path = "src/bin/fly-shadow.rs" 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] [dependencies]
# The session framework and its legacy workers (AGENT-01, ENV-01). # The session framework and its legacy workers (AGENT-01, ENV-01).
fly-session = { path = "../fly-session" } fly-session = { path = "../fly-session" }

View file

@ -18,6 +18,11 @@ path = "src/lib.rs"
name = "fly-session" name = "fly-session"
path = "src/bin/fly-session.rs" 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] [dependencies]
# The domain contract (scalars, payloads, canonical digests, the trace format) and the bus. # The domain contract (scalars, payloads, canonical digests, the trace format) and the bus.
# Everything else this crate needs is std or Tokio. # Everything else this crate needs is std or Tokio.

View file

@ -417,6 +417,10 @@ struct Endpoints {
own: Via, own: Via,
store_root: PathBuf, store_root: PathBuf,
sockets: 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, next_socket: AtomicU64,
listeners: Mutex<Vec<UnixListenerHandle>>, listeners: Mutex<Vec<UnixListenerHandle>>,
} }
@ -575,6 +579,13 @@ pub fn die_with_parent(command: &mut std::process::Command) {
} }
impl Launcher { 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. /// Connects the supervisor and prepares the launcher. Nothing is started yet.
pub async fn start( pub async fn start(
router: Router, router: Router,
@ -588,6 +599,8 @@ impl Launcher {
std::fs::create_dir_all(&sockets).map_err(|e| { std::fs::create_dir_all(&sockets).map_err(|e| {
flybus::BusError::new(flybus::ErrorCode::StoreFailure, format!("sockets: {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 { let endpoints = Endpoints {
router, router,
via: mode.transport(via), via: mode.transport(via),
@ -597,6 +610,7 @@ impl Launcher {
}, },
store_root: store_root.into(), store_root: store_root.into(),
sockets, sockets,
gpu_marker,
next_socket: AtomicU64::new(0), next_socket: AtomicU64::new(0),
listeners: Mutex::new(Vec::new()), listeners: Mutex::new(Vec::new()),
}; };
@ -1036,6 +1050,7 @@ impl Launcher {
.arg(flybrain_core::pool::format_cpu_list(&cpus.sweep)); .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()); command.stdin(std::process::Stdio::null());
die_with_parent(&mut command); die_with_parent(&mut command);
let child = command.spawn().map_err(|e| { let child = command.spawn().map_err(|e| {
@ -1698,6 +1713,9 @@ pub(crate) fn legacy_agent_config(spec: &LegacyAgentLaunch, worker_threads: usiz
dataset_dir: spec.dataset_dir.clone(), dataset_dir: spec.dataset_dir.clone(),
profile: spec.profile, profile: spec.profile,
macro_channels: spec.macro_channels.clone(), 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(),
} }
} }

View file

@ -42,7 +42,8 @@ use flybrain_core::envelope::{
agent_from_chunks, agent_to_chunks, decode_envelope, encode_envelope, agent_from_chunks, agent_to_chunks, decode_envelope, encode_envelope,
}; };
use flybrain_core::json::JsonValue; use flybrain_core::json::JsonValue;
use flybrain_core::lif::{LifConfig, SweepPlan, kernel_version}; use flybrain_core::lif::health as lif_health;
use flybrain_core::lif::{LifBackend, LifConfig, SweepPlan, kernel_version};
use serde_json::{Value, json}; use serde_json::{Value, json};
use crate::clock::TickAccumulator; use crate::clock::TickAccumulator;
@ -460,6 +461,10 @@ pub struct LegacyAgentConfig {
pub profile: LegacyProfileKind, pub profile: LegacyProfileKind,
/// The composition's `executor.macroChannels`, in composition order; empty in raw mode. /// The composition's `executor.macroChannels`, in composition order; empty in raw mode.
pub macro_channels: Vec<String>, pub macro_channels: Vec<String>,
/// 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<LifBackend, String>,
} }
#[derive(Clone, Debug, PartialEq, Eq)] #[derive(Clone, Debug, PartialEq, Eq)]
@ -511,9 +516,9 @@ pub struct LegacyAgentWorker {
/// The brain time before the in-flight transition's ticks: the spike window's start. /// The brain time before the in-flight transition's ticks: the spike window's start.
transition_start_ms: f64, transition_start_ms: f64,
/// The in-flight transition's spike bitset, gathered tick by tick from the kernel's spike /// 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 /// lists during Prepare (PERF-01; on the GPU too since GPU-02). It is the bitset
/// `last_spike_ms` for the same window, without the 139,255-neuron scan. `None` when the /// `spike_bitset` would scan out of `last_spike_ms` for the same window, without the
/// kernel keeps no per-tick list (the GPU backend): Commit scans as before. /// 139,255-neuron scan. `None` only before a Prepare: Commit then scans.
tick_spikes: Option<Vec<u8>>, tick_spikes: Option<Vec<u8>>,
staged: Option<StagedAgent>, staged: Option<StagedAgent>,
activated: BTreeSet<Id>, activated: BTreeSet<Id>,
@ -869,6 +874,63 @@ impl LegacyAgentWorker {
/// Builds a network and readout over `dataset`, before any state is installed, and checks /// 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. /// 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<LifBackend, DomainError> {
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( fn build_agent(
&self, &self,
dataset: Arc<BrainDataset>, dataset: Arc<BrainDataset>,
@ -933,8 +995,21 @@ impl LegacyAgentWorker {
if self.config.worker_threads > 1 { if self.config.worker_threads > 1 {
let plan = SweepPlan::with_threads(self.config.worker_threads) let plan = SweepPlan::with_threads(self.config.worker_threads)
.map_err(|e| DomainError::invalid(format!("sweep plan: {e}")))?; .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 wanted = self.config.lif_backend.clone().map_err(|e| {
DomainError::before(ErrorCode::BackendFailure, format!("LIF backend: {e}"))
})?;
let backend = self.attach_backend(&mut agent, wanted)?;
if backend != LifBackend::Cpu {
eprintln!(
"legacy agent {}: LIF backend {} attached, device-owned state",
self.config.agent_id,
backend.label()
);
}
lif_health::write_textfile(backend, wanted);
let fingerprint = self.profile.dataset_fingerprint.clone(); let fingerprint = self.profile.dataset_fingerprint.clone();
let graph = AgentGraph { let graph = AgentGraph {
dataset_digest: dataset_digest(&fingerprint), dataset_digest: dataset_digest(&fingerprint),
@ -1169,22 +1244,27 @@ impl LegacyAgentWorker {
let phase_before = agent.network.timings().total_ns(); let phase_before = agent.network.timings().total_ns();
let phases_before = agent.network.timings(); let phases_before = agent.network.timings();
let ticks_span = crate::profile::span("agent.ticks"); 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 // The frame's ticks in one call (GPU-02): on the CPU the one-tick loop `step(ticks)`
// are its spike list, so the transition's bitset is their union. // 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 bits = vec![0u8; agent.network.last_spike_ms.len().div_ceil(8)];
let mut listed = true; if let Err(e) = agent.network.step_frame(ticks, &mut bits) {
for _ in 0..ticks { // The device state was the only current copy, so this worker cannot go on: it fails
let count = agent.network.step(1) as usize; // and the replacement restores the last checkpoint on the CPU (the GPU is out for
match agent.network.tick_spikes(count) { // the process).
Some(list) if listed => { Self::gpu_failed(&self.config, &format!("{e}; the agent fails, a replacement restores the last checkpoint on the CPU"));
for &neuron in list { return Err(applied(
bits[neuron as usize >> 3] |= 1 << (neuron & 7); ErrorCode::BackendFailure,
format!("the brain ticks failed: {e}"),
));
} }
if let Some(fault) = agent.network.take_backend_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);
} }
_ => listed = false, self.tick_spikes = Some(bits);
}
}
self.tick_spikes = listed.then_some(bits);
drop(ticks_span); drop(ticks_span);
crate::profile::record( crate::profile::record(
"agent.ticks.phase_clock", "agent.ticks.phase_clock",
@ -1551,6 +1631,19 @@ impl LegacyAgentWorker {
)); ));
} }
let params: CaptureParams = ctx.params()?; 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::gpu_failed(&self.config, &format!("device state read-back: {e}"));
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 // 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 // `export_state` is. Encoding, digesting and sealing it -- milliseconds on the full
// connectome -- run after the lock is released (`HandlerReply::deferred`), so the next // connectome -- run after the lock is released (`HandlerReply::deferred`), so the next

View file

@ -991,6 +991,11 @@ impl LegacyRig {
self.launch(agent_id).await 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) { pub async fn stop(mut self) {
self.launcher.reap_all(&id("done")).await; 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"))) 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<ParityRecord>, Vec<usize>), 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( async fn run_script(
rig: &mut LegacyRig, rig: &mut LegacyRig,
agent_id: &Id, agent_id: &Id,
script: &LegacyScript, script: &LegacyScript,
start: Option<(&flybrain_core::agent::AgentState, u64)>, start: Option<(&flybrain_core::agent::AgentState, u64)>,
capture_at_end: bool, capture_at_end: bool,
) -> Result<(Vec<ParityRecord>, Option<Vec<u8>>), 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<usize>>,
) -> Result<(Vec<ParityRecord>, Option<Vec<u8>>), String> { ) -> Result<(Vec<ParityRecord>, Option<Vec<u8>>), String> {
let mut driver = rig.driver(agent_id, script); let mut driver = rig.driver(agent_id, script);
let first = match start { let first = match start {
@ -1594,7 +1640,12 @@ async fn run_script(
} }
}; };
let mut records = vec![first]; 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 { let mut record = match step {
ScriptStep::Frame { ScriptStep::Frame {
sugar, sugar,
@ -1602,9 +1653,31 @@ async fn run_script(
rewards, rewards,
next_context, next_context,
} => { } => {
driver match driver
.frame(index + 1, sugar, *frame, rewards, next_context) .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 } => { ScriptStep::Rollback { frame, context } => {
driver.rollback(index + 1, *frame, context).await? driver.rollback(index + 1, *frame, context).await?
@ -1632,8 +1705,20 @@ async fn run_script(
if script.checkpoints.contains(&index) { if script.checkpoints.contains(&index) {
let captured = driver.capture().await?; let captured = driver.capture().await?;
record.state = Some(payload_state_digest(&captured.bytes)?); 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); records.push(record);
index += 1;
} }
let captured = if capture_at_end { let captured = if capture_at_end {
Some(driver.capture().await?.bytes) Some(driver.capture().await?.bytes)

View file

@ -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<String> {
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<usize>) -> LegacyScript {
let channels = pokered_channels();
let bound = |k: usize| -> Vec<String> {
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<ParityRecord>,
recovered: Vec<usize>,
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<ParityRecord> {
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();
}

View file

@ -0,0 +1,176 @@
//! 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 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;
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<String> {
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<String> {
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()));
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()));
eprintln!(
"gpu worker {} x{threads}: {} records identical to the CPU in {:?}",
mode.label(),
got.len(),
started.elapsed()
);
}
}

View file

@ -29,6 +29,7 @@ libc = "0.2"
[dev-dependencies] [dev-dependencies]
base64.workspace = true base64.workspace = true
tempfile = "3"
[[example]] [[example]]
name = "bench" name = "bench"

View file

@ -21,13 +21,23 @@
//! ``` //! ```
//! //!
//! Optional arguments: a dataset directory, then the tick count, then the CPU thread count for the //! 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::sync::Arc;
use std::time::Instant; use std::time::Instant;
use flybrain_core::dataset::load_brain_dataset_from_dir; 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; use flybrain_core::plasticity::PlasticityConfig;
#[cfg(feature = "cuda")] #[cfg(feature = "cuda")]
@ -101,6 +111,95 @@ fn scalar(what: &str, tick: u64, cpu: f64, gpu: f64) -> Option<Divergence> {
}) })
} }
/// 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<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(|| {
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"))] #[cfg(not(feature = "cuda"))]
fn main() { fn main() {
eprintln!("cuda_exact: build with --features cuda"); eprintln!("cuda_exact: build with --features cuda");
@ -121,6 +220,14 @@ fn main() {
.next() .next()
.and_then(|value| value.parse().ok()) .and_then(|value| value.parse().ok())
.unwrap_or(4); .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")); let data = Arc::new(load_brain_dataset_from_dir(&dir).expect("the dataset must load"));
println!( println!(
@ -129,6 +236,11 @@ fn main() {
data.meta.neurons, data.meta.neurons,
data.targets.len() 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 = || { let build = || {
LifNetwork::new( LifNetwork::new(
@ -142,7 +254,7 @@ fn main() {
let mut gpu = build(); let mut gpu = build();
cpu.set_sweep_plan(SweepPlan::with_threads(threads).expect("a pool")); 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!( println!(
"cuda backend up: {:.1} MiB of device memory, max {} ticks per call", "cuda backend up: {:.1} MiB of device memory, max {} ticks per call",
backend.device_bytes as f64 / (1024.0 * 1024.0), backend.device_bytes as f64 / (1024.0 * 1024.0),
@ -213,85 +325,7 @@ fn main() {
let left = cpu.export_state(); let left = cpu.export_state();
let right = gpu.export_state(); let right = gpu.export_state();
divergence = compare_f32("membrane", tick, &left.membrane, &right.membrane) divergence = compare_states(tick, &cpu.role_names, &left, &right);
.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,
)
});
if divergence.is_some() { if divergence.is_some() {
break; 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<flybrain_core::dataset::BrainDataset>, 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<Divergence> = 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);
}
}
}

View file

@ -220,8 +220,10 @@ impl NeuralAgent {
bail!("Agent is already warmed up"); bail!("Agent is already warmed up");
} }
self.network.plasticity.enabled = false; 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; self.network.plasticity.enabled = true;
stepped?;
let rates = self.network.rates.clone(); let rates = self.network.rates.clone();
self.decoder.calibrate(&rates); self.decoder.calibrate(&rates);
if let Some(frame) = first_frame { if let Some(frame) = first_frame {

View file

@ -21,6 +21,9 @@ use crate::version::version_for;
#[cfg(feature = "cuda")] #[cfg(feature = "cuda")]
pub mod 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. /// Version of the default configuration; kept verbatim so existing checkpoints stay loadable.
pub const NEURAL_KERNEL_VERSION: &str = "lif-1ms-f64-v2"; pub const NEURAL_KERNEL_VERSION: &str = "lif-1ms-f64-v2";
@ -57,6 +60,64 @@ pub struct Stimulation {
pub drive: f64, 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<LifBackend, String> {
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<LifBackend, String> {
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::<usize>().map_err(|_| {
format!("FLY_LIF_CUDA_DEVICE={text}: expected a device ordinal (0, 1, ...)")
})?,
};
Ok(LifBackend::Cuda { device })
}
/// `cpu` or `cuda:<device>`, 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)] #[derive(Debug, Clone, PartialEq)]
pub struct LifConfig { pub struct LifConfig {
/// Membrane decay time constant in milliseconds; decay per tick is `fround(exp(-1/decayMs))`. /// Membrane decay time constant in milliseconds; decay per tick is `fround(exp(-1/decayMs))`.
@ -275,7 +336,12 @@ pub struct LifNetwork {
/// Version string of this configuration; pin it in checkpoints. /// Version string of this configuration; pin it in checkpoints.
pub version: String, pub version: String,
pub plasticity: RewardModulatedStdp, 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<f32>, pub membrane: Vec<f32>,
/// Refractory counters; stale on the same terms as `membrane`.
pub refractory: Vec<u8>, pub refractory: Vec<u8>,
pub baseline: Vec<f32>, pub baseline: Vec<f32>,
pub last_spike_ms: Vec<f64>, pub last_spike_ms: Vec<f64>,
@ -311,6 +377,8 @@ pub struct LifNetwork {
visual_drive: Vec<f32>, visual_drive: Vec<f32>,
reward_remaining: f64, reward_remaining: f64,
sweep: SweepPlan, sweep: SweepPlan,
/// Why the GPU backend was detached mid-run, until [`LifNetwork::take_backend_fault`].
backend_fault: Option<String>,
/// When set, [`LifNetwork::step`] runs steps 1-4 and 6 on the GPU; see [`cuda`]. /// When set, [`LifNetwork::step`] runs steps 1-4 and 6 on the GPU; see [`cuda`].
#[cfg(feature = "cuda")] #[cfg(feature = "cuda")]
cuda: Option<Box<cuda::CudaLif>>, cuda: Option<Box<cuda::CudaLif>>,
@ -423,6 +491,7 @@ impl LifNetwork {
timings: PhaseTimings::default(), timings: PhaseTimings::default(),
data, data,
sweep: SweepPlan::sequential(), sweep: SweepPlan::sequential(),
backend_fault: None,
#[cfg(feature = "cuda")] #[cfg(feature = "cuda")]
cuda: None, cuda: None,
}) })
@ -435,18 +504,87 @@ impl LifNetwork {
/// Choose how the per-tick parallel phases are partitioned. Results do not depend on this. /// Choose how the per-tick parallel phases are partitioned. Results do not depend on this.
pub fn set_sweep_plan(&mut self, sweep: SweepPlan) { 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(); let threads = sweep.threads();
self.target_shards = target_shards(&self.data, threads); self.target_shards = target_shards(&self.data, threads);
self.slot_shards = self.plasticity.slot_shards(threads); self.slot_shards = self.plasticity.slot_shards(threads);
self.rows_ascending = threads > 1 && rows_are_target_ascending(&self.data); self.rows_ascending = threads > 1 && rows_are_target_ascending(&self.data);
self.sweep_counts = (0..threads).map(|_| AtomicUsize::new(0)).collect(); self.sweep_counts = (0..threads).map(|_| AtomicUsize::new(0)).collect();
self.sweep = sweep; 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 /// Run the tick on `backend` from now on. Results do not depend on this.
// conditions are off by default, and with the feature absent this line does not exist. ///
/// [`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")] #[cfg(feature = "cuda")]
self.attach_cuda_if_requested(); 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")]
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<String> {
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 { pub fn sweep_plan(&self) -> &SweepPlan {
@ -508,11 +646,10 @@ impl LifNetwork {
self.stimulate(duration_ms); 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 /// 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 /// [`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 /// 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]> { pub fn tick_spikes(&self, count: usize) -> Option<&[u32]> {
#[cfg(feature = "cuda")] #[cfg(feature = "cuda")]
if self.cuda.is_some() { if self.cuda.is_some() {
@ -521,12 +658,18 @@ impl LifNetwork {
self.spikes.get(..count) 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 { 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 // 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. // feature off this compiles to nothing and the loop below is the whole method.
#[cfg(feature = "cuda")] #[cfg(feature = "cuda")]
if self.cuda.is_some() { 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; let mut total = 0u64;
for _ in 0..milliseconds { for _ in 0..milliseconds {
@ -535,6 +678,59 @@ impl LifNetwork {
total 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<u64> {
#[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<u64> {
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 { fn step_one(&mut self) -> usize {
let neurons = self.data.meta.neurons; let neurons = self.data.meta.neurons;
let threshold = self.config.threshold; let threshold = self.config.threshold;
@ -797,10 +993,15 @@ impl LifNetwork {
total 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 { pub fn export_state(&self) -> LifState {
let (membrane, refractory) = self.current_arrays();
LifState { LifState {
membrane: self.membrane.clone(), membrane,
refractory: self.refractory.clone(), refractory,
last_spike_ms: self.last_spike_ms.clone(), last_spike_ms: self.last_spike_ms.clone(),
visual_drive: self.visual_drive.clone(), visual_drive: self.visual_drive.clone(),
rng: self.rng.state(), rng: self.rng.state(),
@ -812,6 +1013,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<f32>, Vec<u8>) {
#[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. /// Import plasticity first, then validate before writing anything.
pub fn import_state(&mut self, state: &LifState) -> Result<()> { pub fn import_state(&mut self, state: &LifState) -> Result<()> {
if state.membrane.len() != self.membrane.len() if state.membrane.len() != self.membrane.len()

View file

@ -38,10 +38,19 @@
//! # State ownership //! # State ownership
//! //!
//! Between batches the device owns `membrane` and `refractory`. With //! 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 //! [`CudaLif::sync_host_each_batch`] set (the default for a backend built with [`CudaLif::new`])
//! batch, which keeps `export_state`, the status endpoints and every existing test correct with no //! they are copied back at the end of every batch, which keeps direct reads of the network's host
//! further changes. Clear it for throughput work and call [`CudaLif::sync_to_host`] explicitly //! arrays correct with no further changes: that is what `examples/cuda_exact`'s per-tick mode and
//! before a checkpoint. //! 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; use std::sync::Arc;
@ -55,6 +64,88 @@ use crate::error::{Error, Result};
use super::LifNetwork; 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 /// 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. /// `LIF_BLOCK` in `cuda/lif.cu`, because the spike bitset words are per-warp ballots.
const BLOCK: u32 = 256; const BLOCK: u32 = 256;
@ -89,6 +180,12 @@ const DEFAULT_MAX_TICKS: usize = 32;
/// neither the build nor the run needs a CUDA toolkit. /// neither the build nor the run needs a CUDA toolkit.
const LIF_PTX: &str = include_str!("../../cuda/lif.ptx"); 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 { fn driver_error(what: &str, error: impl std::fmt::Display) -> Error {
Error::new(format!("CUDA {what} failed: {error}")) Error::new(format!("CUDA {what} failed: {error}"))
} }
@ -149,6 +246,7 @@ pub struct CudaLif {
bucket_rebase_kernel: CudaFunction, bucket_rebase_kernel: CudaFunction,
bucket_apply_kernel: CudaFunction, bucket_apply_kernel: CudaFunction,
ordinal: usize,
neurons: usize, neurons: usize,
blocks: u32, blocks: u32,
max_ticks: usize, max_ticks: usize,
@ -201,7 +299,14 @@ pub struct CudaLif {
host_tick_counts: Vec<u32>, host_tick_counts: Vec<u32>,
host_spikes: Vec<u32>, host_spikes: Vec<u32>,
stimulation_schedule: Vec<bool>, stimulation_schedule: Vec<bool>,
/// The host arrays were overwritten (an import); upload them before the next batch.
host_dirty: bool, 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 /// 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. /// of the crate sees the same host state it would have seen from the CPU kernel.
@ -239,6 +344,7 @@ impl CudaLif {
} }
pub fn with_max_ticks(network: &LifNetwork, ordinal: usize, max_ticks: usize) -> Result<Self> { pub fn with_max_ticks(network: &LifNetwork, ordinal: usize, max_ticks: usize) -> Result<Self> {
inject::attach()?;
let max_ticks = max_ticks.max(1); let max_ticks = max_ticks.max(1);
let neurons = network.data.meta.neurons; let neurons = network.data.meta.neurons;
if neurons == 0 { if neurons == 0 {
@ -389,6 +495,7 @@ impl CudaLif {
bucket_rebase_kernel: function("lif_bucket_rebase")?, bucket_rebase_kernel: function("lif_bucket_rebase")?,
bucket_apply_kernel: function("lif_bucket_apply")?, bucket_apply_kernel: function("lif_bucket_apply")?,
ordinal,
neurons, neurons,
blocks, blocks,
max_ticks, max_ticks,
@ -403,6 +510,9 @@ impl CudaLif {
host_spikes: Vec::new(), host_spikes: Vec::new(),
stimulation_schedule: vec![false; max_ticks], stimulation_schedule: vec![false; max_ticks],
host_dirty: false, host_dirty: false,
host_stale: false,
uploaded_bytes: 0,
downloaded_bytes: 0,
batch_start: context batch_start: context
.new_event(Some(CUevent_flags::CU_EVENT_DEFAULT)) .new_event(Some(CUevent_flags::CU_EVENT_DEFAULT))
.map_err(|error| driver_error("event creation", error))?, .map_err(|error| driver_error("event creation", error))?,
@ -429,19 +539,33 @@ impl CudaLif {
Ok(backend) Ok(backend)
} }
/// The device ordinal this backend runs on.
pub fn ordinal(&self) -> usize {
self.ordinal
}
/// Ticks this backend accepts per call. /// Ticks this backend accepts per call.
pub fn max_ticks(&self) -> usize { pub fn max_ticks(&self) -> usize {
self.max_ticks self.max_ticks
} }
/// The host copies of `membrane` and `refractory` have been written; re-upload them before the /// 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) { pub fn mark_host_dirty(&mut self) {
self.host_dirty = true; 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. /// Copy `membrane` and `refractory` from the device into the network's host arrays.
pub fn sync_to_host(&mut self, network: &mut LifNetwork) -> Result<()> { pub fn sync_to_host(&mut self, network: &mut LifNetwork) -> Result<()> {
inject::sync()?;
self.stream self.stream
.memcpy_dtoh(&self.membrane, &mut network.membrane[..]) .memcpy_dtoh(&self.membrane, &mut network.membrane[..])
.map_err(|error| driver_error("membrane download", error))?; .map_err(|error| driver_error("membrane download", error))?;
@ -450,7 +574,28 @@ impl CudaLif {
.map_err(|error| driver_error("refractory download", error))?; .map_err(|error| driver_error("refractory download", error))?;
self.stream self.stream
.synchronize() .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<f32>, Vec<u8>)> {
inject::sync()?;
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<()> { fn upload_state(&mut self, network: &LifNetwork) -> Result<()> {
@ -460,12 +605,61 @@ impl CudaLif {
self.stream self.stream
.memcpy_htod(&network.refractory[..], &mut self.refractory) .memcpy_htod(&network.refractory[..], &mut self.refractory)
.map_err(|error| driver_error("refractory upload", error))?; .map_err(|error| driver_error("refractory upload", error))?;
self.uploaded_bytes += (self.neurons * 5) as u64;
self.host_dirty = false; self.host_dirty = false;
Ok(()) Ok(())
} }
/// Run `ticks` GPU ticks and replay the host-side phases against the spike lists they produce. /// 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<usize> { /// 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<usize, BatchFailure> {
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<usize> {
debug_assert!(ticks <= self.max_ticks); debug_assert!(ticks <= self.max_ticks);
let neurons = self.neurons; let neurons = self.neurons;
@ -508,7 +702,9 @@ impl CudaLif {
// Uploads: the batch's noise groups, this frame's visual drive, the plastic gains permuted // Uploads: the batch's noise groups, this frame's visual drive, the plastic gains permuted
// into the transposed array's rank order. // into the transposed array's rank order.
let used = ticks * self.noise_kicks; let used = ticks * self.noise_kicks;
let mut uploaded = 0usize;
if used > 0 { if used > 0 {
uploaded += used * 8;
let mut view = self.noise_neuron.slice_mut(0..used); let mut view = self.noise_neuron.slice_mut(0..used);
self.stream self.stream
.memcpy_htod(&self.host_noise_neuron[..used], &mut view) .memcpy_htod(&self.host_noise_neuron[..used], &mut view)
@ -519,12 +715,14 @@ impl CudaLif {
.map_err(|error| driver_error("noise upload", error))?; .map_err(|error| driver_error("noise upload", error))?;
} }
if !network.visual_drive.is_empty() { 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()); let mut view = self.visual_drive.slice_mut(0..network.visual_drive.len());
self.stream self.stream
.memcpy_htod(&network.visual_drive[..], &mut view) .memcpy_htod(&network.visual_drive[..], &mut view)
.map_err(|error| driver_error("visual drive upload", error))?; .map_err(|error| driver_error("visual drive upload", error))?;
} }
if !network.plasticity.gains.is_empty() { if !network.plasticity.gains.is_empty() {
uploaded += network.plasticity.gains.len() * 4;
let mut view = self.gains.slice_mut(0..network.plasticity.gains.len()); let mut view = self.gains.slice_mut(0..network.plasticity.gains.len());
self.stream self.stream
.memcpy_htod(&network.plasticity.gains[..], &mut view) .memcpy_htod(&network.plasticity.gains[..], &mut view)
@ -546,6 +744,7 @@ impl CudaLif {
self.stream self.stream
.synchronize() .synchronize()
.map_err(|error| driver_error("synchronize", error))?; .map_err(|error| driver_error("synchronize", error))?;
inject::batch()?;
self.kernel_ms += f64::from( self.kernel_ms += f64::from(
self.batch_start self.batch_start
.elapsed_ms(&self.batch_end) .elapsed_ms(&self.batch_end)
@ -583,22 +782,9 @@ impl CudaLif {
self.stream self.stream
.synchronize() .synchronize()
.map_err(|error| driver_error("synchronize", error))?; .map_err(|error| driver_error("synchronize", error))?;
self.uploaded_bytes += uploaded as u64;
// The host phases, per tick, in the sequential kernel's order. self.downloaded_bytes += ((ticks + total) * 4) as u64;
let mut at = 0usize; Ok(total)
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)
} }
/// Record phase mark `index` when phase profiling is on. /// Record phase mark `index` when phase profiling is on.
@ -839,37 +1025,110 @@ impl LifNetwork {
/// Attach a backend when `FLY_LIF_CUDA=1`, on device `FLY_LIF_CUDA_DEVICE` (default 0). /// 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 /// 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. /// and silently got the CPU would report a bit-exactness pass that means nothing.
pub(super) fn attach_cuda_if_requested(&mut self) { 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; return;
} }
let ordinal = std::env::var("FLY_LIF_CUDA_DEVICE") let Ok(super::LifBackend::Cuda { device }) = super::LifBackend::from_env() else {
.ok() return;
.and_then(|value| value.parse::<usize>().ok()) };
.unwrap_or(0); match CudaLif::new(self, device) {
match CudaLif::new(self, ordinal) {
Ok(backend) => self.attach_cuda(backend), Ok(backend) => self.attach_cuda(backend),
Err(error) => panic!("FLY_LIF_CUDA=1 but the CUDA backend would not start: {error}"), Err(error) => panic!("FLY_LIF_CUDA=1 but the CUDA backend would not start: {error}"),
} }
} }
/// The batched GPU path behind [`LifNetwork::step`]. /// Attach a device-owned backend on `device`, or switch an attached one to device-owned state.
pub(super) fn step_on_cuda(&mut self, milliseconds: u64) -> u64 { 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<Result<(Vec<f32>, Vec<u8>)>> {
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<u64> {
let mut backend = self.cuda.take().expect("a CUDA backend is attached"); let mut backend = self.cuda.take().expect("a CUDA backend is attached");
let mut total = 0u64; let mut total = 0u64;
let mut left = milliseconds; let mut left = milliseconds;
while left > 0 { while left > 0 {
let ticks = left.min(backend.max_ticks() as u64) as usize; 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, 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; left -= ticks as u64;
} }
self.cuda = Some(backend); 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 /// Steps 5, 6 (the spike stamp and role tally only), 7 and 8 of `step_one`, against a spike

View file

@ -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<Option<String>> = Mutex::new(None);
fn marker() -> Option<PathBuf> {
std::env::var_os(MARKER_ENV)
.filter(|path| !path.is_empty())
.map(PathBuf::from)
}
fn marker_lines(path: &Path) -> Vec<String> {
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<String> {
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());
}
}

View file

@ -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);
}
}

View file

@ -1,6 +1,6 @@
//! `LifNetwork::tick_spikes` (PERF-01): after a one-tick `step`, the list is exactly the neurons //! `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 //! 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; 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"); 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());
}