Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 131 additions & 0 deletions benchmarks/sparse_current.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
"""Benchmark actual FlyVis Network forward/backward on its visual connectome.

Run after installing FlyVis: python benchmarks/sparse_current.py --out results.jsonl
Model compilation and data loading are excluded. No training dataset is needed.
"""

import argparse
import gc
import json
import platform
import statistics
import subprocess
import time
from pathlib import Path

import torch

from flyvis import Network


def measure(backend, extent, batch, steps, repeats, warmup):
torch.manual_seed(20260926)
model = Network(
connectome=dict(
type="ConnectomeFromAvgFilters",
file="fib25-fib19_v2.2.json",
extent=extent,
n_syn_fill=1,
),
backend=backend,
)
torch.manual_seed(20260927)
stimulus = torch.randn(batch, steps, model.n_nodes) * 0.1

def step():
model.zero_grad(set_to_none=True)
output = model(stimulus, dt=0.02)
loss = output.square().mean()
loss.backward()
return loss

for _ in range(warmup):
step()
model.zero_grad(set_to_none=True)
gc.collect()
torch.cuda.empty_cache()
torch.cuda.synchronize()
baseline = torch.cuda.memory_allocated()
torch.cuda.reset_peak_memory_stats()
measurements = []
for _ in range(repeats):
torch.cuda.synchronize()
start = time.perf_counter()
loss = step()
torch.cuda.synchronize()
measurements.append((time.perf_counter() - start) * 1000)
peak = torch.cuda.max_memory_allocated()
result = dict(
backend=backend,
extent=extent,
nodes=model.n_nodes,
edges=model.n_edges,
trainable_parameters=sum(
p.numel() for p in model.parameters() if p.requires_grad
),
batch=batch,
steps=steps,
dtype=str(stimulus.dtype),
dt=0.02,
repeats=repeats,
warmup=warmup,
forward_backward_ms=statistics.median(measurements),
repetition_ms=measurements,
baseline_bytes=baseline,
peak_bytes=peak,
incremental_peak_bytes=peak - baseline,
loss=float(loss.detach()),
gradients_finite=all(
bool(torch.isfinite(p.grad).all())
for p in model.parameters()
if p.requires_grad and p.grad is not None
),
)
model.zero_grad(set_to_none=True)
gc.collect()
torch.cuda.empty_cache()
return result


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--extent", type=int, default=15)
parser.add_argument("--batches", type=int, nargs="+", default=[4, 16])
parser.add_argument("--steps", type=int, nargs="+", default=[8, 32])
parser.add_argument("--repeats", type=int, default=5)
parser.add_argument("--warmup", type=int, default=2)
parser.add_argument("--out", type=Path, required=True)
args = parser.parse_args()
if not torch.cuda.is_available():
parser.error("This peak-memory benchmark requires CUDA")
torch.set_default_device("cuda")
torch.set_default_dtype(torch.float32)
torch.set_num_threads(4)
environment = dict(
torch=torch.__version__,
cuda=torch.version.cuda,
device=torch.cuda.get_device_name(),
platform=platform.platform(),
python=platform.python_version(),
threads=torch.get_num_threads(),
source_commit=subprocess.check_output(
["git", "rev-parse", "HEAD"], text=True
).strip(),
source_dirty=bool(subprocess.check_output(["git", "status", "--porcelain"])),
)
args.out.parent.mkdir(parents=True, exist_ok=True)
with args.out.open("w", encoding="utf-8") as stream:
for batch in args.batches:
for steps in args.steps:
for backend in ("scatter", "csr"):
result = measure(
backend, args.extent, batch, steps, args.repeats, args.warmup
)
result["environment"] = environment
stream.write(json.dumps(result) + "\n")
stream.flush()
print(json.dumps(result), flush=True)


if __name__ == "__main__":
main()
43 changes: 43 additions & 0 deletions docs/docs/reference/network.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,48 @@
# Network

## Optional CSR aggregation

`Network(backend="csr")` selects CSR aggregation for the default
`PPNeuronIGRSynapses` dynamics. The default remains `backend="scatter"`.
For Hydra-based training, set the solver override `backend=csr`.

The default scatter path expands activity to `[batch, edges]` before activation
and weighted summation. The sparse backend instead activates `[batch, nodes]`
and computes the same summed current with sparse matrix multiplication. Its
custom backward samples the weight gradient only at existing connections; it
does not construct a dense `[nodes, nodes]` gradient. Forward and transposed CSR
layouts are cached, so backward does not sort the graph at each time step.

Shared synaptic strengths, signs, counts, biases, time constants, Euler updates,
and node state hooks retain their existing meaning. Unsorted and parallel edges
are supported: parallel weights are summed once per forward and gradients flow
to every original edge. Per-edge current inspection still uses the original
connectome ordering and will allocate edge-sized tensors when requested.

Backend activation storage scales with `batch * nodes * steps` instead of
`batch * edges * steps`. Graph layouts, parameters, output trajectories and
temporary workspace still consume memory. Use CSR at batch sizes of 16 or more on the
supplied visual-system graph, or when memory limits training. On the RTX 5090
and H200, scatter was faster at batch 4 and CSR was faster at batch 16.

Requirements and limitations:

- CPU or CUDA, float32 or float64, with PyTorch CSR `sampled_addmm` support.
- First-order gradients only; higher-order derivatives are unsupported.
- The built-in `PPNeuronIGRSynapses` class and its out-of-place pointwise
activations. Other dynamics continue to use scatter.
- Fixed topology. Construct a new network for a different connectome.
- No AMP, `torch.compile`, MPS or arbitrary custom-activation support is claimed.

