An all-magnonic neuron with tunable fading memory.
3 blocks of code here have a permanent identifier (oscr:b:…), listed with the matches below: citable for good, with a page of its own. Select a match and press Cite to copy it. What a block identifier is.
The 6 matches
- [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 · block
oscr:b:6EN5PJ71V3M4P-Z· Report a mismatch - [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 · block
oscr:b:6EN5PJ71V3M4P-Z· Report a mismatch - [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] § 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] § 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 · block
oscr:b:FBK4WYVD759HF-X· Report a mismatch - [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 · block
oscr:b:JQJYEA0YNRX4P-A· 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
- #!/usr/bin/env python3
- """
- Train and evaluate a differentiable time-domain / spiking neural network on Iris.
- This corrected standalone script follows reproduce_two_pulse_correlation_standalone.py
- more directly than the earlier training version:
- 1. It reads the embedded lookup tables from reproduce_two_pulse_correlation_standalone.py.
- 2. It uses a differentiable torch implementation of the reference eta(k) interpolation.
- 3. It keeps the original reference rule eta(k)=1 for k < k_max unless disabled.
- 4. It uses the same Euler response equation:
- dc_sq/dt = eta(k) * pwr_exc - decay(k) * c_sq - decay_prime * c_sq**2
- k = sqrt(max((f - f0 - W_cross*c_sq_in - W_self*c_sq)/a, 0))
- 5. It uses fixed decay_fix=0.016722666 by default, matching the common reference setting.
- Optionally, --use-decay-lookup enables differentiable decay(k) interpolation.
- Install:
- pip install numpy matplotlib scikit-learn torch
- Run, assuming the reference file is in the same folder:
- python train_iris_physical_snn_standalone_corrected.py \
- --reference-neuron-code reproduce_two_pulse_correlation_standalone.py
- Typical run:
- python train_iris_physical_snn_standalone_corrected.py \
- --M 10 --N 10 --repetitions 2 --epochs 100 \
- --t-start-ns 500 --t-sim-ns 900 --dt-ns 1 \
- --class-window-start-ns 580 --class-window-end-ns 850
- """
- from __future__ import annotations
- import argparse
- import csv
- import json
- import platform
- import sys
- import random
- from dataclasses import dataclass
- from pathlib import Path
- from typing import Dict, List, Tuple
- import matplotlib.pyplot as plt
- import numpy as np
- import torch
- import torch.nn as nn
- import torch.nn.functional as F
- from sklearn.datasets import load_iris
- from sklearn.model_selection import train_test_split
- from sklearn.preprocessing import MinMaxScaler
- from torch.utils.data import DataLoader, TensorDataset
- # -----------------------------------------------------------------------------
- # Configuration
- # -----------------------------------------------------------------------------
- @dataclass
- class Config:
- # Network and encoding
- M: int = 10
- N: int = 10
- repetitions: int = 2
- pulse_spacing_ns: float = 10.0
- t_start_ns: float = 500.0
- t_sim_ns: float = 900.0
- dt_ns: float = 1.0
- pulse_sigma_ns: float = 4.0
- feature_max: float = 0.1
- input_gain: float = 1.0
- hidden_drive_scale: float = 0.05
- class_window_start_ns: float = 580.0
- class_window_end_ns: float = 850.0
- # Data and optimization
- train_fraction: float = 0.60
- val_fraction: float = 0.20
- test_fraction: float = 0.20
- batch_size: int = 150
- epochs: int = 50
- lr: float = 0.02
- weight_decay: float = 1e-4
- seed: int = 7
- n_runs: int = 10
- print_every: int = 5
- output_dir: str = "iris_physical_snn_outputs"
- diagnostic_index: int = 0
- device: str = "auto"
- # Reference lookup source
- reference_neuron_code: str = "embedded package lookup tables"
- # Physical-neuron parameters from the reference code.
- pwr_exc: float = 0.008
- W_self: float = 1.88774e9
- W_cross: float = 1.57479e9
- a_dispersion: float = 4.90868e-6
- f_0: float = 1.39422e9
- f_drive: float = 1.69e9
- k_max: float = 3_842_049.0
- decay_fix: float = 0.016722666
- decay_prime: float = 0.5
- # Numerical options for differentiability/stability.
- use_decay_lookup: bool = False
- use_hard_eta_cutoff: bool = True
- k_softplus_scale: float = 1.0e11
- response_clip: float = 1.0
- # -----------------------------------------------------------------------------
- # Utility functions
- # -----------------------------------------------------------------------------
- def set_seed(seed: int) -> None:
- torch.set_num_threads(1)
- random.seed(seed)
- np.random.seed(seed)
- torch.manual_seed(seed)
- torch.cuda.manual_seed_all(seed)
- def inv_sigmoid(x: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
- x = torch.clamp(x, eps, 1.0 - eps)
- return torch.log(x / (1.0 - x))
- def get_device(device_arg: str) -> torch.device:
- if device_arg == "auto":
- return torch.device("cuda" if torch.cuda.is_available() else "cpu")
- return torch.device(device_arg)
- def load_reference_lookup_tables_from_file(reference_py: str | Path | None = None) -> Dict[str, np.ndarray]:
- """Return the lookup tables embedded in :mod:`physical_snn.two_pulse`.
- The optional argument is accepted for backward compatibility with the
- original standalone scripts. The packaged implementation does not parse
- Python source code at runtime.
- """
- from .two_pulse import _load_embedded_lookup_tables
- return {name: values.astype(np.float32) for name, values in _load_embedded_lookup_tables().items()}
- def torch_interp1d(x: torch.Tensor, xp: torch.Tensor, fp: torch.Tensor) -> torch.Tensor:
- """Differentiable piecewise-linear interpolation matching numpy.interp.
- xp and fp are one-dimensional, sorted buffers. x can have any shape.
- The interpolation is differentiable with respect to x almost everywhere.
- """
- x_clamped = torch.clamp(x, min=float(xp[0]), max=float(xp[-1]))
- idx_hi = torch.searchsorted(xp, x_clamped.contiguous(), right=False)
- idx_hi = torch.clamp(idx_hi, 1, xp.numel() - 1)
- idx_lo = idx_hi - 1
- x0 = xp[idx_lo]
- x1 = xp[idx_hi]
- y0 = fp[idx_lo]
- y1 = fp[idx_hi]
- w = (x_clamped - x0) / torch.clamp(x1 - x0, min=1.0e-30)
- return y0 + w * (y1 - y0)
- # -----------------------------------------------------------------------------
- # Dataset
- # -----------------------------------------------------------------------------
- def load_and_split_iris(cfg: Config, device: torch.device):
- iris = load_iris()
- X_raw = iris.data.astype(np.float32)
- y = iris.target.astype(np.int64)
- scaler = MinMaxScaler(feature_range=(0.0, cfg.feature_max))
- X_norm = scaler.fit_transform(X_raw).astype(np.float32)
- X_trainval, X_test, y_trainval, y_test, raw_trainval, raw_test = train_test_split(
- X_norm,
- y,
- X_raw,
- test_size=cfg.test_fraction,
- random_state=cfg.seed,
- stratify=y,
- )
- val_size_within_trainval = cfg.val_fraction / (cfg.train_fraction + cfg.val_fraction)
- X_train, X_val, y_train, y_val, raw_train, raw_val = train_test_split(
- X_trainval,
- y_trainval,
- raw_trainval,
- test_size=val_size_within_trainval,
- random_state=cfg.seed,
- stratify=y_trainval,
- )
- def make_loader(X, yy, shuffle):
- ds = TensorDataset(torch.tensor(X, dtype=torch.float32), torch.tensor(yy, dtype=torch.long))
- return DataLoader(ds, batch_size=cfg.batch_size, shuffle=shuffle, drop_last=False)
- loaders = {
- "train": make_loader(X_train, y_train, True),
- "val": make_loader(X_val, y_val, False),
- "test": make_loader(X_test, y_test, False),
- }
- arrays = {
- "X_train": torch.tensor(X_train, dtype=torch.float32, device=device),
- "y_train": torch.tensor(y_train, dtype=torch.long, device=device),
- "X_val": torch.tensor(X_val, dtype=torch.float32, device=device),
- "y_val": torch.tensor(y_val, dtype=torch.long, device=device),
- "X_test": torch.tensor(X_test, dtype=torch.float32, device=device),
- "y_test": torch.tensor(y_test, dtype=torch.long, device=device),
- "raw_test": raw_test,
- "feature_names": iris.feature_names,
- "target_names": iris.target_names,
- "scaler_data_min": scaler.data_min_,
- "scaler_data_max": scaler.data_max_,
- }
- return loaders, arrays
- # -----------------------------------------------------------------------------
- # Pulse generation and differentiable physical neuron
- # -----------------------------------------------------------------------------
- def build_time_axis(cfg: Config, device: torch.device) -> torch.Tensor:
- n_steps = int(round(cfg.t_sim_ns / cfg.dt_ns)) + 1
- if n_steps < 2:
- raise ValueError("Simulation must contain at least two time steps.")
- return torch.linspace(0.0, cfg.t_sim_ns, n_steps, device=device)
- def pulse_times(cfg: Config) -> List[float]:
- times = []
- for r in range(cfg.repetitions):
- base = cfg.t_start_ns + r * 4 * cfg.pulse_spacing_ns
- for j in range(4):
- times.append(base + j * cfg.pulse_spacing_ns)
- return times
- class DifferentiablePhysicalNeuron(nn.Module):
- """Batch differentiable Euler solver for the reference physical-neuron ODE."""
- def __init__(self, cfg: Config, lookup_tables: Dict[str, np.ndarray]):
- super().__init__()
- self.cfg = cfg
- self.register_buffer("k_lookup", torch.tensor(lookup_tables["k_lookup"], dtype=torch.float32))
- self.register_buffer("eta_lookup", torch.tensor(lookup_tables["eta_lookup"], dtype=torch.float32))
- self.register_buffer("decay_k", torch.tensor(lookup_tables["decay_k"], dtype=torch.float32))
- self.register_buffer("decay_vals", torch.tensor(lookup_tables["decay_vals"], dtype=torch.float32))
- def eta_from_k(self, k_dynamic: torch.Tensor) -> torch.Tensor:
- eta_interp = torch_interp1d(k_dynamic, self.k_lookup, self.eta_lookup)
- if self.cfg.use_hard_eta_cutoff:
- # Reference behavior in build_lookup_functions:
- # if k < params.k_max: return 1.0; else np.interp(...)
- return torch.where(k_dynamic < self.cfg.k_max, torch.ones_like(eta_interp), eta_interp)
- return eta_interp
- def decay_from_k(self, k_dynamic: torch.Tensor) -> torch.Tensor:
- if self.cfg.use_decay_lookup:
- return torch_interp1d(k_dynamic, self.decay_k, self.decay_vals)
- return torch.full_like(k_dynamic, float(self.cfg.decay_fix))
- def forward(self, c_sq_in: torch.Tensor) -> torch.Tensor:
- """Simulate neurons.
- Parameters
- ----------
- c_sq_in : tensor, shape [batch, neurons, time]
- Time-dependent input intensity for each physical neuron.
- Returns
- -------
- c_sq_out : tensor, shape [batch, neurons, time]
- Physical response intensity.
- """
- if c_sq_in.ndim != 3:
- raise ValueError(f"c_sq_in must have shape [batch, neurons, time], got {tuple(c_sq_in.shape)}")
- cfg = self.cfg
- batch, neurons, steps = c_sq_in.shape
- c_prev = torch.zeros((batch, neurons), dtype=c_sq_in.dtype, device=c_sq_in.device)
- out: List[torch.Tensor] = []
- for t in range(steps):
- inp_t = c_sq_in[:, :, t]
- k_square = (cfg.f_drive - cfg.f_0 - (cfg.W_cross * inp_t + cfg.W_self * c_prev)) / cfg.a_dispersion
- # The reference code uses sqrt(max(k_square, 0)). softplus gives a
- # differentiable approximation while retaining the same limiting behavior.
- k_dynamic = torch.sqrt(
- F.softplus(k_square / cfg.k_softplus_scale) * cfg.k_softplus_scale + 1.0e-12
- )
- eta_t = self.eta_from_k(k_dynamic)
- decay_t = self.decay_from_k(k_dynamic)
- dc_dt = eta_t * cfg.pwr_exc - decay_t * c_prev - cfg.decay_prime * c_prev * c_prev
- c_next = c_prev + cfg.dt_ns * dc_dt
- c_next = torch.clamp(c_next, min=0.0, max=cfg.response_clip)
- out.append(c_next)
- c_prev = c_next
- c_sq_out = torch.stack(out, dim=2)
- if not torch.isfinite(c_sq_out).all():
- raise FloatingPointError("Physical neuron response became NaN or Inf.")
- return c_sq_out
- # -----------------------------------------------------------------------------
- # Network
- # -----------------------------------------------------------------------------
- class IrisPhysicalSNN(nn.Module):
- """Iris classifier with physical input and hidden layers.
- Trainable parameters:
- input_weights : effective [M, 4] matrix constrained to (0, 1)
- hidden_weights : effective [N, M] matrix constrained to (0, 1)
- output_linear : [3, N] linear readout
- Hidden input definition:
- The complete input-layer response trace c_in_layer_out[:, M, T] is linearly
- mixed at every time point with hidden_weights [N, M]:
- hidden_drive[b, n, t] = hidden_drive_scale * sum_m W_hidden[n, m] * input_response[b, m, t]
- This hidden_drive is then used as c_sq_in(t) for the N hidden physical neurons.
- """
- def __init__(self, cfg: Config, time_ns: torch.Tensor, lookup_tables: Dict[str, np.ndarray]):
- super().__init__()
- self.cfg = cfg
- self.register_buffer("time_ns", time_ns)
- self.physical_neuron = DifferentiablePhysicalNeuron(cfg, lookup_tables)
- gen = torch.Generator(device=time_ns.device)
- gen.manual_seed(cfg.seed)
- input_init = 0.05 + 0.90 * torch.rand((cfg.M, 4), generator=gen, device=time_ns.device)
- hidden_init = 0.05 + 0.90 * torch.rand((cfg.N, cfg.M), generator=gen, device=time_ns.device)
- self.input_weight_raw = nn.Parameter(inv_sigmoid(input_init))
- self.hidden_weight_raw = nn.Parameter(inv_sigmoid(hidden_init))
- self.feature_norm = nn.BatchNorm1d(cfg.N, track_running_stats=False)
- self.output_linear = nn.Linear(cfg.N, 3)
- @property
- def input_weights(self) -> torch.Tensor:
- return torch.sigmoid(self.input_weight_raw)
- @property
- def hidden_weights(self) -> torch.Tensor:
- return torch.sigmoid(self.hidden_weight_raw)
- def build_input_drive(self, x: torch.Tensor) -> Tuple[torch.Tensor, Dict[str, np.ndarray]]:
- """Build permuted Gaussian pulse trains for all M input neurons.
- x is the normalized Iris feature tensor with shape [batch, 4].
- Output has shape [batch, M, time].
- """
- cfg = self.cfg
- batch = x.shape[0]
- if x.shape[1] != 4:
- raise ValueError(f"Iris input must have 4 features, got {x.shape[1]}")
- input_drive = torch.zeros((batch, cfg.M, self.time_ns.numel()), dtype=x.dtype, device=x.device)
- W_in = self.input_weights
- expected_pulses = 4 * cfg.repetitions
- feature_indices_by_neuron: List[List[int]] = []
- times_by_neuron: List[List[float]] = []
- for m in range(cfg.M):
- neuron_feature_order = []
- neuron_times = []
- pulse_counter = 0
- for r in range(cfg.repetitions):
- for j in range(4):
- feature_idx = (m + j) % 4
- t0 = cfg.t_start_ns + r * 4 * cfg.pulse_spacing_ns + j * cfg.pulse_spacing_ns
- amp = cfg.input_gain * W_in[m, feature_idx] * x[:, feature_idx]
- pulse = torch.exp(-((self.time_ns - t0) ** 2) / (2.0 * cfg.pulse_sigma_ns**2))
- input_drive[:, m, :] += amp[:, None] * pulse[None, :]
- neuron_feature_order.append(feature_idx)
- neuron_times.append(t0)
- pulse_counter += 1
- if pulse_counter != expected_pulses:
- raise ValueError(f"Input neuron {m} received {pulse_counter} pulses; expected {expected_pulses}.")
- feature_indices_by_neuron.append(neuron_feature_order)
- times_by_neuron.append(neuron_times)
- meta = {
- "feature_indices_by_neuron": np.asarray(feature_indices_by_neuron, dtype=int),
- "times_by_neuron": np.asarray(times_by_neuron, dtype=float),
- }
- return input_drive, meta
- def forward(self, x: torch.Tensor, return_traces: bool = False):
- input_drive, pulse_meta = self.build_input_drive(x)
- input_response = self.physical_neuron(input_drive)
- W_h = self.hidden_weights
- hidden_drive = torch.einsum("nm,bmt->bnt", W_h, input_response)
- hidden_drive = self.cfg.hidden_drive_scale * hidden_drive
- hidden_response = self.physical_neuron(hidden_drive)
- win = (self.time_ns >= self.cfg.class_window_start_ns) & (self.time_ns <= self.cfg.class_window_end_ns)
- if not bool(win.any()):
- raise ValueError("Classification window contains no simulation time points.")
- # Integrated hidden response over a fixed classification window.
- # Subtract a pre-pulse baseline so the classifier responds to the pulse-induced
- # deviation rather than the common steady pump background.
- base_win = self.time_ns < self.cfg.t_start_ns
- if bool(base_win.any()):
- baseline = hidden_response[:, :, base_win].mean(dim=2, keepdim=True)
- else:
- baseline = torch.zeros_like(hidden_response[:, :, :1])
- hidden_delta = hidden_response[:, :, win] - baseline
- hidden_features = torch.trapz(hidden_delta, self.time_ns[win], dim=2)
- # BatchNorm is useful for the integrated features, but it cannot train with
- # a batch of size 1. For single-sample diagnostics, evaluate the sample as
- # part of the whole test batch in plot_diagnostic().
- logits = self.output_linear(self.feature_norm(hidden_features))
- if logits.shape[1] != 3:
- raise ValueError(f"Logits must have shape [batch, 3], got {tuple(logits.shape)}")
- if return_traces:
- return {
- "logits": logits,
- "input_drive": input_drive,
- "input_response": input_response,
- "hidden_drive": hidden_drive,
- "hidden_response": hidden_response,
- "hidden_features": hidden_features,
- "pulse_meta": pulse_meta,
- }
- return logits
- # -----------------------------------------------------------------------------
- # Training, evaluation, checks
- # -----------------------------------------------------------------------------
- def run_epoch(model, loader, optimizer, device, train: bool) -> Tuple[float, float]:
- model.train(train)
- total_loss = 0.0
- total_correct = 0
- total = 0
- for xb, yb in loader:
- xb = xb.to(device)
- yb = yb.to(device)
- if train:
- optimizer.zero_grad(set_to_none=True)
- with torch.set_grad_enabled(train):
- logits = model(xb)
- loss = F.cross_entropy(logits, yb)
- if train:
- loss.backward()
- torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=5.0)
- optimizer.step()
- pred = torch.argmax(logits.detach(), dim=1)
- total_loss += float(loss.detach().item()) * xb.shape[0]
- total_correct += int((pred == yb).sum().item())
- total += int(xb.shape[0])
- return total_loss / total, total_correct / total
- def evaluate(model, loader, device) -> Tuple[float, float]:
- return run_epoch(model, loader, None, device, train=False)
- def train_model(model, loaders, cfg: Config, device: torch.device) -> List[Dict[str, float]]:
- optimizer = torch.optim.Adam(model.parameters(), lr=cfg.lr, weight_decay=cfg.weight_decay)
- history: List[Dict[str, float]] = []
- for epoch in range(1, cfg.epochs + 1):
- train_loss, train_acc = run_epoch(model, loaders["train"], optimizer, device, train=True)
- val_loss, val_acc = evaluate(model, loaders["val"], device)
- row = {
- "epoch": epoch,
- "train_loss": train_loss,
- "train_accuracy": train_acc,
- "val_loss": val_loss,
- "val_accuracy": val_acc,
- }
- history.append(row)
- if epoch == 1 or epoch % cfg.print_every == 0 or epoch == cfg.epochs:
- print(
- f"Epoch {epoch:4d} | "
- f"train loss {train_loss:.4f}, train acc {train_acc:.3f} | "
- f"val loss {val_loss:.4f}, val acc {val_acc:.3f}"
- )
- return history
- def consistency_checks(cfg: Config, model: IrisPhysicalSNN, loaders) -> None:
- n_features = 4
- n_classes = 3
- p_times = pulse_times(cfg)
- end_pulse = max(p_times) if p_times else cfg.t_start_ns
- if cfg.M <= 0 or cfg.N <= 0:
- raise ValueError("M and N must be positive.")
- if cfg.repetitions <= 0:
- raise ValueError("repetitions must be positive.")
- if len(p_times) != 4 * cfg.repetitions:
- raise ValueError("Pulse sequence does not contain exactly 4*X pulses.")
- if cfg.class_window_start_ns >= cfg.class_window_end_ns:
- raise ValueError("Classification-window start must be smaller than end.")
- if cfg.t_sim_ns <= cfg.class_window_end_ns:
- raise ValueError("Simulation time is too short for the classification window.")
- if cfg.t_sim_ns <= end_pulse + 5.0 * cfg.pulse_sigma_ns:
- raise ValueError("Simulation time is too short to contain all pulses and their response tail.")
- if tuple(model.input_weights.shape) != (cfg.M, 4):
- raise ValueError("Input encoding matrix has wrong shape.")
- if tuple(model.hidden_weights.shape) != (cfg.N, cfg.M):
- raise ValueError("Hidden-layer matrix has wrong shape.")
- if tuple(model.output_linear.weight.shape) != (3, cfg.N):
- raise ValueError("Output linear matrix has wrong shape.")
- n_train = len(loaders["train"].dataset)
- n_val = len(loaders["val"].dataset)
- n_test = len(loaders["test"].dataset)
- print("\nConsistency checks")
- print("------------------")
- print(f"Number of Iris features : {n_features}")
- print(f"Input physical neurons M : {cfg.M}")
- print(f"Hidden physical neurons N : {cfg.N}")
- print(f"Output channels/classes : {n_classes}")
- print(f"Feature normalization range : [0.0, {cfg.feature_max}]")
- print(f"Number of sequence repetitions X : {cfg.repetitions}")
- print(f"Pulses per input neuron : {4 * cfg.repetitions}")
- print(f"Pulse spacing : {cfg.pulse_spacing_ns:.3f} ns")
- print(f"Encoded sequence start : {cfg.t_start_ns:.3f} ns")
- print(f"Encoded sequence last pulse time : {end_pulse:.3f} ns")
- print(f"Classification window : [{cfg.class_window_start_ns:.3f}, {cfg.class_window_end_ns:.3f}] ns")
- print(f"Simulation time step : {cfg.dt_ns:.3f} ns")
- print(f"Simulation end time : {cfg.t_sim_ns:.3f} ns")
- print(f"Input encoding matrix shape : {tuple(model.input_weights.shape)} = [M, 4]")
- print(f"Hidden-layer matrix shape : {tuple(model.hidden_weights.shape)} = [N, M]")
- print(f"Output linear matrix shape : {tuple(model.output_linear.weight.shape)} = [3, N]")
- print(f"Training/validation/test split sizes : {n_train}/{n_val}/{n_test}")
- print("Physical-neuron implementation : differentiable lookup eta(k) + Euler update")
- print(f"Reference neuron code : {cfg.reference_neuron_code}")
- print(f"Decay source : {'lookup decay(k)' if cfg.use_decay_lookup else 'fixed decay_fix'}")
- print(f"Hard eta cutoff k < k_max -> eta=1 : {cfg.use_hard_eta_cutoff}")
- print()
- # -----------------------------------------------------------------------------
- # Output files
- # -----------------------------------------------------------------------------
- def save_history(history: List[Dict[str, float]], out_dir: Path, filename: str = "training_history.csv") -> Path:
- out_dir.mkdir(parents=True, exist_ok=True)
- path = out_dir / filename
- with path.open("w", newline="") as f:
- writer = csv.DictWriter(f, fieldnames=list(history[0].keys()))
- writer.writeheader()
- writer.writerows(history)
- return path
- def save_figure_png_svg(fig: plt.Figure, out_dir: Path, stem: str) -> Tuple[Path, Path]:
- """Save one matplotlib figure as both PNG and SVG."""
- out_dir.mkdir(parents=True, exist_ok=True)
- png_path = out_dir / f"{stem}.png"
- svg_path = out_dir / f"{stem}.svg"
- fig.savefig(png_path, dpi=300, bbox_inches="tight")
- fig.savefig(svg_path, bbox_inches="tight")
- return png_path, svg_path
- def write_csv(path: Path, columns: List[str], rows: List[List[float]]) -> Path:
- path.parent.mkdir(parents=True, exist_ok=True)
- with path.open("w", newline="") as f:
- writer = csv.writer(f)
- writer.writerow(columns)
- writer.writerows(rows)
- return path
- def plot_history(history: List[Dict[str, float]], out_dir: Path) -> Dict[str, Path]:
- """Save per-run accuracy/loss plots as PNG+SVG and their source CSV files."""
- out_dir.mkdir(parents=True, exist_ok=True)
- epochs = [r["epoch"] for r in history]
- acc_rows = [
- [r["epoch"], r["train_accuracy"], r["val_accuracy"]]
- for r in history
- ]
- acc_csv = write_csv(out_dir / "accuracy_vs_epoch.csv", ["epoch", "train_accuracy", "val_accuracy"], acc_rows)
- fig, ax = plt.subplots(figsize=(6.0, 4.0), dpi=160)
- ax.plot(epochs, [r["train_accuracy"] for r in history], label="Training accuracy")
- ax.plot(epochs, [r["val_accuracy"] for r in history], label="Validation accuracy")
- ax.set_xlabel("Epoch")
- ax.set_ylabel("Accuracy")
- ax.set_title("Iris physical-SNN accuracy")
- ax.grid(True, alpha=0.3)
- ax.legend(frameon=False)
- fig.tight_layout()
- acc_png, acc_svg = save_figure_png_svg(fig, out_dir, "accuracy_vs_epoch")
- plt.close(fig)
- loss_rows = [
- [r["epoch"], r["train_loss"], r["val_loss"]]
- for r in history
- ]
- loss_csv = write_csv(out_dir / "loss_vs_epoch.csv", ["epoch", "train_loss", "val_loss"], loss_rows)
- fig, ax = plt.subplots(figsize=(6.0, 4.0), dpi=160)
- ax.plot(epochs, [r["train_loss"] for r in history], label="Training loss")
- ax.plot(epochs, [r["val_loss"] for r in history], label="Validation loss")
- ax.set_xlabel("Epoch")
- ax.set_ylabel("Cross-entropy loss")
- ax.set_title("Iris physical-SNN loss")
- ax.grid(True, alpha=0.3)
- ax.legend(frameon=False)
- fig.tight_layout()
- loss_png, loss_svg = save_figure_png_svg(fig, out_dir, "loss_vs_epoch")
- plt.close(fig)
- return {
- "accuracy_png": acc_png,
- "accuracy_svg": acc_svg,
- "accuracy_csv": acc_csv,
- "loss_png": loss_png,
- "loss_svg": loss_svg,
- "loss_csv": loss_csv,
- }
- def plot_average_accuracy(all_histories: List[List[Dict[str, float]]], out_dir: Path) -> Dict[str, Path]:
- """Save mean +/- std accuracy over repeated runs."""
- out_dir.mkdir(parents=True, exist_ok=True)
- if not all_histories:
- raise ValueError("No histories supplied for averaging.")
- n_epochs = len(all_histories[0])
- for i, h in enumerate(all_histories):
- if len(h) != n_epochs:
- raise ValueError(f"Run {i} has {len(h)} epochs, expected {n_epochs}.")
- epochs = np.asarray([r["epoch"] for r in all_histories[0]], dtype=float)
- train_acc = np.asarray([[r["train_accuracy"] for r in h] for h in all_histories], dtype=float)
- val_acc = np.asarray([[r["val_accuracy"] for r in h] for h in all_histories], dtype=float)
- train_mean = train_acc.mean(axis=0)
- train_std = train_acc.std(axis=0, ddof=1 if len(all_histories) > 1 else 0)
- val_mean = val_acc.mean(axis=0)
- val_std = val_acc.std(axis=0, ddof=1 if len(all_histories) > 1 else 0)
- rows = []
- for i, epoch in enumerate(epochs):
- rows.append([epoch, train_mean[i], train_std[i], val_mean[i], val_std[i]])
- csv_path = write_csv(
- out_dir / "average_accuracy_vs_epoch.csv",
- ["epoch", "train_accuracy_mean", "train_accuracy_std", "val_accuracy_mean", "val_accuracy_std"],
- rows,
- )
- fig, ax = plt.subplots(figsize=(6.5, 4.2), dpi=160)
- ax.plot(epochs, train_mean, label="Training accuracy mean")
- ax.fill_between(epochs, train_mean - train_std, train_mean + train_std, alpha=0.25, label="Training ±1 std")
- ax.plot(epochs, val_mean, label="Validation accuracy mean")
- ax.fill_between(epochs, val_mean - val_std, val_mean + val_std, alpha=0.25, label="Validation ±1 std")
- ax.set_xlabel("Epoch")
- ax.set_ylabel("Accuracy")
- ax.set_title(f"Iris physical-SNN accuracy over {len(all_histories)} runs")
- ax.set_ylim(0.0, 1.05)
- ax.grid(True, alpha=0.3)
- ax.legend(frameon=False)
- fig.tight_layout()
- png_path, svg_path = save_figure_png_svg(fig, out_dir, "average_accuracy_vs_epoch")
- plt.close(fig)
- return {"png": png_path, "svg": svg_path, "csv": csv_path}
- def plot_diagnostic(model: IrisPhysicalSNN, arrays, cfg: Config, out_dir: Path) -> Dict[str, Path]:
- """Save diagnostic input/response plots as PNG+SVG plus source CSV.
- The plotted time range starts at the beginning of the first encoded peak.
- Spike labels and spike-amplitude text are intentionally omitted to keep the
- plot uncluttered. The scaled hidden mean trace is also omitted.
- """
- model.eval()
- out_dir.mkdir(parents=True, exist_ok=True)
- idx = int(np.clip(cfg.diagnostic_index, 0, arrays["X_test"].shape[0] - 1))
- x_all = arrays["X_test"]
- y_all = arrays["y_test"]
- y = y_all[idx : idx + 1]
- # Use the full test batch so BatchNorm has a meaningful batch for diagnostics.
- with torch.no_grad():
- traces = model(x_all, return_traces=True)
- logits = traces["logits"]
- prob = torch.softmax(logits, dim=1)
- pred = int(torch.argmax(logits[idx : idx + 1], dim=1).item())
- time = model.time_ns.detach().cpu().numpy()
- input_drive = traces["input_drive"][idx].detach().cpu().numpy()
- input_response = traces["input_response"][idx].detach().cpu().numpy()
- output_scores = prob[idx].detach().cpu().numpy()
- selected = list(range(min(3, cfg.M)))
- plot_start = max(0.0, cfg.t_start_ns - 3.0 * cfg.pulse_sigma_ns)
- plot_end = min(cfg.t_sim_ns, cfg.t_start_ns + cfg.repetitions * 4 * cfg.pulse_spacing_ns + 8.0 * cfg.pulse_sigma_ns)
- plot_mask = (time >= plot_start) & (time <= plot_end)
- if not np.any(plot_mask):
- raise ValueError("Diagnostic plotting window contains no time points.")
- # CSV source data for the diagnostic plot.
- columns = ["time_ns"]
- rows_matrix = [time[plot_mask]]
- pre = time < cfg.t_start_ns
- for m in selected:
- columns.append(f"input_pulse_train_neuron_{m + 1}")
- rows_matrix.append(input_drive[m, plot_mask])
- columns.append(f"raw_physical_response_neuron_{m + 1}")
- rows_matrix.append(input_response[m, plot_mask])
- if np.any(pre):
- delta = input_response[m] - input_response[m, pre].mean()
- else:
- delta = input_response[m]
- columns.append(f"baseline_subtracted_response_neuron_{m + 1}")
- rows_matrix.append(delta[plot_mask])
- diag_rows = np.column_stack(rows_matrix).tolist()
- csv_path = write_csv(out_dir / "diagnostic_input_hidden_output_traces.csv", columns, diag_rows)
- fig, axes = plt.subplots(len(selected), 1, figsize=(10.8, 7.0), dpi=150, sharex=True)
- if len(selected) == 1:
- axes = [axes]
- target_names = arrays["target_names"]
- fig.suptitle(
- f"Diagnostic Iris sample {idx}: true={target_names[int(y.item())]}, "
- f"pred={target_names[pred]}, probabilities={np.round(output_scores, 3)}",
- y=0.995,
- )
- for ax, m in zip(axes, selected):
- ax.plot(time[plot_mask], input_drive[m, plot_mask], linestyle="--", linewidth=1.2, label=f"input pulse train, neuron {m + 1}")
- ax.plot(time[plot_mask], input_response[m, plot_mask], linewidth=1.7, label=f"raw physical response, input neuron {m + 1}")
- if np.any(pre):
- input_response_delta = input_response[m] - input_response[m, pre].mean()
- ax.plot(
- time[plot_mask],
- input_response_delta[plot_mask],
- linewidth=1.2,
- alpha=0.85,
- label=f"baseline-subtracted response, neuron {m + 1}",
- )
- for r in range(cfg.repetitions):
- for j in range(4):
- t0 = cfg.t_start_ns + r * 4 * cfg.pulse_spacing_ns + j * cfg.pulse_spacing_ns
- ax.axvline(t0, alpha=0.15, linewidth=0.9)
- ax.set_ylabel("Intensity (a.u.)")
- ax.grid(True, alpha=0.25)
- ax.legend(loc="upper right", fontsize=8, frameon=False)
- ax.set_xlim(plot_start, plot_end)
- axes[-1].set_xlabel("Time (ns)")
- fig.tight_layout(rect=[0, 0, 1, 0.96])
- png_path, svg_path = save_figure_png_svg(fig, out_dir, "diagnostic_input_hidden_output_traces")
- plt.close(fig)
- return {"png": png_path, "svg": svg_path, "csv": csv_path}
- def write_plot_readme(out_dir: Path, n_runs: int) -> Path:
- """Write a README describing how to reproduce every generated plot from CSV files."""
- readme = out_dir / "README_plot_data.md"
- text = f"""# Plot data README
- This directory contains figures saved as both PNG and SVG, plus CSV files with the data required to reproduce the plots.
- ## Repeated-run outputs
- The script was configured for `{n_runs}` run(s). Per-run outputs are stored in subdirectories named `run_00`, `run_01`, etc.
- Each run directory contains:
- - `training_history.csv`: epoch, training loss, training accuracy, validation loss, validation accuracy.
- - `accuracy_vs_epoch.csv`: source data for `accuracy_vs_epoch.png` and `accuracy_vs_epoch.svg`.
- - `loss_vs_epoch.csv`: source data for `loss_vs_epoch.png` and `loss_vs_epoch.svg`.
- - `diagnostic_input_hidden_output_traces.csv`: source data for `diagnostic_input_hidden_output_traces.png` and `diagnostic_input_hidden_output_traces.svg`.
- - `trained_model_state_dict.pt`: PyTorch model parameters for that run.
- The top-level directory contains:
- - `all_runs_summary.csv`: final test loss and test accuracy for each run.
- - `average_accuracy_vs_epoch.csv`: mean and standard deviation of training and validation accuracy over runs.
- - `average_accuracy_vs_epoch.png` and `average_accuracy_vs_epoch.svg`: repeated-run accuracy summary.
- ## Minimal plotting examples
- ```python
- import pandas as pd
- import matplotlib.pyplot as plt
- # Per-run accuracy
- run = "run_00"
- df = pd.read_csv(f"{{run}}/accuracy_vs_epoch.csv")
- plt.figure()
- plt.plot(df["epoch"], df["train_accuracy"], label="training")
- plt.plot(df["epoch"], df["val_accuracy"], label="validation")
- plt.xlabel("Epoch")
- plt.ylabel("Accuracy")
- plt.legend()
- plt.tight_layout()
- plt.show()
- # Average +/- std accuracy over repeated runs
- df = pd.read_csv("average_accuracy_vs_epoch.csv")
- plt.figure()
- plt.plot(df["epoch"], df["train_accuracy_mean"], label="training mean")
- plt.fill_between(df["epoch"], df["train_accuracy_mean"] - df["train_accuracy_std"], df["train_accuracy_mean"] + df["train_accuracy_std"], alpha=0.25)
- plt.plot(df["epoch"], df["val_accuracy_mean"], label="validation mean")
- plt.fill_between(df["epoch"], df["val_accuracy_mean"] - df["val_accuracy_std"], df["val_accuracy_mean"] + df["val_accuracy_std"], alpha=0.25)
- plt.xlabel("Epoch")
- plt.ylabel("Accuracy")
- plt.legend()
- plt.tight_layout()
- plt.show()
- # Diagnostic input traces
- df = pd.read_csv("run_00/diagnostic_input_hidden_output_traces.csv")
- plt.figure()
- plt.plot(df["time_ns"], df["input_pulse_train_neuron_1"], "--", label="input pulse train n1")
- plt.plot(df["time_ns"], df["raw_physical_response_neuron_1"], label="raw response n1")
- plt.plot(df["time_ns"], df["baseline_subtracted_response_neuron_1"], label="baseline-subtracted n1")
- plt.xlabel("Time (ns)")
- plt.ylabel("Intensity (a.u.)")
- plt.legend()
- plt.tight_layout()
- plt.show()
- ```
- """
- readme.write_text(text)
- return readme
- def save_reproducibility_metadata(cfg: Config, out_dir: Path, device: torch.device) -> Path:
- """Save the exact configuration and software environment used for a run."""
- metadata = {
- "configuration": cfg.__dict__,
- "python": sys.version,
- "platform": platform.platform(),
- "numpy": np.__version__,
- "torch": torch.__version__,
- "scikit_learn": __import__("sklearn").__version__,
- "device": str(device),
- "cuda_available": torch.cuda.is_available(),
- }
- path = out_dir / "reproducibility_metadata.json"
- path.write_text(json.dumps(metadata, indent=2, sort_keys=True))
- return path
- # -----------------------------------------------------------------------------
- # CLI
- # -----------------------------------------------------------------------------
- def parse_args() -> Config:
- p = argparse.ArgumentParser(description="Train a differentiable physical SNN on the Iris dataset.")
- p.add_argument("--M", type=int, default=10)
- p.add_argument("--N", type=int, default=10)
- p.add_argument("--repetitions", type=int, default=2)
- p.add_argument("--epochs", type=int, default=100)
- p.add_argument("--n-runs", type=int, default=10, help="Number of independent training runs used for mean/std statistics.")
- p.add_argument("--batch-size", type=int, default=150)
- p.add_argument("--lr", type=float, default=0.02)
- p.add_argument("--weight-decay", type=float, default=1e-4)
- p.add_argument("--seed", type=int, default=7)
- p.add_argument("--print-every", type=int, default=5)
- p.add_argument("--output-dir", type=str, default="iris_physical_snn_outputs")
- p.add_argument("--device", type=str, default="auto")
- p.add_argument("--reference-neuron-code", type=str, default="embedded", help="Deprecated compatibility option; packaged lookup tables are always used.")
- p.add_argument("--t-start-ns", type=float, default=200.0)
- p.add_argument("--t-sim-ns", type=float, default=525.0)
- p.add_argument("--dt-ns", type=float, default=0.1)
- p.add_argument("--pulse-spacing-ns", type=float, default=25.0)
- p.add_argument("--pulse-sigma-ns", type=float, default=4.0)
- p.add_argument("--feature-max", type=float, default=0.1, help="Upper bound for MinMax feature scaling; default [0, 0.1].")
- p.add_argument("--input-gain", type=float, default=1.5, help="Global gain multiplying input_weight * normalized_feature.")
- p.add_argument("--hidden-drive-scale", type=float, default=0.05, help="Scale applied after hidden [N,M] mixing to avoid saturation.")
- p.add_argument("--class-window-start-ns", type=float, default=420.0)
- p.add_argument("--class-window-end-ns", type=float, default=520.0)
- p.add_argument("--diagnostic-index", type=int, default=0)
- p.add_argument("--pwr-exc", type=float, default=0.008)
- p.add_argument("--decay-fix", type=float, default=0.016722666)
- p.add_argument("--decay-prime", type=float, default=0.5)
- p.add_argument("--use-decay-lookup", action="store_true")
- p.add_argument("--no-hard-eta-cutoff", action="store_true")
- p.add_argument("--k-softplus-scale", type=float, default=1.0e11)
- p.add_argument("--response-clip", type=float, default=1.0)
- ns = p.parse_args()
- return Config(
- M=ns.M,
- N=ns.N,
- repetitions=ns.repetitions,
- epochs=ns.epochs,
- n_runs=ns.n_runs,
- batch_size=ns.batch_size,
- lr=ns.lr,
- weight_decay=ns.weight_decay,
- seed=ns.seed,
- print_every=ns.print_every,
- output_dir=ns.output_dir,
- device=ns.device,
- reference_neuron_code=ns.reference_neuron_code,
- t_start_ns=ns.t_start_ns,
- t_sim_ns=ns.t_sim_ns,
- dt_ns=ns.dt_ns,
- pulse_spacing_ns=ns.pulse_spacing_ns,
- pulse_sigma_ns=ns.pulse_sigma_ns,
- feature_max=ns.feature_max,
- input_gain=ns.input_gain,
- hidden_drive_scale=ns.hidden_drive_scale,
- class_window_start_ns=ns.class_window_start_ns,
- class_window_end_ns=ns.class_window_end_ns,
- diagnostic_index=ns.diagnostic_index,
- pwr_exc=ns.pwr_exc,
- decay_fix=ns.decay_fix,
- decay_prime=ns.decay_prime,
- use_decay_lookup=ns.use_decay_lookup,
- use_hard_eta_cutoff=not ns.no_hard_eta_cutoff,
- k_softplus_scale=ns.k_softplus_scale,
- response_clip=ns.response_clip,
- )
- def train_one_run(base_cfg: Config, run_index: int, lookup_tables: Dict[str, np.ndarray], device: torch.device, root_out_dir: Path):
- """Train/evaluate one seeded run and save all per-run outputs."""
- run_seed = base_cfg.seed + run_index
- cfg = Config(**{**base_cfg.__dict__, "seed": run_seed})
- set_seed(cfg.seed)
- run_dir = root_out_dir / f"run_{run_index:02d}"
- run_dir.mkdir(parents=True, exist_ok=True)
- loaders, arrays = load_and_split_iris(cfg, device)
- time_ns = build_time_axis(cfg, device)
- model = IrisPhysicalSNN(cfg, time_ns, lookup_tables).to(device)
- if run_index == 0:
- consistency_checks(cfg, model, loaders)
- print(f"\n=== Run {run_index + 1}/{base_cfg.n_runs} | seed={run_seed} | device={device} ===")
- history = train_model(model, loaders, cfg, device)
- test_loss, test_acc = evaluate(model, loaders["test"], device)
- print(f"Run {run_index + 1} final test loss: {test_loss:.4f}")
- print(f"Run {run_index + 1} final test accuracy: {test_acc:.4f}")
- hist_path = save_history(history, run_dir)
- plot_paths = plot_history(history, run_dir)
- diag_paths = plot_diagnostic(model, arrays, cfg, run_dir)
- weights_path = run_dir / "trained_model_state_dict.pt"
- torch.save(model.state_dict(), weights_path)
- return {
- "run": run_index,
- "seed": run_seed,
- "history": history,
- "test_loss": test_loss,
- "test_accuracy": test_acc,
- "run_dir": run_dir,
- "training_history_csv": hist_path,
- "plot_paths": plot_paths,
- "diagnostic_paths": diag_paths,
- "weights_path": weights_path,
- }
- def main() -> None:
- cfg = parse_args()
- if cfg.n_runs <= 0:
- raise ValueError("--n-runs must be positive.")
- device = get_device(cfg.device)
- out_dir = Path(cfg.output_dir).expanduser().resolve()
- out_dir.mkdir(parents=True, exist_ok=True)
- lookup_tables = load_reference_lookup_tables_from_file()
- metadata_path = save_reproducibility_metadata(cfg, out_dir, device)
- run_results = []
- all_histories = []
- for run_index in range(cfg.n_runs):
- result = train_one_run(cfg, run_index, lookup_tables, device, out_dir)
- run_results.append(result)
- all_histories.append(result["history"])
- avg_paths = plot_average_accuracy(all_histories, out_dir)
- summary_rows = []
- for r in run_results:
- summary_rows.append([r["run"], r["seed"], r["test_loss"], r["test_accuracy"], str(r["run_dir"])])
- summary_csv = write_csv(out_dir / "all_runs_summary.csv", ["run", "seed", "test_loss", "test_accuracy", "run_dir"], summary_rows)
- readme_path = write_plot_readme(out_dir, cfg.n_runs)
- test_accs = np.asarray([r["test_accuracy"] for r in run_results], dtype=float)
- print("\nRepeated-run summary")
- print("--------------------")
- print(f"Runs : {cfg.n_runs}")
- print(f"Test accuracy mean : {test_accs.mean():.4f}")
- print(f"Test accuracy std : {test_accs.std(ddof=1 if cfg.n_runs > 1 else 0):.4f}")
- print("\nSaved top-level outputs")
- print("-----------------------")
- print(f"All-runs summary CSV : {summary_csv}")
- print(f"Average accuracy PNG : {avg_paths['png']}")
- print(f"Average accuracy SVG : {avg_paths['svg']}")
- print(f"Average accuracy CSV : {avg_paths['csv']}")
- print(f"Plot-data README : {readme_path}")
- print(f"Reproducibility metadata : {metadata_path}")
- print(f"Per-run outputs directory : {out_dir}")
- if __name__ == "__main__":
- main()
iris_experiment.py at commit 4ef085b, under MIT · at the source
Overview
- Fachbereich Physik and Landesforschungszentrum OPTIMAS, RPTU Kaiserslautern-Landau, Kaiserslautern, Germany
- V. G. Baryakhtar Institute of Magnetism of the NAS of Ukraine, Kyiv, Ukraine
- 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
- INNOVENT e.V. Technologieentwicklung, Jena, Germany
- Department of Electrical and Information Engineering, Politecnico di Bari, Bari, Italy
- Department of Mathematical and Computer Sciences, Physical Sciences and Earth Sciences, University of Messina, Messina, Italy
- Centre de Nanosciences et de Nanotechnologies, Université Paris-Saclay, Palaiseau, France
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
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
Availability: 1 check, the latest on 21 November 2026: the link answers (HTTP 200)
- 21 November 2026: the link answers (HTTP 200)
8 files
- code/
scripts/ , Jupyter, 942 linesgenerate-custom-activati on.ipynb - code/
scripts/ , Jupyter, 1,158 linesmain.ipynb - code/
src/ , Python, 68 linesload_fct.py - code/
src/ , Python, 143 linesplot_fct.py - code/
src/ , Python, 17 linespulse_fct.py - code/
src/ , Python, 37 linesresult_utils.py - code/
src/ , Python, 224 linessim_tools.py - code/
src/ , Python, 266 linessimulation.py
Zenodo 21628421
Availability: 1 check, the latest on 21 November 2026: the link answers (HTTP 200)
- 21 November 2026: the link answers (HTTP 200)
8 files
- scripts/
reproduce_all.py , Python, 53 lines - src/
physical_snn/ , Python, 3 lines__init__.py - src/
physical_snn/ , Python, 4 lines__main__.py - src/
physical_snn/ , Python, 1,040 linesiris_experiment.py - src/
physical_snn/ , Python, 505 linestwo_pulse.py - tests/
test_core.py , Python, 46 lines - LICENSE, License, 21 lines
- README.md, Text, 150 lines
dbreitba/magnonic-neuron-model
9c6b60be5d20294fa8ee7b83a19e3fa1e5e9f824, 16 February 2026Availability: 1 check, the latest on 21 November 2026: the link answers
- 21 November 2026: the link answers
8 files
- code/
scripts/ , Jupyter, 942 linesgenerate-custom-activati on.ipynb - code/
scripts/ , Jupyter, 1,158 lines, 2 matchesmain.ipynb - code/
src/ , Python, 68 linesload_fct.py - code/
src/ , Python, 143 linesplot_fct.py - code/
src/ , Python, 17 linespulse_fct.py - code/
src/ , Python, 37 linesresult_utils.py - code/
src/ , Python, 224 linessim_tools.py - code/
src/ , Python, 266 linessimulation.py
dbreitba/magnonic-snn
4ef085b2311dd7eaa71a62417729e31a6265cab6, 27 July 2026Availability: 1 check, the latest on 21 November 2026: the link answers
- 21 November 2026: the link answers
8 files
- scripts/
reproduce_all.py , Python, 53 lines - src/
physical_snn/ , Python, 3 lines__init__.py - src/
physical_snn/ , Python, 4 lines__main__.py - src/
physical_snn/ , Python, 1,040 lines, 4 matchesiris_experiment.py - src/
physical_snn/ , Python, 505 linestwo_pulse.py - tests/
test_core.py , Python, 46 lines - LICENSE, License, 21 lines
- README.md, Text, 150 lines
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/
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, 23 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. https://
BibTeX
@article{breitbach2026al
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},
doi = {10.1126/
url = {https://
pmid = {43063254},
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/
VL - 12
IS - 47
SP - eaeg1429
SN - 2375-2548
PB - American Association for the Advancement of Science
DO - 10.1126/
UR - https://
LA - en
ER -
CSL-JSON
{
"id": "10.1126/
"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":
"volume": "12",
"issue": "47",
"page": "eaeg1429",
"DOI": "10.1126/
"PMID": "43063254",
"PMCID": "PMC13787459",
"ISSN": "2375-2548",
"publisher": "American Association for the Advancement of Science",
"URL": "https://
"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: [code]
- An all-magnonic neuron with tunable fading memoryJournal: Science advancesIn 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 communicationsIn 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 reportsIn 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: NeuronIn 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 sciencesIn 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: eNeuroIn 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 communicationsIn common: xarray, PyTorch, scikit-learn, 4 other tools
- [8] doi:10.7554/elife.110074 [code]
- Disentangling cephalopod chromatophores motor units with computer vision.Journal: eLifeIn 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 biologyIn 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 communicationsIn 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.
Claim this paper
Correct its record
Say what each link of this record is, remove the ones that are not the paper's, add the ones that are missing. The correction becomes a new version of the record, in its Versions section.
Validate its tracing map
You validate the map as this page shows it: 4 repositories of the authors' code, each at its verified commit and with its license, 28 scripts, and 6 matches between paragraphs and code (see the Code and Map sections). It then receives a DOI on Zenodo, with you (your ORCID iD) and OSCR as its creators; the code itself is not deposited.
The map's fingerprint: sha256:e4374d39cdbe3ff3…
Add the badge to the code's README
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 -->
[](https://openscicode.org/badge/doi/10.1126/sciadv.aeg1429)
<!-- oscr-badge:end -->reStructuredText
.. oscr-badge:start
.. image:: https://openscicode.org/badge/doi/10.1126/sciadv.aeg1429.svg
:target: https://openscicode.org/badge/doi/10.1126/sciadv.aeg1429
:alt: OSCR
.. oscr-badge:endHTML
<!-- oscr-badge:start -->
<a href="https://openscicode.org/badge/doi/10.1126/sciadv.aeg1429"><img src="https://openscicode.org/badge/doi/10.1126/sciadv.aeg1429.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".
- dbreitba/magnonic-neuron-model on GitHub (add a README there)
- dbreitba/magnonic-snn: README.md on GitHub
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.
