OSCR

An all-magnonic neuron with tunable fading memory

Code ↔ Paper

6 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

The 6 matches
  1. [1] § MATERIALS AND METHODS › Time-domain network training with the differentiable neuron model › Architecture ↔ src/physical_snn/iris_experiment.py, lines 318 to 442 · score 0.94 · hidden layer response, hidden weights, trainable parameters, linear readout, physical neurons, pulse trains · Report a mismatch
  2. [2] § RESULTS › Functional benchmark of the temporal neuron response ↔ src/physical_snn/iris_experiment.py, lines 318 to 442 · score 0.84 · hidden layer response, linear readout, physical neuron, pulse spacing, permuted, Iris · Report a mismatch
  3. [3] § MATERIALS AND METHODS › Numerical neuron model ↔ code/scripts/main.ipynb, lines 130 to 163 · score 0.66 · simulation timestep, excitation efficiency, simulation parameters, Gaussian, numerical, dispersion · Report a mismatch
  4. [4] § MATERIALS AND METHODS › Wave-vector calculation ↔ code/scripts/main.ipynb, lines 130 to 163 · score 0.65 · FMR frequency, cross shift, fit, quadratic, coefficient, dispersion · Report a mismatch
  5. [5] § RESULTS › Functional benchmark of the temporal neuron response ↔ src/physical_snn/iris_experiment.py, lines 787 to 857 · score 0.53 · validation accuracy, pulse trains, Iris, epoch, hidden, baseline · Report a mismatch
  6. [6] § MATERIALS AND METHODS › Time-domain network training with the differentiable neuron model ↔ src/physical_snn/iris_experiment.py, lines 245 to 310 · score 0.51 · Euler solver, PyTorch, dynamics, simulated, neuron · Report a mismatch

Paper