CSR layouts are nonpersistent buffers. A sparse network and a scatter network
constructed from the same configuration have compatible parameter state dicts.
Reconstructing a network from `network.config` uses scatter by default,
including for models trained with CSR.

Run `python benchmarks/sparse_current.py --out results.jsonl` for a bounded
forward/backward benchmark on the supplied visual-system connectome. It does
not require downloading the training dataset or running an optimization job.

::: flyvis.network.network.Network

## Stimulus
Expand Down
1 change: 1 addition & 0 deletions flyvis/config/solver.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
ensemble_and_network_id: ???
task_name: ???
train: true
backend: scatter
resume: false
checkpoint_only: false
network_name: ${task_name}/${ensemble_and_network_id}
Expand Down
18 changes: 10 additions & 8 deletions flyvis/network/dynamics.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,7 @@ def write_state_velocity(
target_sum: Callable,
x_t: torch.Tensor,
dt: float,
current_sum: Callable = None,
**kwargs,
) -> None:
"""
Expand All @@ -202,19 +203,20 @@ def write_state_velocity(
target_sum: Function to sum edge values for each target node.
x_t: External input at time t.
dt: Time step.
current_sum: Optional node-level weighted aggregation. The sparse
backend activates each neuron before propagation instead of
materializing an activated copy for every outgoing edge.
**kwargs: Additional keyword arguments.
"""
internal_current = (
target_sum(params.edges.weight * self.activation(state.sources.activity))
if current_sum is None
else current_sum(self.activation(state.nodes.activity))
)
vel.nodes.activity = (
1
/ torch.max(params.nodes.time_const, torch.tensor(dt).float())
* (
-state.nodes.activity
+ params.nodes.bias
+ target_sum(
params.edges.weight * self.activation(state.sources.activity)
) # internal chemical current
+ x_t
)
* (-state.nodes.activity + params.nodes.bias + internal_current + x_t)
)

def currents(
Expand Down
33 changes: 31 additions & 2 deletions flyvis/network/network.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import logging
import warnings
from contextlib import contextmanager
from functools import partial
from typing import Any, Callable, Dict, Iterable, Literal, Optional, Union

import numpy as np
Expand All @@ -29,8 +30,9 @@
from flyvis.utils.nn_utils import n_params, simulation
from flyvis.utils.tensor_utils import AutoDeref, RefTensor

from .dynamics import NetworkDynamics
from .dynamics import NetworkDynamics, PPNeuronIGRSynapses
from .initialization import Parameter
from .sparse import SparseCurrent
from .stimulus import init_stimulus

logger = logging.getLogger(__name__)
Expand All @@ -46,6 +48,9 @@ class Network(nn.Module):
dynamics: Network dynamics configuration.
node_config: Node parameter configuration.
edge_config: Edge parameter configuration.
backend: ``"scatter"`` (default) or ``"csr"``. The latter
avoids edge-by-batch activations for the default PPNeuronIGRSynapses
dynamics, with first-order float32/float64 gradients on CPU/CUDA.

Attributes:
connectome (Connectome): Connectome directory.
Expand Down Expand Up @@ -120,6 +125,7 @@ def __init__(
),
),
stimulus_config: Dict[str, Any] = Namespace(type="Stimulus", init_buffer=False),
backend: str = "scatter",
):
super().__init__()

Expand All @@ -133,6 +139,17 @@ def __init__(
# Store the connectome, dynamics, and parameters.
self.connectome = init_connectome(**connectome)
self.dynamics = forward_subclass(NetworkDynamics, dynamics)
if backend not in ("scatter", "csr"):
raise ValueError(f"Unknown propagation backend: {backend!r}")
if backend == "csr" and (
type(self.dynamics) is not PPNeuronIGRSynapses
or getattr(self.dynamics.activation, "inplace", False)
):
raise ValueError(
"csr requires PPNeuronIGRSynapses with a built-in, "
"out-of-place pointwise activation"
)
self.backend = backend

# Load constant indices into memory.
# Store source/target indices.
Expand All @@ -141,6 +158,11 @@ def __init__(

self.n_nodes = len(self.connectome.nodes.index)
self.n_edges = len(self.connectome.edges.source_index)
self._sparse_current = (
SparseCurrent(self._source_indices, self._target_indices, self.n_nodes)
if backend == "csr"
else None
)

# Optional way of parameter sharing is averaging at every call across
# precomputed masks. This can be useful for e.g. symmetric electrical
Expand Down Expand Up @@ -293,6 +315,8 @@ def _param_api(self) -> AutoDeref[str, AutoDeref[str, RefTensor]]:
params[route][param_name] = RefTensor(values, indices)
# Add derived parameters.
self.dynamics.write_derived_params(params)
if self._sparse_current is not None:
params.edges.csr_weight = self._sparse_current.prepare(params.edges.weight)
for k, v in params.nodes.items():
if k not in params.sources:
params.sources[k] = self._source_gather(v)
Expand Down Expand Up @@ -397,8 +421,13 @@ def _next_state(
"""
vel = AutoDeref(nodes=AutoDeref(), edges=AutoDeref())

kwargs = {}
if self._sparse_current is not None:
kwargs["current_sum"] = partial(
self._sparse_current, values=params.edges.csr_weight
)
self.dynamics.write_state_velocity(
vel, state, params, self.target_sum, x_t, dt=dt
vel, state, params, self.target_sum, x_t, dt=dt, **kwargs
)

next_state = AutoDeref(
Expand Down
Loading