Loaded from Europe PMC by your browser; OSCR does not store it: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Python · 1,040 lines · 42 KB · MIT · 4 matches

  1. #!/usr/bin/env python3
  2. """
  3. Train and evaluate a differentiable time-domain / spiking neural network on Iris.
  4. This corrected standalone script follows reproduce_two_pulse_correlation_standalone.py
  5. more directly than the earlier training version:
  6. 1. It reads the embedded lookup tables from reproduce_two_pulse_correlation_standalone.py.
  7. 2. It uses a differentiable torch implementation of the reference eta(k) interpolation.
  8. 3. It keeps the original reference rule eta(k)=1 for k < k_max unless disabled.
  9. 4. It uses the same Euler response equation:
  10. dc_sq/dt = eta(k) * pwr_exc - decay(k) * c_sq - decay_prime * c_sq**2
  11. k = sqrt(max((f - f0 - W_cross*c_sq_in - W_self*c_sq)/a, 0))
  12. 5. It uses fixed decay_fix=0.016722666 by default, matching the common reference setting.
  13. Optionally, --use-decay-lookup enables differentiable decay(k) interpolation.
  14. Install:
  15. pip install numpy matplotlib scikit-learn torch
  16. Run, assuming the reference file is in the same folder:
  17. python train_iris_physical_snn_standalone_corrected.py \
  18. --reference-neuron-code reproduce_two_pulse_correlation_standalone.py
  19. Typical run:
  20. python train_iris_physical_snn_standalone_corrected.py \
  21. --M 10 --N 10 --repetitions 2 --epochs 100 \
  22. --t-start-ns 500 --t-sim-ns 900 --dt-ns 1 \
  23. --class-window-start-ns 580 --class-window-end-ns 850
  24. """
  25. from __future__ import annotations
  26. import argparse
  27. import csv
  28. import json
  29. import platform
  30. import sys
  31. import random
  32. from dataclasses import dataclass
  33. from pathlib import Path
  34. from typing import Dict, List, Tuple
  35. import matplotlib.pyplot as plt
  36. import numpy as np
  37. import torch
  38. import torch.nn as nn
  39. import torch.nn.functional as F
  40. from sklearn.datasets import load_iris
  41. from sklearn.model_selection import train_test_split
  42. from sklearn.preprocessing import MinMaxScaler
  43. from torch.utils.data import DataLoader, TensorDataset
  44. # -----------------------------------------------------------------------------
  45. # Configuration
  46. # -----------------------------------------------------------------------------
  47. @dataclass
  48. class Config:
  49. # Network and encoding
  50. M: int = 10
  51. N: int = 10
  52. repetitions: int = 2
  53. pulse_spacing_ns: float = 10.0
  54. t_start_ns: float = 500.0
  55. t_sim_ns: float = 900.0
  56. dt_ns: float = 1.0
  57. pulse_sigma_ns: float = 4.0
  58. feature_max: float = 0.1
  59. input_gain: float = 1.0
  60. hidden_drive_scale: float = 0.05
  61. class_window_start_ns: float = 580.0
  62. class_window_end_ns: float = 850.0
  63. # Data and optimization
  64. train_fraction: float = 0.60
  65. val_fraction: float = 0.20
  66. test_fraction: float = 0.20
  67. batch_size: int = 150
  68. epochs: int = 50
  69. lr: float = 0.02
  70. weight_decay: float = 1e-4
  71. seed: int = 7
  72. n_runs: int = 10
  73. print_every: int = 5
  74. output_dir: str = "iris_physical_snn_outputs"
  75. diagnostic_index: int = 0
  76. device: str = "auto"
  77. # Reference lookup source
  78. reference_neuron_code: str = "embedded package lookup tables"
  79. # Physical-neuron parameters from the reference code.
  80. pwr_exc: float = 0.008
  81. W_self: float = 1.88774e9
  82. W_cross: float = 1.57479e9
  83. a_dispersion: float = 4.90868e-6
  84. f_0: float = 1.39422e9
  85. f_drive: float = 1.69e9
  86. k_max: float = 3_842_049.0
  87. decay_fix: float = 0.016722666
  88. decay_prime: float = 0.5
  89. # Numerical options for differentiability/stability.
  90. use_decay_lookup: bool = False
  91. use_hard_eta_cutoff: bool = True
  92. k_softplus_scale: float = 1.0e11
  93. response_clip: float = 1.0
  94. # -----------------------------------------------------------------------------
  95. # Utility functions
  96. # -----------------------------------------------------------------------------
  97. def set_seed(seed: int) -> None:
  98. torch.set_num_threads(1)
  99. random.seed(seed)
  100. np.random.seed(seed)
  101. torch.manual_seed(seed)
  102. torch.cuda.manual_seed_all(seed)
  103. def inv_sigmoid(x: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
  104. x = torch.clamp(x, eps, 1.0 - eps)
  105. return torch.log(x / (1.0 - x))
  106. def get_device(device_arg: str) -> torch.device:
  107. if device_arg == "auto":
  108. return torch.device("cuda" if torch.cuda.is_available() else "cpu")
  109. return torch.device(device_arg)
  110. def load_reference_lookup_tables_from_file(reference_py: str | Path | None = None) -> Dict[str, np.ndarray]:
  111. """Return the lookup tables embedded in :mod:`physical_snn.two_pulse`.
  112. The optional argument is accepted for backward compatibility with the
  113. original standalone scripts. The packaged implementation does not parse
  114. Python source code at runtime.
  115. """
  116. from .two_pulse import _load_embedded_lookup_tables
  117. return {name: values.astype(np.float32) for name, values in _load_embedded_lookup_tables().items()}
  118. def torch_interp1d(x: torch.Tensor, xp: torch.Tensor, fp: torch.Tensor) -> torch.Tensor:
  119. """Differentiable piecewise-linear interpolation matching numpy.interp.
  120. xp and fp are one-dimensional, sorted buffers. x can have any shape.
  121. The interpolation is differentiable with respect to x almost everywhere.
  122. """
  123. x_clamped = torch.clamp(x, min=float(xp[0]), max=float(xp[-1]))
  124. idx_hi = torch.searchsorted(xp, x_clamped.contiguous(), right=False)
  125. idx_hi = torch.clamp(idx_hi, 1, xp.numel() - 1)
  126. idx_lo = idx_hi - 1
  127. x0 = xp[idx_lo]
  128. x1 = xp[idx_hi]
  129. y0 = fp[idx_lo]
  130. y1 = fp[idx_hi]
  131. w = (x_clamped - x0) / torch.clamp(x1 - x0, min=1.0e-30)
  132. return y0 + w * (y1 - y0)
  133. # -----------------------------------------------------------------------------
  134. # Dataset
  135. # -----------------------------------------------------------------------------
  136. def load_and_split_iris(cfg: Config, device: torch.device):
  137. iris = load_iris()
  138. X_raw = iris.data.astype(np.float32)
  139. y = iris.target.astype(np.int64)
  140. scaler = MinMaxScaler(feature_range=(0.0, cfg.feature_max))
  141. X_norm = scaler.fit_transform(X_raw).astype(np.float32)
  142. X_trainval, X_test, y_trainval, y_test, raw_trainval, raw_test = train_test_split(
  143. X_norm,
  144. y,
  145. X_raw,
  146. test_size=cfg.test_fraction,
  147. random_state=cfg.seed,
  148. stratify=y,
  149. )
  150. val_size_within_trainval = cfg.val_fraction / (cfg.train_fraction + cfg.val_fraction)
  151. X_train, X_val, y_train, y_val, raw_train, raw_val = train_test_split(
  152. X_trainval,
  153. y_trainval,
  154. raw_trainval,
  155. test_size=val_size_within_trainval,
  156. random_state=cfg.seed,
  157. stratify=y_trainval,
  158. )
  159. def make_loader(X, yy, shuffle):
  160. ds = TensorDataset(torch.tensor(X, dtype=torch.float32), torch.tensor(yy, dtype=torch.long))
  161. return DataLoader(ds, batch_size=cfg.batch_size, shuffle=shuffle, drop_last=False)
  162. loaders = {
  163. "train": make_loader(X_train, y_train, True),
  164. "val": make_loader(X_val, y_val, False),
  165. "test": make_loader(X_test, y_test, False),
  166. }
  167. arrays = {
  168. "X_train": torch.tensor(X_train, dtype=torch.float32, device=device),
  169. "y_train": torch.tensor(y_train, dtype=torch.long, device=device),
  170. "X_val": torch.tensor(X_val, dtype=torch.float32, device=device),
  171. "y_val": torch.tensor(y_val, dtype=torch.long, device=device),
  172. "X_test": torch.tensor(X_test, dtype=torch.float32, device=device),
  173. "y_test": torch.tensor(y_test, dtype=torch.long, device=device),
  174. "raw_test": raw_test,
  175. "feature_names": iris.feature_names,
  176. "target_names": iris.target_names,
  177. "scaler_data_min": scaler.data_min_,
  178. "scaler_data_max": scaler.data_max_,
  179. }
  180. return loaders, arrays
  181. # -----------------------------------------------------------------------------
  182. # Pulse generation and differentiable physical neuron
  183. # -----------------------------------------------------------------------------
  184. def build_time_axis(cfg: Config, device: torch.device) -> torch.Tensor:
  185. n_steps = int(round(cfg.t_sim_ns / cfg.dt_ns)) + 1
  186. if n_steps < 2:
  187. raise ValueError("Simulation must contain at least two time steps.")
  188. return torch.linspace(0.0, cfg.t_sim_ns, n_steps, device=device)
  189. def pulse_times(cfg: Config) -> List[float]:
  190. times = []
  191. for r in range(cfg.repetitions):
  192. base = cfg.t_start_ns + r * 4 * cfg.pulse_spacing_ns
  193. for j in range(4):
  194. times.append(base + j * cfg.pulse_spacing_ns)
  195. return times
  196. class DifferentiablePhysicalNeuron(nn.Module):
  197. """Batch differentiable Euler solver for the reference physical-neuron ODE."""
  198. def __init__(self, cfg: Config, lookup_tables: Dict[str, np.ndarray]):
  199. super().__init__()
  200. self.cfg = cfg
  201. self.register_buffer("k_lookup", torch.tensor(lookup_tables["k_lookup"], dtype=torch.float32))
  202. self.register_buffer("eta_lookup", torch.tensor(lookup_tables["eta_lookup"], dtype=torch.float32))
  203. self.register_buffer("decay_k", torch.tensor(lookup_tables["decay_k"], dtype=torch.float32))
  204. self.register_buffer("decay_vals", torch.tensor(lookup_tables["decay_vals"], dtype=torch.float32))
  205. def eta_from_k(self, k_dynamic: torch.Tensor) -> torch.Tensor:
  206. eta_interp = torch_interp1d(k_dynamic, self.k_lookup, self.eta_lookup)
  207. if self.cfg.use_hard_eta_cutoff:
  208. # Reference behavior in build_lookup_functions:
  209. # if k < params.k_max: return 1.0; else np.interp(...)
  210. return torch.where(k_dynamic < self.cfg.k_max, torch.ones_like(eta_interp), eta_interp)
  211. return eta_interp
  212. def decay_from_k(self, k_dynamic: torch.Tensor) -> torch.Tensor:
  213. if self.cfg.use_decay_lookup:
  214. return torch_interp1d(k_dynamic, self.decay_k, self.decay_vals)
  215. return torch.full_like(k_dynamic, float(self.cfg.decay_fix))
  216. def forward(self, c_sq_in: torch.Tensor) -> torch.Tensor:
  217. """Simulate neurons.
  218. Parameters
  219. ----------
  220. c_sq_in : tensor, shape [batch, neurons, time]
  221. Time-dependent input intensity for each physical neuron.
  222. Returns
  223. -------
  224. c_sq_out : tensor, shape [batch, neurons, time]
  225. Physical response intensity.
  226. """
  227. if c_sq_in.ndim != 3:
  228. raise ValueError(f"c_sq_in must have shape [batch, neurons, time], got {tuple(c_sq_in.shape)}")
  229. cfg = self.cfg
  230. batch, neurons, steps = c_sq_in.shape
  231. c_prev = torch.zeros((batch, neurons), dtype=c_sq_in.dtype, device=c_sq_in.device)
  232. out: List[torch.Tensor] = []
  233. for t in range(steps):
  234. inp_t = c_sq_in[:, :, t]
  235. k_square = (cfg.f_drive - cfg.f_0 - (cfg.W_cross * inp_t + cfg.W_self * c_prev)) / cfg.a_dispersion
  236. # The reference code uses sqrt(max(k_square, 0)). softplus gives a
  237. # differentiable approximation while retaining the same limiting behavior.
  238. k_dynamic = torch.sqrt(
  239. F.softplus(k_square / cfg.k_softplus_scale) * cfg.k_softplus_scale + 1.0e-12
  240. )
  241. eta_t = self.eta_from_k(k_dynamic)
  242. decay_t = self.decay_from_k(k_dynamic)
  243. dc_dt = eta_t * cfg.pwr_exc - decay_t * c_prev - cfg.decay_prime * c_prev * c_prev
  244. c_next = c_prev + cfg.dt_ns * dc_dt
  245. c_next = torch.clamp(c_next, min=0.0, max=cfg.response_clip)
  246. out.append(c_next)
  247. c_prev = c_next
  248. c_sq_out = torch.stack(out, dim=2)
  249. if not torch.isfinite(c_sq_out).all():
  250. raise FloatingPointError("Physical neuron response became NaN or Inf.")
  251. return c_sq_out
  252. # -----------------------------------------------------------------------------
  253. # Network
  254. # -----------------------------------------------------------------------------
  255. class IrisPhysicalSNN(nn.Module):
  256. """Iris classifier with physical input and hidden layers.
  257. Trainable parameters:
  258. input_weights : effective [M, 4] matrix constrained to (0, 1)
  259. hidden_weights : effective [N, M] matrix constrained to (0, 1)
  260. output_linear : [3, N] linear readout
  261. Hidden input definition:
  262. The complete input-layer response trace c_in_layer_out[:, M, T] is linearly
  263. mixed at every time point with hidden_weights [N, M]:
  264. hidden_drive[b, n, t] = hidden_drive_scale * sum_m W_hidden[n, m] * input_response[b, m, t]
  265. This hidden_drive is then used as c_sq_in(t) for the N hidden physical neurons.
  266. """
  267. def __init__(self, cfg: Config, time_ns: torch.Tensor, lookup_tables: Dict[str, np.ndarray]):
  268. super().__init__()
  269. self.cfg = cfg
  270. self.register_buffer("time_ns", time_ns)
  271. self.physical_neuron = DifferentiablePhysicalNeuron(cfg, lookup_tables)
  272. gen = torch.Generator(device=time_ns.device)
  273. gen.manual_seed(cfg.seed)
  274. input_init = 0.05 + 0.90 * torch.rand((cfg.M, 4), generator=gen, device=time_ns.device)
  275. hidden_init = 0.05 + 0.90 * torch.rand((cfg.N, cfg.M), generator=gen, device=time_ns.device)
  276. self.input_weight_raw = nn.Parameter(inv_sigmoid(input_init))
  277. self.hidden_weight_raw = nn.Parameter(inv_sigmoid(hidden_init))
  278. self.feature_norm = nn.BatchNorm1d(cfg.N, track_running_stats=False)
  279. self.output_linear = nn.Linear(cfg.N, 3)
  280. @property
  281. def input_weights(self) -> torch.Tensor:
  282. return torch.sigmoid(self.input_weight_raw)
  283. @property
  284. def hidden_weights(self) -> torch.Tensor:
  285. return torch.sigmoid(self.hidden_weight_raw)
  286. def build_input_drive(self, x: torch.Tensor) -> Tuple[torch.Tensor, Dict[str, np.ndarray]]:
  287. """Build permuted Gaussian pulse trains for all M input neurons.
  288. x is the normalized Iris feature tensor with shape [batch, 4].
  289. Output has shape [batch, M, time].
  290. """
  291. cfg = self.cfg
  292. batch = x.shape[0]
  293. if x.shape[1] != 4:
  294. raise ValueError(f"Iris input must have 4 features, got {x.shape[1]}")
  295. input_drive = torch.zeros((batch, cfg.M, self.time_ns.numel()), dtype=x.dtype, device=x.device)
  296. W_in = self.input_weights
  297. expected_pulses = 4 * cfg.repetitions
  298. feature_indices_by_neuron: List[List[int]] = []
  299. times_by_neuron: List[List[float]] = []
  300. for m in range(cfg.M):
  301. neuron_feature_order = []
  302. neuron_times = []
  303. pulse_counter = 0
  304. for r in range(cfg.repetitions):
  305. for j in range(4):
  306. feature_idx = (m + j) % 4
  307. t0 = cfg.t_start_ns + r * 4 * cfg.pulse_spacing_ns + j * cfg.pulse_spacing_ns
  308. amp = cfg.input_gain * W_in[m, feature_idx] * x[:, feature_idx]
  309. pulse = torch.exp(-((self.time_ns - t0) ** 2) / (2.0 * cfg.pulse_sigma_ns**2))
  310. input_drive[:, m, :] += amp[:, None] * pulse[None, :]
  311. neuron_feature_order.append(feature_idx)
  312. neuron_times.append(t0)
  313. pulse_counter += 1
  314. if pulse_counter != expected_pulses:
  315. raise ValueError(f"Input neuron {m} received {pulse_counter} pulses; expected {expected_pulses}.")
  316. feature_indices_by_neuron.append(neuron_feature_order)
  317. times_by_neuron.append(neuron_times)
  318. meta = {
  319. "feature_indices_by_neuron": np.asarray(feature_indices_by_neuron, dtype=int),
  320. "times_by_neuron": np.asarray(times_by_neuron, dtype=float),
  321. }
  322. return input_drive, meta
  323. def forward(self, x: torch.Tensor, return_traces: bool = False):
  324. input_drive, pulse_meta = self.build_input_drive(x)
  325. input_response = self.physical_neuron(input_drive)
  326. W_h = self.hidden_weights
  327. hidden_drive = torch.einsum("nm,bmt->bnt", W_h, input_response)
  328. hidden_drive = self.cfg.hidden_drive_scale * hidden_drive
  329. hidden_response = self.physical_neuron(hidden_drive)
  330. win = (self.time_ns >= self.cfg.class_window_start_ns) & (self.time_ns <= self.cfg.class_window_end_ns)
  331. if not bool(win.any()):
  332. raise ValueError("Classification window contains no simulation time points.")
  333. # Integrated hidden response over a fixed classification window.
  334. # Subtract a pre-pulse baseline so the classifier responds to the pulse-induced
  335. # deviation rather than the common steady pump background.
  336. base_win = self.time_ns < self.cfg.t_start_ns
  337. if bool(base_win.any()):
  338. baseline = hidden_response[:, :, base_win].mean(dim=2, keepdim=True)
  339. else:
  340. baseline = torch.zeros_like(hidden_response[:, :, :1])
  341. hidden_delta = hidden_response[:, :, win] - baseline
  342. hidden_features = torch.trapz(hidden_delta, self.time_ns[win], dim=2)
  343. # BatchNorm is useful for the integrated features, but it cannot train with
  344. # a batch of size 1. For single-sample diagnostics, evaluate the sample as
  345. # part of the whole test batch in plot_diagnostic().
  346. logits = self.output_linear(self.feature_norm(hidden_features))
  347. if logits.shape[1] != 3:
  348. raise ValueError(f"Logits must have shape [batch, 3], got {tuple(logits.shape)}")
  349. if return_traces:
  350. return {
  351. "logits": logits,
  352. "input_drive": input_drive,
  353. "input_response": input_response,
  354. "hidden_drive": hidden_drive,
  355. "hidden_response": hidden_response,
  356. "hidden_features": hidden_features,
  357. "pulse_meta": pulse_meta,
  358. }
  359. return logits
  360. # -----------------------------------------------------------------------------
  361. # Training, evaluation, checks
  362. # -----------------------------------------------------------------------------
  363. def run_epoch(model, loader, optimizer, device, train: bool) -> Tuple[float, float]:
  364. model.train(train)
  365. total_loss = 0.0
  366. total_correct = 0
  367. total = 0
  368. for xb, yb in loader:
  369. xb = xb.to(device)
  370. yb = yb.to(device)
  371. if train:
  372. optimizer.zero_grad(set_to_none=True)
  373. with torch.set_grad_enabled(train):
  374. logits = model(xb)
  375. loss = F.cross_entropy(logits, yb)
  376. if train:
  377. loss.backward()
  378. torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=5.0)
  379. optimizer.step()
  380. pred = torch.argmax(logits.detach(), dim=1)
  381. total_loss += float(loss.detach().item()) * xb.shape[0]
  382. total_correct += int((pred == yb).sum().item())
  383. total += int(xb.shape[0])
  384. return total_loss / total, total_correct / total
  385. def evaluate(model, loader, device) -> Tuple[float, float]:
  386. return run_epoch(model, loader, None, device, train=False)
  387. def train_model(model, loaders, cfg: Config, device: torch.device) -> List[Dict[str, float]]:
  388. optimizer = torch.optim.Adam(model.parameters(), lr=cfg.lr, weight_decay=cfg.weight_decay)
  389. history: List[Dict[str, float]] = []
  390. for epoch in range(1, cfg.epochs + 1):
  391. train_loss, train_acc = run_epoch(model, loaders["train"], optimizer, device, train=True)
  392. val_loss, val_acc = evaluate(model, loaders["val"], device)
  393. row = {
  394. "epoch": epoch,
  395. "train_loss": train_loss,
  396. "train_accuracy": train_acc,
  397. "val_loss": val_loss,
  398. "val_accuracy": val_acc,
  399. }
  400. history.append(row)
  401. if epoch == 1 or epoch % cfg.print_every == 0 or epoch == cfg.epochs:
  402. print(
  403. f"Epoch {epoch:4d} | "
  404. f"train loss {train_loss:.4f}, train acc {train_acc:.3f} | "
  405. f"val loss {val_loss:.4f}, val acc {val_acc:.3f}"
  406. )
  407. return history
  408. def consistency_checks(cfg: Config, model: IrisPhysicalSNN, loaders) -> None:
  409. n_features = 4
  410. n_classes = 3
  411. p_times = pulse_times(cfg)
  412. end_pulse = max(p_times) if p_times else cfg.t_start_ns
  413. if cfg.M <= 0 or cfg.N <= 0:
  414. raise ValueError("M and N must be positive.")
  415. if cfg.repetitions <= 0:
  416. raise ValueError("repetitions must be positive.")
  417. if len(p_times) != 4 * cfg.repetitions:
  418. raise ValueError("Pulse sequence does not contain exactly 4*X pulses.")
  419. if cfg.class_window_start_ns >= cfg.class_window_end_ns:
  420. raise ValueError("Classification-window start must be smaller than end.")
  421. if cfg.t_sim_ns <= cfg.class_window_end_ns:
  422. raise ValueError("Simulation time is too short for the classification window.")
  423. if cfg.t_sim_ns <= end_pulse + 5.0 * cfg.pulse_sigma_ns:
  424. raise ValueError("Simulation time is too short to contain all pulses and their response tail.")
  425. if tuple(model.input_weights.shape) != (cfg.M, 4):
  426. raise ValueError("Input encoding matrix has wrong shape.")
  427. if tuple(model.hidden_weights.shape) != (cfg.N, cfg.M):
  428. raise ValueError("Hidden-layer matrix has wrong shape.")
  429. if tuple(model.output_linear.weight.shape) != (3, cfg.N):
  430. raise ValueError("Output linear matrix has wrong shape.")
  431. n_train = len(loaders["train"].dataset)
  432. n_val = len(loaders["val"].dataset)
  433. n_test = len(loaders["test"].dataset)
  434. print("\nConsistency checks")
  435. print("------------------")
  436. print(f"Number of Iris features : {n_features}")
  437. print(f"Input physical neurons M : {cfg.M}")
  438. print(f"Hidden physical neurons N : {cfg.N}")
  439. print(f"Output channels/classes : {n_classes}")
  440. print(f"Feature normalization range : [0.0, {cfg.feature_max}]")
  441. print(f"Number of sequence repetitions X : {cfg.repetitions}")
  442. print(f"Pulses per input neuron : {4 * cfg.repetitions}")
  443. print(f"Pulse spacing : {cfg.pulse_spacing_ns:.3f} ns")
  444. print(f"Encoded sequence start : {cfg.t_start_ns:.3f} ns")
  445. print(f"Encoded sequence last pulse time : {end_pulse:.3f} ns")
  446. print(f"Classification window : [{cfg.class_window_start_ns:.3f}, {cfg.class_window_end_ns:.3f}] ns")
  447. print(f"Simulation time step : {cfg.dt_ns:.3f} ns")
  448. print(f"Simulation end time : {cfg.t_sim_ns:.3f} ns")
  449. print(f"Input encoding matrix shape : {tuple(model.input_weights.shape)} = [M, 4]")
  450. print(f"Hidden-layer matrix shape : {tuple(model.hidden_weights.shape)} = [N, M]")
  451. print(f"Output linear matrix shape : {tuple(model.output_linear.weight.shape)} = [3, N]")
  452. print(f"Training/validation/test split sizes : {n_train}/{n_val}/{n_test}")
  453. print("Physical-neuron implementation : differentiable lookup eta(k) + Euler update")
  454. print(f"Reference neuron code : {cfg.reference_neuron_code}")
  455. print(f"Decay source : {'lookup decay(k)' if cfg.use_decay_lookup else 'fixed decay_fix'}")
  456. print(f"Hard eta cutoff k < k_max -> eta=1 : {cfg.use_hard_eta_cutoff}")
  457. print()
  458. # -----------------------------------------------------------------------------
  459. # Output files
  460. # -----------------------------------------------------------------------------
  461. def save_history(history: List[Dict[str, float]], out_dir: Path, filename: str = "training_history.csv") -> Path:
  462. out_dir.mkdir(parents=True, exist_ok=True)
  463. path = out_dir / filename
  464. with path.open("w", newline="") as f:
  465. writer = csv.DictWriter(f, fieldnames=list(history[0].keys()))
  466. writer.writeheader()
  467. writer.writerows(history)
  468. return path
  469. def save_figure_png_svg(fig: plt.Figure, out_dir: Path, stem: str) -> Tuple[Path, Path]:
  470. """Save one matplotlib figure as both PNG and SVG."""
  471. out_dir.mkdir(parents=True, exist_ok=True)
  472. png_path = out_dir / f"{stem}.png"
  473. svg_path = out_dir / f"{stem}.svg"
  474. fig.savefig(png_path, dpi=300, bbox_inches="tight")
  475. fig.savefig(svg_path, bbox_inches="tight")
  476. return png_path, svg_path
  477. def write_csv(path: Path, columns: List[str], rows: List[List[float]]) -> Path:
  478. path.parent.mkdir(parents=True, exist_ok=True)
  479. with path.open("w", newline="") as f:
  480. writer = csv.writer(f)
  481. writer.writerow(columns)
  482. writer.writerows(rows)
  483. return path
  484. def plot_history(history: List[Dict[str, float]], out_dir: Path) -> Dict[str, Path]:
  485. """Save per-run accuracy/loss plots as PNG+SVG and their source CSV files."""
  486. out_dir.mkdir(parents=True, exist_ok=True)
  487. epochs = [r["epoch"] for r in history]
  488. acc_rows = [
  489. [r["epoch"], r["train_accuracy"], r["val_accuracy"]]
  490. for r in history
  491. ]
  492. acc_csv = write_csv(out_dir / "accuracy_vs_epoch.csv", ["epoch", "train_accuracy", "val_accuracy"], acc_rows)
  493. fig, ax = plt.subplots(figsize=(6.0, 4.0), dpi=160)
  494. ax.plot(epochs, [r["train_accuracy"] for r in history], label="Training accuracy")
  495. ax.plot(epochs, [r["val_accuracy"] for r in history], label="Validation accuracy")
  496. ax.set_xlabel("Epoch")
  497. ax.set_ylabel("Accuracy")
  498. ax.set_title("Iris physical-SNN accuracy")
  499. ax.grid(True, alpha=0.3)
  500. ax.legend(frameon=False)
  501. fig.tight_layout()
  502. acc_png, acc_svg = save_figure_png_svg(fig, out_dir, "accuracy_vs_epoch")
  503. plt.close(fig)
  504. loss_rows = [
  505. [r["epoch"], r["train_loss"], r["val_loss"]]
  506. for r in history
  507. ]
  508. loss_csv = write_csv(out_dir / "loss_vs_epoch.csv", ["epoch", "train_loss", "val_loss"], loss_rows)
  509. fig, ax = plt.subplots(figsize=(6.0, 4.0), dpi=160)
  510. ax.plot(epochs, [r["train_loss"] for r in history], label="Training loss")
  511. ax.plot(epochs, [r["val_loss"] for r in history], label="Validation loss")
  512. ax.set_xlabel("Epoch")
  513. ax.set_ylabel("Cross-entropy loss")
  514. ax.set_title("Iris physical-SNN loss")
  515. ax.grid(True, alpha=0.3)
  516. ax.legend(frameon=False)
  517. fig.tight_layout()
  518. loss_png, loss_svg = save_figure_png_svg(fig, out_dir, "loss_vs_epoch")
  519. plt.close(fig)
  520. return {
  521. "accuracy_png": acc_png,
  522. "accuracy_svg": acc_svg,
  523. "accuracy_csv": acc_csv,
  524. "loss_png": loss_png,
  525. "loss_svg": loss_svg,
  526. "loss_csv": loss_csv,
  527. }
  528. def plot_average_accuracy(all_histories: List[List[Dict[str, float]]], out_dir: Path) -> Dict[str, Path]:
  529. """Save mean +/- std accuracy over repeated runs."""
  530. out_dir.mkdir(parents=True, exist_ok=True)
  531. if not all_histories:
  532. raise ValueError("No histories supplied for averaging.")
  533. n_epochs = len(all_histories[0])
  534. for i, h in enumerate(all_histories):
  535. if len(h) != n_epochs:
  536. raise ValueError(f"Run {i} has {len(h)} epochs, expected {n_epochs}.")
  537. epochs = np.asarray([r["epoch"] for r in all_histories[0]], dtype=float)
  538. train_acc = np.asarray([[r["train_accuracy"] for r in h] for h in all_histories], dtype=float)
  539. val_acc = np.asarray([[r["val_accuracy"] for r in h] for h in all_histories], dtype=float)
  540. train_mean = train_acc.mean(axis=0)
  541. train_std = train_acc.std(axis=0, ddof=1 if len(all_histories) > 1 else 0)
  542. val_mean = val_acc.mean(axis=0)
  543. val_std = val_acc.std(axis=0, ddof=1 if len(all_histories) > 1 else 0)
  544. rows = []
  545. for i, epoch in enumerate(epochs):
  546. rows.append([epoch, train_mean[i], train_std[i], val_mean[i], val_std[i]])
  547. csv_path = write_csv(
  548. out_dir / "average_accuracy_vs_epoch.csv",
  549. ["epoch", "train_accuracy_mean", "train_accuracy_std", "val_accuracy_mean", "val_accuracy_std"],
  550. rows,
  551. )
  552. fig, ax = plt.subplots(figsize=(6.5, 4.2), dpi=160)
  553. ax.plot(epochs, train_mean, label="Training accuracy mean")
  554. ax.fill_between(epochs, train_mean - train_std, train_mean + train_std, alpha=0.25, label="Training ±1 std")
  555. ax.plot(epochs, val_mean, label="Validation accuracy mean")
  556. ax.fill_between(epochs, val_mean - val_std, val_mean + val_std, alpha=0.25, label="Validation ±1 std")
  557. ax.set_xlabel("Epoch")
  558. ax.set_ylabel("Accuracy")
  559. ax.set_title(f"Iris physical-SNN accuracy over {len(all_histories)} runs")
  560. ax.set_ylim(0.0, 1.05)
  561. ax.grid(True, alpha=0.3)
  562. ax.legend(frameon=False)
  563. fig.tight_layout()
  564. png_path, svg_path = save_figure_png_svg(fig, out_dir, "average_accuracy_vs_epoch")
  565. plt.close(fig)
  566. return {"png": png_path, "svg": svg_path, "csv": csv_path}
  567. def plot_diagnostic(model: IrisPhysicalSNN, arrays, cfg: Config, out_dir: Path) -> Dict[str, Path]:
  568. """Save diagnostic input/response plots as PNG+SVG plus source CSV.
  569. The plotted time range starts at the beginning of the first encoded peak.
  570. Spike labels and spike-amplitude text are intentionally omitted to keep the
  571. plot uncluttered. The scaled hidden mean trace is also omitted.
  572. """
  573. model.eval()
  574. out_dir.mkdir(parents=True, exist_ok=True)
  575. idx = int(np.clip(cfg.diagnostic_index, 0, arrays["X_test"].shape[0] - 1))
  576. x_all = arrays["X_test"]
  577. y_all = arrays["y_test"]
  578. y = y_all[idx : idx + 1]
  579. # Use the full test batch so BatchNorm has a meaningful batch for diagnostics.
  580. with torch.no_grad():
  581. traces = model(x_all, return_traces=True)
  582. logits = traces["logits"]
  583. prob = torch.softmax(logits, dim=1)
  584. pred = int(torch.argmax(logits[idx : idx + 1], dim=1).item())
  585. time = model.time_ns.detach().cpu().numpy()
  586. input_drive = traces["input_drive"][idx].detach().cpu().numpy()
  587. input_response = traces["input_response"][idx].detach().cpu().numpy()
  588. output_scores = prob[idx].detach().cpu().numpy()
  589. selected = list(range(min(3, cfg.M)))
  590. plot_start = max(0.0, cfg.t_start_ns - 3.0 * cfg.pulse_sigma_ns)
  591. plot_end = min(cfg.t_sim_ns, cfg.t_start_ns + cfg.repetitions * 4 * cfg.pulse_spacing_ns + 8.0 * cfg.pulse_sigma_ns)
  592. plot_mask = (time >= plot_start) & (time <= plot_end)
  593. if not np.any(plot_mask):
  594. raise ValueError("Diagnostic plotting window contains no time points.")
  595. # CSV source data for the diagnostic plot.
  596. columns = ["time_ns"]
  597. rows_matrix = [time[plot_mask]]
  598. pre = time < cfg.t_start_ns
  599. for m in selected:
  600. columns.append(f"input_pulse_train_neuron_{m + 1}")
  601. rows_matrix.append(input_drive[m, plot_mask])
  602. columns.append(f"raw_physical_response_neuron_{m + 1}")
  603. rows_matrix.append(input_response[m, plot_mask])
  604. if np.any(pre):
  605. delta = input_response[m] - input_response[m, pre].mean()
  606. else:
  607. delta = input_response[m]
  608. columns.append(f"baseline_subtracted_response_neuron_{m + 1}")
  609. rows_matrix.append(delta[plot_mask])
  610. diag_rows = np.column_stack(rows_matrix).tolist()
  611. csv_path = write_csv(out_dir / "diagnostic_input_hidden_output_traces.csv", columns, diag_rows)
  612. fig, axes = plt.subplots(len(selected), 1, figsize=(10.8, 7.0), dpi=150, sharex=True)
  613. if len(selected) == 1:
  614. axes = [axes]
  615. target_names = arrays["target_names"]
  616. fig.suptitle(
  617. f"Diagnostic Iris sample {idx}: true={target_names[int(y.item())]}, "
  618. f"pred={target_names[pred]}, probabilities={np.round(output_scores, 3)}",
  619. y=0.995,
  620. )
  621. for ax, m in zip(axes, selected):
  622. ax.plot(time[plot_mask], input_drive[m, plot_mask], linestyle="--", linewidth=1.2, label=f"input pulse train, neuron {m + 1}")
  623. ax.plot(time[plot_mask], input_response[m, plot_mask], linewidth=1.7, label=f"raw physical response, input neuron {m + 1}")
  624. if np.any(pre):
  625. input_response_delta = input_response[m] - input_response[m, pre].mean()
  626. ax.plot(
  627. time[plot_mask],
  628. input_response_delta[plot_mask],
  629. linewidth=1.2,
  630. alpha=0.85,
  631. label=f"baseline-subtracted response, neuron {m + 1}",
  632. )
  633. for r in range(cfg.repetitions):
  634. for j in range(4):
  635. t0 = cfg.t_start_ns + r * 4 * cfg.pulse_spacing_ns + j * cfg.pulse_spacing_ns
  636. ax.axvline(t0, alpha=0.15, linewidth=0.9)
  637. ax.set_ylabel("Intensity (a.u.)")
  638. ax.grid(True, alpha=0.25)
  639. ax.legend(loc="upper right", fontsize=8, frameon=False)
  640. ax.set_xlim(plot_start, plot_end)
  641. axes[-1].set_xlabel("Time (ns)")
  642. fig.tight_layout(rect=[0, 0, 1, 0.96])
  643. png_path, svg_path = save_figure_png_svg(fig, out_dir, "diagnostic_input_hidden_output_traces")
  644. plt.close(fig)
  645. return {"png": png_path, "svg": svg_path, "csv": csv_path}
  646. def write_plot_readme(out_dir: Path, n_runs: int) -> Path:
  647. """Write a README describing how to reproduce every generated plot from CSV files."""
  648. readme = out_dir / "README_plot_data.md"
  649. text = f"""# Plot data README
  650. This directory contains figures saved as both PNG and SVG, plus CSV files with the data required to reproduce the plots.
  651. ## Repeated-run outputs
  652. The script was configured for `{n_runs}` run(s). Per-run outputs are stored in subdirectories named `run_00`, `run_01`, etc.
  653. Each run directory contains:
  654. - `training_history.csv`: epoch, training loss, training accuracy, validation loss, validation accuracy.
  655. - `accuracy_vs_epoch.csv`: source data for `accuracy_vs_epoch.png` and `accuracy_vs_epoch.svg`.
  656. - `loss_vs_epoch.csv`: source data for `loss_vs_epoch.png` and `loss_vs_epoch.svg`.
  657. - `diagnostic_input_hidden_output_traces.csv`: source data for `diagnostic_input_hidden_output_traces.png` and `diagnostic_input_hidden_output_traces.svg`.
  658. - `trained_model_state_dict.pt`: PyTorch model parameters for that run.
  659. The top-level directory contains:
  660. - `all_runs_summary.csv`: final test loss and test accuracy for each run.
  661. - `average_accuracy_vs_epoch.csv`: mean and standard deviation of training and validation accuracy over runs.
  662. - `average_accuracy_vs_epoch.png` and `average_accuracy_vs_epoch.svg`: repeated-run accuracy summary.
  663. ## Minimal plotting examples
  664. ```python
  665. import pandas as pd
  666. import matplotlib.pyplot as plt
  667. # Per-run accuracy
  668. run = "run_00"
  669. df = pd.read_csv(f"{{run}}/accuracy_vs_epoch.csv")
  670. plt.figure()
  671. plt.plot(df["epoch"], df["train_accuracy"], label="training")
  672. plt.plot(df["epoch"], df["val_accuracy"], label="validation")
  673. plt.xlabel("Epoch")
  674. plt.ylabel("Accuracy")
  675. plt.legend()
  676. plt.tight_layout()
  677. plt.show()
  678. # Average +/- std accuracy over repeated runs
  679. df = pd.read_csv("average_accuracy_vs_epoch.csv")
  680. plt.figure()
  681. plt.plot(df["epoch"], df["train_accuracy_mean"], label="training mean")
  682. plt.fill_between(df["epoch"], df["train_accuracy_mean"] - df["train_accuracy_std"], df["train_accuracy_mean"] + df["train_accuracy_std"], alpha=0.25)
  683. plt.plot(df["epoch"], df["val_accuracy_mean"], label="validation mean")
  684. plt.fill_between(df["epoch"], df["val_accuracy_mean"] - df["val_accuracy_std"], df["val_accuracy_mean"] + df["val_accuracy_std"], alpha=0.25)
  685. plt.xlabel("Epoch")
  686. plt.ylabel("Accuracy")
  687. plt.legend()
  688. plt.tight_layout()
  689. plt.show()
  690. # Diagnostic input traces
  691. df = pd.read_csv("run_00/diagnostic_input_hidden_output_traces.csv")
  692. plt.figure()
  693. plt.plot(df["time_ns"], df["input_pulse_train_neuron_1"], "--", label="input pulse train n1")
  694. plt.plot(df["time_ns"], df["raw_physical_response_neuron_1"], label="raw response n1")
  695. plt.plot(df["time_ns"], df["baseline_subtracted_response_neuron_1"], label="baseline-subtracted n1")
  696. plt.xlabel("Time (ns)")
  697. plt.ylabel("Intensity (a.u.)")
  698. plt.legend()
  699. plt.tight_layout()
  700. plt.show()
  701. ```
  702. """
  703. readme.write_text(text)
  704. return readme
  705. def save_reproducibility_metadata(cfg: Config, out_dir: Path, device: torch.device) -> Path:
  706. """Save the exact configuration and software environment used for a run."""
  707. metadata = {
  708. "configuration": cfg.__dict__,
  709. "python": sys.version,
  710. "platform": platform.platform(),
  711. "numpy": np.__version__,
  712. "torch": torch.__version__,
  713. "scikit_learn": __import__("sklearn").__version__,
  714. "device": str(device),
  715. "cuda_available": torch.cuda.is_available(),
  716. }
  717. path = out_dir / "reproducibility_metadata.json"
  718. path.write_text(json.dumps(metadata, indent=2, sort_keys=True))
  719. return path
  720. # -----------------------------------------------------------------------------
  721. # CLI
  722. # -----------------------------------------------------------------------------
  723. def parse_args() -> Config:
  724. p = argparse.ArgumentParser(description="Train a differentiable physical SNN on the Iris dataset.")
  725. p.add_argument("--M", type=int, default=10)
  726. p.add_argument("--N", type=int, default=10)
  727. p.add_argument("--repetitions", type=int, default=2)
  728. p.add_argument("--epochs", type=int, default=100)
  729. p.add_argument("--n-runs", type=int, default=10, help="Number of independent training runs used for mean/std statistics.")
  730. p.add_argument("--batch-size", type=int, default=150)
  731. p.add_argument("--lr", type=float, default=0.02)
  732. p.add_argument("--weight-decay", type=float, default=1e-4)
  733. p.add_argument("--seed", type=int, default=7)
  734. p.add_argument("--print-every", type=int, default=5)
  735. p.add_argument("--output-dir", type=str, default="iris_physical_snn_outputs")
  736. p.add_argument("--device", type=str, default="auto")
  737. p.add_argument("--reference-neuron-code", type=str, default="embedded", help="Deprecated compatibility option; packaged lookup tables are always used.")
  738. p.add_argument("--t-start-ns", type=float, default=200.0)
  739. p.add_argument("--t-sim-ns", type=float, default=525.0)
  740. p.add_argument("--dt-ns", type=float, default=0.1)
  741. p.add_argument("--pulse-spacing-ns", type=float, default=25.0)
  742. p.add_argument("--pulse-sigma-ns", type=float, default=4.0)
  743. p.add_argument("--feature-max", type=float, default=0.1, help="Upper bound for MinMax feature scaling; default [0, 0.1].")
  744. p.add_argument("--input-gain", type=float, default=1.5, help="Global gain multiplying input_weight * normalized_feature.")
  745. p.add_argument("--hidden-drive-scale", type=float, default=0.05, help="Scale applied after hidden [N,M] mixing to avoid saturation.")
  746. p.add_argument("--class-window-start-ns", type=float, default=420.0)
  747. p.add_argument("--class-window-end-ns", type=float, default=520.0)
  748. p.add_argument("--diagnostic-index", type=int, default=0)
  749. p.add_argument("--pwr-exc", type=float, default=0.008)
  750. p.add_argument("--decay-fix", type=float, default=0.016722666)
  751. p.add_argument("--decay-prime", type=float, default=0.5)
  752. p.add_argument("--use-decay-lookup", action="store_true")
  753. p.add_argument("--no-hard-eta-cutoff", action="store_true")
  754. p.add_argument("--k-softplus-scale", type=float, default=1.0e11)
  755. p.add_argument("--response-clip", type=float, default=1.0)
  756. ns = p.parse_args()
  757. return Config(
  758. M=ns.M,
  759. N=ns.N,
  760. repetitions=ns.repetitions,
  761. epochs=ns.epochs,
  762. n_runs=ns.n_runs,
  763. batch_size=ns.batch_size,
  764. lr=ns.lr,
  765. weight_decay=ns.weight_decay,
  766. seed=ns.seed,
  767. print_every=ns.print_every,
  768. output_dir=ns.output_dir,
  769. device=ns.device,
  770. reference_neuron_code=ns.reference_neuron_code,
  771. t_start_ns=ns.t_start_ns,
  772. t_sim_ns=ns.t_sim_ns,
  773. dt_ns=ns.dt_ns,
  774. pulse_spacing_ns=ns.pulse_spacing_ns,
  775. pulse_sigma_ns=ns.pulse_sigma_ns,
  776. feature_max=ns.feature_max,
  777. input_gain=ns.input_gain,
  778. hidden_drive_scale=ns.hidden_drive_scale,
  779. class_window_start_ns=ns.class_window_start_ns,
  780. class_window_end_ns=ns.class_window_end_ns,
  781. diagnostic_index=ns.diagnostic_index,
  782. pwr_exc=ns.pwr_exc,
  783. decay_fix=ns.decay_fix,
  784. decay_prime=ns.decay_prime,
  785. use_decay_lookup=ns.use_decay_lookup,
  786. use_hard_eta_cutoff=not ns.no_hard_eta_cutoff,
  787. k_softplus_scale=ns.k_softplus_scale,
  788. response_clip=ns.response_clip,
  789. )
  790. def train_one_run(base_cfg: Config, run_index: int, lookup_tables: Dict[str, np.ndarray], device: torch.device, root_out_dir: Path):
  791. """Train/evaluate one seeded run and save all per-run outputs."""
  792. run_seed = base_cfg.seed + run_index
  793. cfg = Config(**{**base_cfg.__dict__, "seed": run_seed})
  794. set_seed(cfg.seed)
  795. run_dir = root_out_dir / f"run_{run_index:02d}"
  796. run_dir.mkdir(parents=True, exist_ok=True)
  797. loaders, arrays = load_and_split_iris(cfg, device)
  798. time_ns = build_time_axis(cfg, device)
  799. model = IrisPhysicalSNN(cfg, time_ns, lookup_tables).to(device)
  800. if run_index == 0:
  801. consistency_checks(cfg, model, loaders)
  802. print(f"\n=== Run {run_index + 1}/{base_cfg.n_runs} | seed={run_seed} | device={device} ===")
  803. history = train_model(model, loaders, cfg, device)
  804. test_loss, test_acc = evaluate(model, loaders["test"], device)
  805. print(f"Run {run_index + 1} final test loss: {test_loss:.4f}")
  806. print(f"Run {run_index + 1} final test accuracy: {test_acc:.4f}")
  807. hist_path = save_history(history, run_dir)
  808. plot_paths = plot_history(history, run_dir)
  809. diag_paths = plot_diagnostic(model, arrays, cfg, run_dir)
  810. weights_path = run_dir / "trained_model_state_dict.pt"
  811. torch.save(model.state_dict(), weights_path)
  812. return {
  813. "run": run_index,
  814. "seed": run_seed,
  815. "history": history,
  816. "test_loss": test_loss,
  817. "test_accuracy": test_acc,
  818. "run_dir": run_dir,
  819. "training_history_csv": hist_path,
  820. "plot_paths": plot_paths,
  821. "diagnostic_paths": diag_paths,
  822. "weights_path": weights_path,
  823. }
  824. def main() -> None:
  825. cfg = parse_args()
  826. if cfg.n_runs <= 0:
  827. raise ValueError("--n-runs must be positive.")
  828. device = get_device(cfg.device)
  829. out_dir = Path(cfg.output_dir).expanduser().resolve()
  830. out_dir.mkdir(parents=True, exist_ok=True)
  831. lookup_tables = load_reference_lookup_tables_from_file()
  832. metadata_path = save_reproducibility_metadata(cfg, out_dir, device)
  833. run_results = []
  834. all_histories = []
  835. for run_index in range(cfg.n_runs):
  836. result = train_one_run(cfg, run_index, lookup_tables, device, out_dir)
  837. run_results.append(result)
  838. all_histories.append(result["history"])
  839. avg_paths = plot_average_accuracy(all_histories, out_dir)
  840. summary_rows = []
  841. for r in run_results:
  842. summary_rows.append([r["run"], r["seed"], r["test_loss"], r["test_accuracy"], str(r["run_dir"])])
  843. summary_csv = write_csv(out_dir / "all_runs_summary.csv", ["run", "seed", "test_loss", "test_accuracy", "run_dir"], summary_rows)
  844. readme_path = write_plot_readme(out_dir, cfg.n_runs)
  845. test_accs = np.asarray([r["test_accuracy"] for r in run_results], dtype=float)
  846. print("\nRepeated-run summary")
  847. print("--------------------")
  848. print(f"Runs : {cfg.n_runs}")
  849. print(f"Test accuracy mean : {test_accs.mean():.4f}")
  850. print(f"Test accuracy std : {test_accs.std(ddof=1 if cfg.n_runs > 1 else 0):.4f}")
  851. print("\nSaved top-level outputs")
  852. print("-----------------------")
  853. print(f"All-runs summary CSV : {summary_csv}")
  854. print(f"Average accuracy PNG : {avg_paths['png']}")
  855. print(f"Average accuracy SVG : {avg_paths['svg']}")
  856. print(f"Average accuracy CSV : {avg_paths['csv']}")
  857. print(f"Plot-data README : {readme_path}")
  858. print(f"Reproducibility metadata : {metadata_path}")
  859. print(f"Per-run outputs directory : {out_dir}")
  860. if __name__ == "__main__":
  861. main()

iris_experiment.py at commit 4ef085b, under MIT · at the source

Overview

  1. Fachbereich Physik and Landesforschungszentrum OPTIMAS, RPTU Kaiserslautern-Landau, Kaiserslautern, Germany
  2. V. G. Baryakhtar Institute of Magnetism of the NAS of Ukraine, Kyiv, Ukraine
  3. School of Physics, Hubei Key Laboratory of Gravitation and Quantum Physics, Institute for Quantum Science and Engineering, Huazhong University of Science and Technology, Wuhan, China
  4. INNOVENT e.V. Technologieentwicklung, Jena, Germany
  5. Department of Electrical and Information Engineering, Politecnico di Bari, Bari, Italy
  6. Department of Mathematical and Computer Sciences, Physical Sciences and Earth Sciences, University of Messina, Messina, Italy
  7. Centre de Nanosciences et de Nanotechnologies, Université Paris-Saclay, Palaiseau, France
Journal: Science advances, volume 12, issue 47, article eaeg1429
Dates: received 2 March 2026; accepted 9 October 2026; published online 20 November 2026; in print November 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI · PMCID PMC13787459
Status: code verified (how the code is found and verified)
Journal subjects: Physical and Materials Sciences, Condensed Matter Physics
Funding: HORIZON EUROPE European Research Council (101042439); Max Planck Graduate Center mit der Johannes Gutenberg-Universität Mainz; European Research Council (101042439); Deutsche Forschungsgemeinschaft (TRR 173-268565370 (Project B01), TRR 173 - 268565370, 271741898); PETASPIN association; National Natural Science Foundation of China (12574118); National Academy of Sciences of Ukraine (0124U000270); NAS of Ukraine (0124U000270)
Citations: not cited yet (Europe PMC); 69 references in the paper

Abstract

Magnonics offers nanometer-scale wave propagation and strong nonlinearities, making it attractive for neuromorphic applications such as artificial neurons. Yet, magnonic elements with interconnections solely within the magnonic system remain challenging, preventing the realization of interconnected magnonic neurons to date. Here, we experimentally demonstrate an all-magnonic neuron that reacts to magnon inputs with thresholded, amplified magnon firing and subsequent self-reset, enabling all-magnonic operation and cascading. Our approach is based on micro-antenna excitation on an ultralow damping garnet with perpendicular magnetic anisotropy, where we exploit the positive magnon frequency shift to realize nonlinear activation. Using Brillouin light scattering spectroscopy, we uncover a transient neuron response with tunable fading memory: A 25% change in pump power results in a three-order-of-magnitude tuning in memory time, which we harness, demonstrating temporal integration of up to 50 magnon pulses. Last, we realize neuron triggering in a cascade of three neurons, highlighting its potential for connected magnonic circuits.

Reproduced under the paper's license (CC BY), from the paper cited above.

Repositories

Its files are read in the Code ↔ Paper reader above, with 6 matches between paragraphs and lines of code.

Zenodo 18657410

License: CC-BY-4.0
State: the link answers, verified on 21 November 2026
Evidence: files inventoried
Size: 1 file
Software Heritage: not checked
Found in: “Data, code, and materials availability:”
Not found: README, license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: NumPy (8 files), pandas (6 files), xarray (5 files), Matplotlib (4 files), PyTorch (1 file), SciPy (1 file)
Availability: 1 check, the latest on 21 November 2026: the link answers (HTTP 200)
  • 21 November 2026: the link answers (HTTP 200)
8 files

Zenodo 21628421

License: MIT
State: the link answers, verified on 21 November 2026
Evidence: files inventoried
Size: 1 file
Software Heritage: not checked
Found in: “Data, code, and materials availability:”
Not found: README, license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: NumPy (3 files), Matplotlib (2 files), PyTorch (2 files), pandas (1 file), scikit-learn (1 file)
Availability: 1 check, the latest on 21 November 2026: the link answers (HTTP 200)
  • 21 November 2026: the link answers (HTTP 200)
8 files

dbreitba/magnonic-neuron-model

License: none: the authors keep all their rights
State: the link answers, verified on 21 November 2026
Evidence: files inventoried
Commit: 9c6b60be5d20294fa8ee7b83a19e3fa1e5e9f824, 16 February 2026
Languages: Python (6), Jupyter (2)
Size: 47 files, 8 scripts
Software Heritage: not archived
Found in: the Zenodo archive record
Holds: environment (pyproject.toml), 2 notebooks
Not found: README, license file, CITATION.cff, tests, continuous integration, documentation
Tools: NumPy (8 files), pandas (6 files), xarray (5 files), Matplotlib (4 files), PyTorch (1 file), SciPy (1 file)
Availability: 1 check, the latest on 21 November 2026: the link answers
  • 21 November 2026: the link answers
8 files

dbreitba/magnonic-snn

License: MIT
State: the link answers, verified on 21 November 2026
Evidence: files inventoried
Commit: 4ef085b2311dd7eaa71a62417729e31a6265cab6, 27 July 2026
Languages: Python (6)
Size: 18 files, 6 scripts
Software Heritage: not archived
Found in: the Zenodo archive record
Holds: README, license file, CITATION.cff, environment (pyproject.toml, requirements-dev.txt, requirements.txt), tests, continuous integration
Not found: documentation
Tools: NumPy (3 files), Matplotlib (2 files), PyTorch (2 files), pandas (1 file), scikit-learn (1 file)
Availability: 1 check, the latest on 21 November 2026: the link answers
  • 21 November 2026: the link answers
8 files

The paper's code and data availability statement is in the Data section.

Tracing map

Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.

What the map holds:

  • 4 repositories of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 28 scripts, each with its path and the digest of its content;
  • 6 matches between paragraphs of the paper and lines of the code (method lexical-v1);
  • neither the text of the paper nor the code itself.

Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.

Data

No dataset and no data link were found in the paper.

Data, code, and materials availability

All data and code needed to evaluate and reproduce the results in the paper are present in the paper and/or the Supplementary Materials. This study did not generate new materials. The codes that support the theoretical modeling and calculations are available on Zenodo at https://doi.org/10.5281/zenodo.18657410. The code for the time-domain network training is available at https://doi.org/10.5281/zenodo.21628421.

Reproduced under the paper's license (CC BY), from the paper cited above.

Versions

The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.

Version 1, 21 November 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 12 authors, 8 funders, 23 references.

Cite

This paper

Breitbach, D., Bechberger, M., Mortada, H., Heinz, B., Verba, R., Wang, Q., Dubs, C., Carpentieri, M., Finocchio, G., Rodrigues, D., Hamadeh, A. A., & Pirro, P. (2026). An all-magnonic neuron with tunable fading memory. Science advances, 12(47), eaeg1429.

BibTeX

@article{breitbach2026all,
author = {Breitbach, David and Bechberger, Moritz and Mortada, Hanadi and Heinz, Björn and Verba, Roman and Wang, Qi and Dubs, Carsten and Carpentieri, Mario and Finocchio, Giovanni and Rodrigues, Davi and Hamadeh, Alexandre Abbass and Pirro, Philipp},
title = {{An all-magnonic neuron with tunable fading memory}},
journal = {Science advances},
year = {2026},
month = nov,
volume = {12},
number = {47},
pages = {eaeg1429},
publisher = {American Association for the Advancement of Science},
issn = {2375-2548},
pmcid = {PMC13787459}
}

RIS

TY - JOUR
AU - Breitbach, David
AU - Bechberger, Moritz
AU - Mortada, Hanadi
AU - Heinz, Björn
AU - Verba, Roman
AU - Wang, Qi
AU - Dubs, Carsten
AU - Carpentieri, Mario
AU - Finocchio, Giovanni
AU - Rodrigues, Davi
AU - Hamadeh, Alexandre Abbass
AU - Pirro, Philipp
TI - An all-magnonic neuron with tunable fading memory
T2 - Science advances
J2 - Sci Adv
PY - 2026
DA - 2026/11/20
VL - 12
IS - 47
SP - eaeg1429
SN - 2375-2548
PB - American Association for the Advancement of Science
LA - en
ER -

CSL-JSON

{
"id": "pmcid:PMC13787459",
"type": "article-journal",
"title": "An all-magnonic neuron with tunable fading memory",
"container-title": "Science advances",
"author": [
{
"family": "Breitbach",
"given": "David"
},
{
"family": "Bechberger",
"given": "Moritz"
},
{
"family": "Mortada",
"given": "Hanadi"
},
{
"family": "Heinz",
"given": "Björn"
},
{
"family": "Verba",
"given": "Roman"
},
{
"family": "Wang",
"given": "Qi"
},
{
"family": "Dubs",
"given": "Carsten"
},
{
"family": "Carpentieri",
"given": "Mario"
},
{
"family": "Finocchio",
"given": "Giovanni"
},
{
"family": "Rodrigues",
"given": "Davi"
},
{
"family": "Hamadeh",
"given": "Alexandre Abbass"
},
{
"family": "Pirro",
"given": "Philipp"
}
],
"container-title-short": "Sci Adv",
"volume": "12",
"issue": "47",
"page": "eaeg1429",
"PMCID": "PMC13787459",
"ISSN": "2375-2548",
"publisher": "American Association for the Advancement of Science",
"language": "en",
"issued": {
"date-parts": [
[
2026,
11,
20
]
]
}
}

The tracing map gets a citation of its own once an author has validated it and it has a DOI.

Similar papers

The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.

[1] doi:10.1126/sciadv.aeg1429 [code]
An all-magnonic neuron with tunable fading memory.
Journal: Science advances
In common: xarray, PyTorch, scikit-learn, 4 other tools, 23 references, 12 authors
[2] doi:10.1038/s41467-024-55220-y [code]
Quantum-limited stochastic optical neural networks operating at a few quanta per activation.
Journal: Nature communications
In common: PyTorch, pandas, Matplotlib, 1 other tool, 4 references
[3] doi:10.1038/s41598-023-43488-x [code]
Adaptive structure evolution and biologically plausible synaptic plasticity for recurrent spiking neural networks.
Journal: Scientific reports
In common: PyTorch, scikit-learn, pandas, 3 other tools, 2 references
[4] doi:10.1016/j.neuron.2023.05.008 [code]
Mouse frontal cortex mediates additive multisensory decisions.
Journal: Neuron
In common: xarray, scikit-learn, pandas, 3 other tools, 1 reference
[5] doi:10.1098/rstb.2024.0461 [code]
Shallow recurrent decoders for neural and behavioural dynamics.
Journal: Philosophical transactions of the Royal Society of London. Series B, Biological sciences
In common: xarray, PyTorch, scikit-learn, 4 other tools
[6] doi:10.1523/eneuro.0362-25.2026 [code]
Similarities between &lt;i&gt;Ciona&lt;/i&gt; Dorsal Motor Ganglion and Vertebrate Cerebellum: Did a Chordate Ancestor Already Show D/V Subdivision within a Hindbrain Precursor?
Journal: eNeuro
In common: xarray, PyTorch, scikit-learn, 4 other tools
[7] doi:10.1038/s41467-026-76098-y [code]
A single computational objective can produce specialization of streams in visual cortex.
Journal: Nature communications
In common: xarray, PyTorch, scikit-learn, 4 other tools
[8] doi:10.7554/elife.110074 [code]
Disentangling cephalopod chromatophores motor units with computer vision.
Journal: eLife
In common: xarray, PyTorch, scikit-learn, 4 other tools
[9] doi:10.1371/journal.pcbi.1014302 [code]
Trial-level sequence modeling reveals hidden dynamics of dual-task interference.
Journal: PLoS computational biology
In common: xarray, PyTorch, scikit-learn, 4 other tools
[10] doi:10.1038/s41467-026-72057-9 [code]
Sex-specific behavioral feedback modulates sensorimotor processing and drives flexible social behavior.
Journal: Nature communications
In common: xarray, PyTorch, scikit-learn, 4 other tools

Contribute

The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.

Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.

Add the badge to the code's README

OSCR: the badge of this paper

If you are an author or a maintainer of this paper's code, you can add this badge. It says what OSCR knows of the paper (its code, its validated tracing map) and links the code to this page. Paste one of these snippets under the README's title. Keep the two marks around it, so that the badge can be replaced in place and is never added twice. OSCR changes nothing in your repository.

Markdown
<!-- oscr-badge:start -->
[![OSCR](https://openscicode.org/badge/repo/zenodo:18657410.svg)](https://openscicode.org/badge/repo/zenodo:18657410)
<!-- oscr-badge:end -->
reStructuredText
.. oscr-badge:start

.. image:: https://openscicode.org/badge/repo/zenodo:18657410.svg
   :target: https://openscicode.org/badge/repo/zenodo:18657410
   :alt: OSCR

.. oscr-badge:end
HTML
<!-- oscr-badge:start -->
<a href="https://openscicode.org/badge/repo/zenodo:18657410"><img src="https://openscicode.org/badge/repo/zenodo:18657410.svg" alt="OSCR"></a>
<!-- oscr-badge:end -->

On GitHub, open the README, choose Edit (the pencil), paste the snippet under the title, then "Commit changes".

If you choose to, you can have the badge kept up to date for you, with oscr badge --write from the command line or with the GitHub Action in your repository's workflows. Every other form and option (a card, AsciiDoc, LaTeX, shields.io) is on the badge page.

Request its removal

To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).

Discussion, reproductions, activity

Discussion: code errors and mismatches between the code and the paper about this paper and its code, from readers and its authors, beside the paper and its tracing map.

Report a mismatch between the code and the paper · Report a code error (signed in)

Reproductions: reports from readers who ran the authors' code and did not get the paper's result, what they ran, with which environment, commit and data.

Report a reproduction failure (signed in)

Versions of its code: the releases of its code tied to a version of this paper (the preprint, the accepted manuscript, the version of record…), each with the tracing map versioned with it.

Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.