NIR Bridge API
sc_neurocore.nir_bridge
NIR integration for SC-NeuroCore.
Provides bidirectional conversion between NIR graphs and SC-NeuroCore
networks.
Text Only>>> import nir
>>> from sc_neurocore.nir_bridge import from_nir
>>> graph = nir.read("model.nir")
>>> network = from_nir(graph, dt=1.0)
>>> network.run(inputs, steps=100)
HardwareNoiseAnnotation
dataclass
Measured target noise that can be replayed in simulation.
Source code in src/sc_neurocore/nir_bridge/hardware_targets.py
| Python |
|---|
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81 | @dataclass(frozen=True)
class HardwareNoiseAnnotation:
"""Measured target noise that can be replayed in simulation."""
target_id: str
observations: dict[str, float]
simulation_contract: dict[str, Any]
def to_dict(self) -> dict[str, Any]:
"""Return a JSON-serialisable noise annotation."""
return {
"observations": dict(self.observations),
"simulation_contract": dict(self.simulation_contract),
"target_id": self.target_id,
}
|
to_dict()
Return a JSON-serialisable noise annotation.
Source code in src/sc_neurocore/nir_bridge/hardware_targets.py
| Python |
|---|
| def to_dict(self) -> dict[str, Any]:
"""Return a JSON-serialisable noise annotation."""
return {
"observations": dict(self.observations),
"simulation_contract": dict(self.simulation_contract),
"target_id": self.target_id,
}
|
NeuromorphicHardwareProfile
dataclass
NIR extension profile for a named neuromorphic target.
Source code in src/sc_neurocore/nir_bridge/hardware_targets.py
| Python |
|---|
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63 | @dataclass(frozen=True)
class NeuromorphicHardwareProfile:
"""NIR extension profile for a named neuromorphic target."""
target_id: str
display_name: str
backend_status: str
supported_nir_nodes: tuple[str, ...]
unsupported_nir_nodes: tuple[str, ...]
sc_constraints: SCMappingConstraints
notes: tuple[str, ...] = ()
def to_manifest(self) -> dict[str, Any]:
"""Return the profile in deterministic manifest form."""
return {
"backend_status": self.backend_status,
"display_name": self.display_name,
"notes": list(self.notes),
"sc_constraints": self.sc_constraints.to_dict(),
"supported_nir_nodes": list(self.supported_nir_nodes),
"target_id": self.target_id,
"unsupported_nir_nodes": list(self.unsupported_nir_nodes),
}
|
to_manifest()
Return the profile in deterministic manifest form.
Source code in src/sc_neurocore/nir_bridge/hardware_targets.py
| Python |
|---|
52
53
54
55
56
57
58
59
60
61
62
63 | def to_manifest(self) -> dict[str, Any]:
"""Return the profile in deterministic manifest form."""
return {
"backend_status": self.backend_status,
"display_name": self.display_name,
"notes": list(self.notes),
"sc_constraints": self.sc_constraints.to_dict(),
"supported_nir_nodes": list(self.supported_nir_nodes),
"target_id": self.target_id,
"unsupported_nir_nodes": list(self.unsupported_nir_nodes),
}
|
SCMappingConstraints
dataclass
SC-specific constraints used before lowering NIR graphs to a target.
Source code in src/sc_neurocore/nir_bridge/hardware_targets.py
| Python |
|---|
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37 | @dataclass(frozen=True)
class SCMappingConstraints:
"""SC-specific constraints used before lowering NIR graphs to a target."""
bitstream_lengths: tuple[int, ...]
stream_transport: str
precision_modes: tuple[str, ...]
stochastic_sources: tuple[str, ...]
back_annotation_channels: tuple[str, ...]
def to_dict(self) -> dict[str, Any]:
"""Return a JSON-serialisable representation."""
return {
"bitstream_lengths": list(self.bitstream_lengths),
"stream_transport": self.stream_transport,
"precision_modes": list(self.precision_modes),
"stochastic_sources": list(self.stochastic_sources),
"back_annotation_channels": list(self.back_annotation_channels),
}
|
to_dict()
Return a JSON-serialisable representation.
Source code in src/sc_neurocore/nir_bridge/hardware_targets.py
| Python |
|---|
28
29
30
31
32
33
34
35
36
37 | def to_dict(self) -> dict[str, Any]:
"""Return a JSON-serialisable representation."""
return {
"bitstream_lengths": list(self.bitstream_lengths),
"stream_transport": self.stream_transport,
"precision_modes": list(self.precision_modes),
"stochastic_sources": list(self.stochastic_sources),
"back_annotation_channels": list(self.back_annotation_channels),
}
|
SiliconMappingConfig
dataclass
Configuration for NIR silicon mapping report generation.
Source code in src/sc_neurocore/nir_bridge/silicon_mapping.py
| Python |
|---|
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70 | @dataclass(frozen=True)
class SiliconMappingConfig:
"""Configuration for NIR silicon mapping report generation."""
targets: tuple[str, ...] = _DEFAULT_TARGETS
bitstream_length: int = 256
event_rate_hz: float = 1000.0
noise_observations: Mapping[str, Mapping[str, float]] = field(default_factory=dict)
artefact_name: str = "nir_silicon_mapping_report.json"
def __post_init__(self) -> None:
if not self.targets:
raise ValueError("targets must not be empty")
if self.bitstream_length <= 0:
raise ValueError("bitstream_length must be positive")
if self.event_rate_hz <= 0.0 or not math.isfinite(self.event_rate_hz):
raise ValueError("event_rate_hz must be finite and positive")
for target in self.targets:
get_hardware_profile(target)
|
NeuromorphicAdapterPackage
dataclass
Deterministic handoff package for one neuromorphic hardware target.
Source code in src/sc_neurocore/nir_bridge/neuromorphic_adapters.py
| Python |
|---|
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117 | @dataclass(frozen=True)
class NeuromorphicAdapterPackage:
"""Deterministic handoff package for one neuromorphic hardware target."""
target_id: str
adapter_name: str
vendor_stack: str
sdk_dependency: str
handoff_entrypoint: str
hardware_status: str
mapping_report: dict[str, Any]
target_report: dict[str, Any]
def manifest(self) -> dict[str, Any]:
"""Return a JSON-serialisable adapter manifest."""
return {
"adapter_name": self.adapter_name,
"fallback_requirements": list(self.target_report["fallback_requirements"]),
"handoff_entrypoint": self.handoff_entrypoint,
"hardware_status": self.hardware_status,
"lowering_status": self.target_report["lowering_status"],
"noise_back_annotation_hooks": list(self.target_report["noise_back_annotation_hooks"]),
"schema_version": ADAPTER_SCHEMA_VERSION,
"sdk_dependency": self.sdk_dependency,
"summary": dict(self.target_report["summary"]),
"target_id": self.target_id,
"vendor_stack": self.vendor_stack,
}
def files(self) -> dict[str, str]:
"""Return deterministic package files keyed by relative path."""
manifest = self.manifest()
limitations = "\n".join(f"- {item}" for item in self.target_report["limitations"])
fallback = "\n".join(
f"- {item['node']} ({item['node_type']}): {item['requirement']}"
for item in self.target_report["fallback_requirements"]
)
if not fallback:
fallback = "- none"
readme = (
f"# {self.adapter_name}\n\n"
f"Target: `{self.target_id}`\n\n"
f"Vendor stack: {self.vendor_stack}\n\n"
f"SDK dependency: `{self.sdk_dependency}`\n\n"
f"Lowering status: `{self.target_report['lowering_status']}`\n\n"
"## Handoff Boundary\n\n"
f"{self.handoff_entrypoint}. {self.hardware_status}.\n\n"
"This package is a deterministic SC-NeuroCore planning artefact. "
"It does not claim execution on vendor hardware until the vendor SDK "
"run and board logs are attached.\n\n"
"## Fallback Requirements\n\n"
f"{fallback}\n\n"
"## Limitations\n\n"
f"{limitations}\n"
)
return {
f"{self.target_id}/adapter_manifest.json": json.dumps(
manifest, indent=2, sort_keys=True
)
+ "\n",
f"{self.target_id}/nir_silicon_mapping_report.json": json.dumps(
self.mapping_report, indent=2, sort_keys=True
)
+ "\n",
f"{self.target_id}/README.md": readme,
}
|
manifest()
Return a JSON-serialisable adapter manifest.
Source code in src/sc_neurocore/nir_bridge/neuromorphic_adapters.py
| Python |
|---|
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78 | def manifest(self) -> dict[str, Any]:
"""Return a JSON-serialisable adapter manifest."""
return {
"adapter_name": self.adapter_name,
"fallback_requirements": list(self.target_report["fallback_requirements"]),
"handoff_entrypoint": self.handoff_entrypoint,
"hardware_status": self.hardware_status,
"lowering_status": self.target_report["lowering_status"],
"noise_back_annotation_hooks": list(self.target_report["noise_back_annotation_hooks"]),
"schema_version": ADAPTER_SCHEMA_VERSION,
"sdk_dependency": self.sdk_dependency,
"summary": dict(self.target_report["summary"]),
"target_id": self.target_id,
"vendor_stack": self.vendor_stack,
}
|
files()
Return deterministic package files keyed by relative path.
Source code in src/sc_neurocore/nir_bridge/neuromorphic_adapters.py
| Python |
|---|
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117 | def files(self) -> dict[str, str]:
"""Return deterministic package files keyed by relative path."""
manifest = self.manifest()
limitations = "\n".join(f"- {item}" for item in self.target_report["limitations"])
fallback = "\n".join(
f"- {item['node']} ({item['node_type']}): {item['requirement']}"
for item in self.target_report["fallback_requirements"]
)
if not fallback:
fallback = "- none"
readme = (
f"# {self.adapter_name}\n\n"
f"Target: `{self.target_id}`\n\n"
f"Vendor stack: {self.vendor_stack}\n\n"
f"SDK dependency: `{self.sdk_dependency}`\n\n"
f"Lowering status: `{self.target_report['lowering_status']}`\n\n"
"## Handoff Boundary\n\n"
f"{self.handoff_entrypoint}. {self.hardware_status}.\n\n"
"This package is a deterministic SC-NeuroCore planning artefact. "
"It does not claim execution on vendor hardware until the vendor SDK "
"run and board logs are attached.\n\n"
"## Fallback Requirements\n\n"
f"{fallback}\n\n"
"## Limitations\n\n"
f"{limitations}\n"
)
return {
f"{self.target_id}/adapter_manifest.json": json.dumps(
manifest, indent=2, sort_keys=True
)
+ "\n",
f"{self.target_id}/nir_silicon_mapping_report.json": json.dumps(
self.mapping_report, indent=2, sort_keys=True
)
+ "\n",
f"{self.target_id}/README.md": readme,
}
|
ConnectionSpec
dataclass
Weighted edge between two neuron populations.
Attributes
src : str
Source population name.
dst : str
Destination population name.
weights : np.ndarray
Weight matrix of shape (n_dst, n_src) in float32.
Row i contains the weights from all source neurons to
destination neuron i.
bias : np.ndarray | None
Optional bias vector of shape (n_dst,).
Source code in src/sc_neurocore/nir_bridge/neuron_graph.py
| Python |
|---|
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119 | @dataclass
class ConnectionSpec:
"""Weighted edge between two neuron populations.
Attributes
----------
src : str
Source population name.
dst : str
Destination population name.
weights : np.ndarray
Weight matrix of shape ``(n_dst, n_src)`` in float32.
Row *i* contains the weights from all source neurons to
destination neuron *i*.
bias : np.ndarray | None
Optional bias vector of shape ``(n_dst,)``.
"""
src: str
dst: str
weights: np.ndarray
bias: np.ndarray | None = None
|
NeuronGraph
dataclass
Complete network description ready for FPGA compilation.
Attributes
populations : list[NeuronSpec]
Ordered list of neuron populations (topological order).
connections : list[ConnectionSpec]
Weighted connections between populations.
input_pop : str
Name of the input population.
output_pop : str
Name of the output population.
dt : float
Global simulation timestep.
Source code in src/sc_neurocore/nir_bridge/neuron_graph.py
| Python |
|---|
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183 | @dataclass
class NeuronGraph:
"""Complete network description ready for FPGA compilation.
Attributes
----------
populations : list[NeuronSpec]
Ordered list of neuron populations (topological order).
connections : list[ConnectionSpec]
Weighted connections between populations.
input_pop : str
Name of the input population.
output_pop : str
Name of the output population.
dt : float
Global simulation timestep.
"""
populations: list[NeuronSpec]
connections: list[ConnectionSpec]
input_pop: str
output_pop: str
dt: float = 1.0
@property
def total_neurons(self) -> int:
"""Total neuron count across all populations."""
return sum(pop.n_neurons for pop in self.populations)
@property
def total_synapses(self) -> int:
"""Total synapse count across all connections."""
return sum(conn.weights.size for conn in self.connections)
@property
def neuron_types(self) -> set[str]:
"""Set of unique neuron types in the graph."""
return {pop.neuron_type for pop in self.populations}
def summary(self) -> str:
"""Human-readable summary of the network graph."""
lines = [
f"NeuronGraph: {len(self.populations)} populations, "
f"{len(self.connections)} connections",
f" Total neurons: {self.total_neurons}",
f" Total synapses: {self.total_synapses}",
f" Neuron types: {', '.join(sorted(self.neuron_types))}",
f" Input: {self.input_pop}",
f" Output: {self.output_pop}",
f" dt: {self.dt}",
"",
" Populations:",
]
for pop in self.populations:
lines.append(f" {pop.name}: {pop.neuron_type} × {pop.n_neurons}")
lines.append("")
lines.append(" Connections:")
for conn in self.connections:
shape = f"{conn.weights.shape[1]}→{conn.weights.shape[0]}"
bias_str = " +bias" if conn.bias is not None else ""
lines.append(f" {conn.src} → {conn.dst}: {shape}{bias_str}")
return "\n".join(lines)
|
total_neurons
property
Total neuron count across all populations.
total_synapses
property
Total synapse count across all connections.
neuron_types
property
Set of unique neuron types in the graph.
summary()
Human-readable summary of the network graph.
Source code in src/sc_neurocore/nir_bridge/neuron_graph.py
| Python |
|---|
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183 | def summary(self) -> str:
"""Human-readable summary of the network graph."""
lines = [
f"NeuronGraph: {len(self.populations)} populations, "
f"{len(self.connections)} connections",
f" Total neurons: {self.total_neurons}",
f" Total synapses: {self.total_synapses}",
f" Neuron types: {', '.join(sorted(self.neuron_types))}",
f" Input: {self.input_pop}",
f" Output: {self.output_pop}",
f" dt: {self.dt}",
"",
" Populations:",
]
for pop in self.populations:
lines.append(f" {pop.name}: {pop.neuron_type} × {pop.n_neurons}")
lines.append("")
lines.append(" Connections:")
for conn in self.connections:
shape = f"{conn.weights.shape[1]}→{conn.weights.shape[0]}"
bias_str = " +bias" if conn.bias is not None else ""
lines.append(f" {conn.src} → {conn.dst}: {shape}{bias_str}")
return "\n".join(lines)
|
NeuronSpec
dataclass
One neuron population (layer) in the compiled graph.
Attributes
name : str
Unique population identifier (matches the NIR node name).
neuron_type : str
Canonical neuron type: "lif", "if", "li",
"cuba_lif", "cuba_li".
n_neurons : int
Number of neurons in this population.
params : dict[str, np.ndarray]
Neuron parameters keyed by canonical names:
tau, r, v_leak, v_threshold, v_reset,
tau_syn, tau_mem, w_in (type-dependent).
dt : float
Simulation timestep used during NIR import.
Source code in src/sc_neurocore/nir_bridge/neuron_graph.py
| Python |
|---|
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95 | @dataclass
class NeuronSpec:
"""One neuron population (layer) in the compiled graph.
Attributes
----------
name : str
Unique population identifier (matches the NIR node name).
neuron_type : str
Canonical neuron type: ``"lif"``, ``"if"``, ``"li"``,
``"cuba_lif"``, ``"cuba_li"``.
n_neurons : int
Number of neurons in this population.
params : dict[str, np.ndarray]
Neuron parameters keyed by canonical names:
``tau``, ``r``, ``v_leak``, ``v_threshold``, ``v_reset``,
``tau_syn``, ``tau_mem``, ``w_in`` (type-dependent).
dt : float
Simulation timestep used during NIR import.
"""
name: str
neuron_type: str
n_neurons: int
params: dict[str, np.ndarray] = field(default_factory=dict)
dt: float = 1.0
|
QuantisedGraph
dataclass
NeuronGraph with all parameters converted to Q-format integers.
Attributes
populations : list[NeuronSpec]
Populations with integer-valued parameters (Q-encoded).
connections : list[ConnectionSpec]
Connections with integer-valued weight matrices (Q-encoded).
q : Q88
The fixed-point format configuration used.
input_pop : str
Input population name.
output_pop : str
Output population name.
dt : float
Global timestep.
warnings : list[str]
Overflow/underflow warnings generated during quantisation.
total_neurons : int
Total neuron count.
total_synapses : int
Total synapse count.
Source code in src/sc_neurocore/nir_bridge/quantise_params.py
| Python |
|---|
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94 | @dataclass
class QuantisedGraph:
"""NeuronGraph with all parameters converted to Q-format integers.
Attributes
----------
populations : list[NeuronSpec]
Populations with integer-valued parameters (Q-encoded).
connections : list[ConnectionSpec]
Connections with integer-valued weight matrices (Q-encoded).
q : Q88
The fixed-point format configuration used.
input_pop : str
Input population name.
output_pop : str
Output population name.
dt : float
Global timestep.
warnings : list[str]
Overflow/underflow warnings generated during quantisation.
total_neurons : int
Total neuron count.
total_synapses : int
Total synapse count.
"""
populations: list[NeuronSpec]
connections: list[ConnectionSpec]
q: Q88
input_pop: str
output_pop: str
dt: float
warnings: list[str] = field(default_factory=list)
total_neurons: int = 0
total_synapses: int = 0
|
NetworkCompilationResult
dataclass
All artefacts from a network-level FPGA compilation.
Attributes
neuron_modules : dict[str, str]
Mapping from neuron type to Verilog source.
weight_rom : str
Weight ROM Verilog source.
top_module : str
Top-level interconnect Verilog source.
module_name : str
Top-level module name.
total_neurons : int
Total neuron count.
total_synapses : int
Total synapse count.
q_format : str
Q-format label (e.g. "Q8.8").
interconnect : str
"direct" or "aer".
warnings : list[str]
Quantisation and compilation warnings.
Source code in src/sc_neurocore/nir_bridge/fpga_compiler.py
| Python |
|---|
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216 | @dataclass
class NetworkCompilationResult:
"""All artefacts from a network-level FPGA compilation.
Attributes
----------
neuron_modules : dict[str, str]
Mapping from neuron type to Verilog source.
weight_rom : str
Weight ROM Verilog source.
top_module : str
Top-level interconnect Verilog source.
module_name : str
Top-level module name.
total_neurons : int
Total neuron count.
total_synapses : int
Total synapse count.
q_format : str
Q-format label (e.g. ``"Q8.8"``).
interconnect : str
``"direct"`` or ``"aer"``.
warnings : list[str]
Quantisation and compilation warnings.
"""
neuron_modules: dict[str, str]
weight_rom: str
top_module: str
module_name: str
total_neurons: int
total_synapses: int
q_format: str
interconnect: str
warnings: list[str] = field(default_factory=list)
|
available_hardware_profiles()
Return all known hardware profiles in deterministic order.
Source code in src/sc_neurocore/nir_bridge/hardware_targets.py
| Python |
|---|
| def available_hardware_profiles() -> tuple[NeuromorphicHardwareProfile, ...]:
"""Return all known hardware profiles in deterministic order."""
return tuple(_PROFILES[key] for key in sorted(_PROFILES))
|
build_nir_hardware_manifest(targets=None)
Build a deterministic manifest for NIR hardware-extension planning.
Source code in src/sc_neurocore/nir_bridge/hardware_targets.py
| Python |
|---|
239
240
241
242
243
244
245
246
247
248 | def build_nir_hardware_manifest(targets: tuple[str, ...] | None = None) -> dict[str, Any]:
"""Build a deterministic manifest for NIR hardware-extension planning."""
selected = tuple(sorted(_PROFILES)) if targets is None else targets
profiles = [get_hardware_profile(target).to_manifest() for target in selected]
return {
"schema_version": "1.0",
"extension": "sc_neurocore.nir_hardware_targets",
"profiles": profiles,
}
|
build_noise_annotation(target_id, observations)
Validate measured hardware noise and prepare it for simulation replay.
Source code in src/sc_neurocore/nir_bridge/hardware_targets.py
| Python |
|---|
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278 | def build_noise_annotation(
target_id: str,
observations: Mapping[str, float],
) -> HardwareNoiseAnnotation:
"""Validate measured hardware noise and prepare it for simulation replay."""
profile = get_hardware_profile(target_id)
allowed = set(profile.sc_constraints.back_annotation_channels)
unknown = sorted(set(observations) - allowed)
if unknown:
raise ValueError(f"unknown noise channels for {profile.target_id}: {', '.join(unknown)}")
clean: dict[str, float] = {}
for name, value in observations.items():
numeric = float(value)
if not math.isfinite(numeric) or numeric < 0:
raise ValueError(f"noise channel '{name}' must be finite and non-negative")
clean[name] = numeric
return HardwareNoiseAnnotation(
target_id=profile.target_id,
observations=clean,
simulation_contract={
"apply_to": "sc_probability_and_event_timing",
"replay_mode": "deterministic_seeded",
"requires_measured_hardware": True,
},
)
|
get_hardware_profile(target_id)
Return one hardware profile by identifier.
Source code in src/sc_neurocore/nir_bridge/hardware_targets.py
| Python |
|---|
229
230
231
232
233
234
235
236 | def get_hardware_profile(target_id: str) -> NeuromorphicHardwareProfile:
"""Return one hardware profile by identifier."""
key = target_id.lower().replace("-", "_")
if key not in _PROFILES:
known = ", ".join(sorted(_PROFILES))
raise KeyError(f"unknown neuromorphic target '{target_id}'. Known targets: {known}")
return _PROFILES[key]
|
build_silicon_mapping_report(source, config=None)
Build a deterministic target-mapping report for a parsed NIR network.
Source code in src/sc_neurocore/nir_bridge/silicon_mapping.py
| Python |
|---|
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100 | def build_silicon_mapping_report(
source: Any,
config: SiliconMappingConfig | None = None,
) -> dict[str, Any]:
"""Build a deterministic target-mapping report for a parsed NIR network."""
cfg = config or SiliconMappingConfig()
graph = _coerce_graph(source)
node_payloads = [_node_payload(name, graph.nodes[name]) for name in graph.order]
return {
"schema_version": SCHEMA_VERSION,
"source": {
"node_count": len(graph.nodes),
"edge_count": len(graph.edges),
"topological_order": list(graph.order),
},
"targets": [
_target_report(target, node_payloads, graph.edges, cfg) for target in cfg.targets
],
}
|
write_silicon_mapping_report(output_dir, source, config=None)
Write nir_silicon_mapping_report.json in deterministic form.
Source code in src/sc_neurocore/nir_bridge/silicon_mapping.py
| Python |
|---|
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118 | def write_silicon_mapping_report(
output_dir: str | Path,
source: Any,
config: SiliconMappingConfig | None = None,
) -> Path:
"""Write `nir_silicon_mapping_report.json` in deterministic form."""
cfg = config or SiliconMappingConfig()
output = Path(output_dir)
output.mkdir(parents=True, exist_ok=True)
path = output / cfg.artefact_name
path.write_text(
json.dumps(build_silicon_mapping_report(source, cfg), indent=2, sort_keys=True) + "\n",
encoding="utf-8",
)
return path
|
build_neuromorphic_adapter_bundle(source, targets=SUPPORTED_ADAPTER_TARGETS, config=None)
Build deterministic adapter packages for multiple targets.
Source code in src/sc_neurocore/nir_bridge/neuromorphic_adapters.py
| Python |
|---|
144
145
146
147
148
149
150
151
152
153
154
155
156 | def build_neuromorphic_adapter_bundle(
source: Any,
targets: tuple[str, ...] = SUPPORTED_ADAPTER_TARGETS,
config: SiliconMappingConfig | None = None,
) -> dict[str, NeuromorphicAdapterPackage]:
"""Build deterministic adapter packages for multiple targets."""
return {
_normalise_adapter_target(target): build_neuromorphic_adapter_package(
source, target, config
)
for target in targets
}
|
build_neuromorphic_adapter_package(source, target_id, config=None)
Build one Loihi 2 or SpiNNaker2 adapter handoff package.
Source code in src/sc_neurocore/nir_bridge/neuromorphic_adapters.py
| Python |
|---|
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141 | def build_neuromorphic_adapter_package(
source: Any,
target_id: str,
config: SiliconMappingConfig | None = None,
) -> NeuromorphicAdapterPackage:
"""Build one Loihi 2 or SpiNNaker2 adapter handoff package."""
target = _normalise_adapter_target(target_id)
cfg = _target_config(target, config)
report = build_silicon_mapping_report(source, cfg)
target_report = report["targets"][0]
handoff = _TARGET_HANDOFFS[target]
return NeuromorphicAdapterPackage(
target_id=target,
adapter_name=handoff["adapter_name"],
vendor_stack=handoff["vendor_stack"],
sdk_dependency=handoff["sdk_dependency"],
handoff_entrypoint=handoff["handoff_entrypoint"],
hardware_status=handoff["hardware_status"],
mapping_report=report,
target_report=target_report,
)
|
write_neuromorphic_adapter_bundle(output_dir, source, targets=SUPPORTED_ADAPTER_TARGETS, config=None)
Write Loihi 2/SpiNNaker2 adapter manifests and reports to disk.
Source code in src/sc_neurocore/nir_bridge/neuromorphic_adapters.py
| Python |
|---|
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176 | def write_neuromorphic_adapter_bundle(
output_dir: str | Path,
source: Any,
targets: tuple[str, ...] = SUPPORTED_ADAPTER_TARGETS,
config: SiliconMappingConfig | None = None,
) -> dict[str, Path]:
"""Write Loihi 2/SpiNNaker2 adapter manifests and reports to disk."""
output = Path(output_dir)
packages = build_neuromorphic_adapter_bundle(source, targets, config)
written: dict[str, Path] = {}
for target, package in packages.items():
for rel_path, content in package.files().items():
path = output / rel_path
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content, encoding="utf-8")
written[f"{target}:{rel_path}"] = path
return written
|
from_scnetwork(network, dt=None)
Convert a parsed SCNetwork to a NeuronGraph for FPGA compilation.
Walks the topologically-sorted node list and partitions nodes into
neuron populations and weighted connections. Pass-through nodes
(Input, Output, Scale, Flatten, Threshold) are folded into the
adjacent edges.
Parameters
network : SCNetwork
A parsed SC-NeuroCore network (from from_nir()).
dt : float, optional
Override the simulation timestep. If None, uses the
timestep stored in the network's neuron nodes.
Returns
NeuronGraph
Network description ready for FPGA compilation.
Raises
ValueError
If the network contains no neuron populations or no connections.
Source code in src/sc_neurocore/nir_bridge/neuron_graph.py
| Python |
|---|
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449 | def from_scnetwork(network: Any, dt: float | None = None) -> NeuronGraph:
"""Convert a parsed SCNetwork to a NeuronGraph for FPGA compilation.
Walks the topologically-sorted node list and partitions nodes into
neuron populations and weighted connections. Pass-through nodes
(Input, Output, Scale, Flatten, Threshold) are folded into the
adjacent edges.
Parameters
----------
network : SCNetwork
A parsed SC-NeuroCore network (from ``from_nir()``).
dt : float, optional
Override the simulation timestep. If ``None``, uses the
timestep stored in the network's neuron nodes.
Returns
-------
NeuronGraph
Network description ready for FPGA compilation.
Raises
------
ValueError
If the network contains no neuron populations or no connections.
"""
topo_order = network.topo_order
nodes = network.nodes
edges = list(network.edges)
# Build adjacency: node_name → list of successor node names
successors: dict[str, list[str]] = {}
predecessors: dict[str, list[str]] = {}
for src, dst in edges:
successors.setdefault(src, []).append(dst)
predecessors.setdefault(dst, []).append(src)
populations: list[NeuronSpec] = []
connections: list[ConnectionSpec] = []
input_pop = ""
output_pop = ""
# Track which weight node feeds which neuron node
# Pattern: Input → [Affine/Linear] → [Neuron] → [Affine/Linear] → [Neuron] → Output
pending_weights: dict[str, tuple[np.ndarray, np.ndarray | None]] = {}
# Maps a neuron node name → the weight node that feeds it
weight_source_for: dict[str, str] = {}
# First pass: classify nodes
for name in topo_order:
node = nodes[name]
class_name = type(node).__name__
if class_name == "SCInputNode":
# Input node: find the first neuron population downstream
if not input_pop:
input_pop = name
continue
if class_name == "SCOutputNode":
if not output_pop:
output_pop = name
continue
if class_name in _SC_WEIGHT_NODES:
# Weight-carrying node: store weights for the downstream neuron
weight = getattr(node, "weight", None)
bias = getattr(node, "bias", None)
if weight is None:
w = getattr(node, "weights", None)
if w is not None:
weight = w
if weight is not None:
weight = np.asarray(weight, dtype=np.float32)
if bias is not None:
bias = np.asarray(bias, dtype=np.float32)
pending_weights[name] = (weight, bias)
# Find the neuron this feeds into
for succ in successors.get(name, []):
succ_class = type(nodes[succ]).__name__
if succ_class in _SC_NODE_TO_TYPE:
weight_source_for[succ] = name
continue
if class_name in _SC_PASSTHROUGH_NODES:
continue
# Neuron node
neuron_type = _SC_NODE_TO_TYPE.get(class_name)
if neuron_type is None:
logger.warning(
"Skipping unsupported node type %s (%s) in FPGA compilation",
class_name,
name,
)
continue
n_neurons = getattr(node, "n_neurons", 1)
node_dt = dt if dt is not None else getattr(node, "dt", 1.0)
params = _extract_neuron_params(node, neuron_type)
populations.append(
NeuronSpec(
name=name,
neuron_type=neuron_type,
n_neurons=max(1, n_neurons),
params=params,
dt=node_dt,
)
)
# Second pass: build connections from weight nodes
for i, pop in enumerate(populations):
weight_node_name = weight_source_for.get(pop.name)
if weight_node_name is None:
continue
weight_data = pending_weights.get(weight_node_name)
if weight_data is None:
continue
weights, bias = weight_data
# Find the source population: the neuron or input node that feeds
# the weight node
src_name = ""
for pred in predecessors.get(weight_node_name, []):
pred_class = type(nodes[pred]).__name__
if pred_class in _SC_NODE_TO_TYPE:
src_name = pred
break
if pred_class == "SCInputNode":
src_name = pred
break
if not src_name:
# Use first predecessor
preds = predecessors.get(weight_node_name, [])
if preds:
src_name = preds[0]
else:
src_name = input_pop or "input"
connections.append(
ConnectionSpec(
src=src_name,
dst=pop.name,
weights=weights,
bias=bias,
)
)
# Determine effective input/output
if not input_pop and populations:
input_pop = populations[0].name
if not output_pop and populations:
output_pop = populations[-1].name
if not populations:
raise ValueError(
"NeuronGraph requires at least one neuron population. "
"The NIR graph may contain only pass-through nodes."
)
global_dt = dt if dt is not None else (populations[0].dt if populations else 1.0)
graph = NeuronGraph(
populations=populations,
connections=connections,
input_pop=input_pop,
output_pop=output_pop,
dt=global_dt,
)
logger.info(
"Built NeuronGraph: %d populations, %d connections, %d neurons, %d synapses",
len(populations),
len(connections),
graph.total_neurons,
graph.total_synapses,
)
return graph
|
quantise_graph(graph, q)
Convert all floating-point parameters to Q-format integers.
Parameters
graph : NeuronGraph
Network with float32 parameters.
q : Q88
Target fixed-point format.
Returns
QuantisedGraph
Network with integer-valued parameters and quantisation warnings.
Source code in src/sc_neurocore/nir_bridge/quantise_params.py
| Python |
|---|
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295 | def quantise_graph(graph: NeuronGraph, q: Q88) -> QuantisedGraph:
"""Convert all floating-point parameters to Q-format integers.
Parameters
----------
graph : NeuronGraph
Network with float32 parameters.
q : Q88
Target fixed-point format.
Returns
-------
QuantisedGraph
Network with integer-valued parameters and quantisation warnings.
"""
warnings: list[str] = []
# Check global dt
_check_dt_quantisation(graph.dt, q, warnings)
# Quantise populations
q_populations: list[NeuronSpec] = []
for pop in graph.populations:
q_params: dict[str, np.ndarray] = {}
for pname, pval in pop.params.items():
q_params[pname] = _quantise_array(
pval,
q,
label=f"{pop.name}.{pname}",
warnings=warnings,
)
q_populations.append(
NeuronSpec(
name=pop.name,
neuron_type=pop.neuron_type,
n_neurons=pop.n_neurons,
params=q_params,
dt=pop.dt,
)
)
# Quantise connections
q_connections: list[ConnectionSpec] = []
for conn in graph.connections:
q_weights = _quantise_array(
conn.weights,
q,
label=f"weights[{conn.src}→{conn.dst}]",
warnings=warnings,
)
q_bias = None
if conn.bias is not None:
q_bias = _quantise_array(
conn.bias,
q,
label=f"bias[{conn.src}→{conn.dst}]",
warnings=warnings,
)
q_connections.append(
ConnectionSpec(
src=conn.src,
dst=conn.dst,
weights=q_weights,
bias=q_bias,
)
)
result = QuantisedGraph(
populations=q_populations,
connections=q_connections,
q=q,
input_pop=graph.input_pop,
output_pop=graph.output_pop,
dt=graph.dt,
warnings=warnings,
total_neurons=graph.total_neurons,
total_synapses=graph.total_synapses,
)
logger.info(
"Quantised %d populations, %d connections to Q%d.%d (%d warnings)",
len(q_populations),
len(q_connections),
q.data_width - q.fraction,
q.fraction,
len(warnings),
)
return result
|
compile_network_to_fpga(graph, *, module_name='sc_nir_network', data_width=16, fraction=8, target='artix7')
Compile a NeuronGraph to synthesisable Verilog RTL.
End-to-end pipeline:
- Quantise all parameters to the target Q-format.
- Generate one Verilog module per unique neuron type.
- Generate a combined weight ROM.
- Generate a top-level interconnect module (direct or AER).
Parameters
graph : NeuronGraph
Network description (from from_scnetwork()).
module_name : str
Top-level Verilog module name.
data_width : int
Fixed-point total width (16 for Q8.8, 32 for Q16.16).
fraction : int
Fractional bits.
target : str
FPGA target for resource estimation hints.
Returns
NetworkCompilationResult
All generated Verilog sources and compilation metadata.
Raises
ValueError
If the graph is empty or contains unsupported neuron types.
Source code in src/sc_neurocore/nir_bridge/fpga_compiler.py
| Python |
|---|
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043 | def compile_network_to_fpga(
graph: NeuronGraph,
*,
module_name: str = "sc_nir_network",
data_width: int = 16,
fraction: int = 8,
target: str = "artix7",
) -> NetworkCompilationResult:
"""Compile a NeuronGraph to synthesisable Verilog RTL.
End-to-end pipeline:
1. Quantise all parameters to the target Q-format.
2. Generate one Verilog module per unique neuron type.
3. Generate a combined weight ROM.
4. Generate a top-level interconnect module (direct or AER).
Parameters
----------
graph : NeuronGraph
Network description (from ``from_scnetwork()``).
module_name : str
Top-level Verilog module name.
data_width : int
Fixed-point total width (16 for Q8.8, 32 for Q16.16).
fraction : int
Fractional bits.
target : str
FPGA target for resource estimation hints.
Returns
-------
NetworkCompilationResult
All generated Verilog sources and compilation metadata.
Raises
------
ValueError
If the graph is empty or contains unsupported neuron types.
"""
q = Q88(data_width=data_width, fraction=fraction)
warnings: list[str] = []
# Step 1: Quantise
qgraph = quantise_graph(graph, q)
warnings.extend(qgraph.warnings)
# Step 2: Generate per-type neuron modules (cached by exact parameter set)
neuron_modules: dict[str, str] = {}
type_representative: dict[str, NeuronSpec] = {}
type_signature: dict[str, tuple[Any, ...]] = {}
for pop in graph.populations:
signature = _population_module_signature(pop)
if pop.neuron_type not in type_representative:
type_representative[pop.neuron_type] = pop
type_signature[pop.neuron_type] = signature
elif type_signature[pop.neuron_type] != signature:
raise ValueError(
f"Neuron type {pop.neuron_type!r} appears with different "
"parameters across populations; per-population RTL modules are "
"required before this can be compiled faithfully"
)
for ntype, rep_pop in type_representative.items():
if ntype not in _NEURON_TEMPLATES:
warnings.append(f"Unsupported neuron type '{ntype}' — skipping module generation")
continue
try:
verilog = _build_neuron_module(
ntype,
rep_pop,
data_width=data_width,
fraction=fraction,
)
neuron_modules[ntype] = verilog
logger.info("Generated Verilog for neuron type: %s", ntype)
except (ValueError, KeyError) as exc:
warnings.append(f"Failed to compile neuron type '{ntype}': {exc}")
logger.error("Neuron compilation failed for %s: %s", ntype, exc)
# Step 3: Weight ROM
weight_rom = _build_weight_rom(qgraph, data_width=data_width)
# Step 4: Top-level interconnect. Small networks use explicit direct
# wiring. Larger networks use weighted address-event fan-out while
# preserving dense affine accumulation semantics.
total_neurons = graph.total_neurons
interconnect = "direct"
if total_neurons > _AER_THRESHOLD:
interconnect = "aer"
top_module = _build_top_aer(
module_name,
qgraph,
data_width=data_width,
fraction=fraction,
)
else:
top_module = _build_top_direct(
module_name,
qgraph,
data_width=data_width,
fraction=fraction,
)
q_label = f"Q{data_width - fraction}.{fraction}"
result = NetworkCompilationResult(
neuron_modules=neuron_modules,
weight_rom=weight_rom,
top_module=top_module,
module_name=module_name,
total_neurons=total_neurons,
total_synapses=graph.total_synapses,
q_format=q_label,
interconnect=interconnect,
warnings=warnings,
)
logger.info(
"Network compilation complete: %s, %d neurons, %d synapses, %s interconnect, %d warnings",
q_label,
total_neurons,
graph.total_synapses,
interconnect,
len(warnings),
)
return result
|
from_nir(source, dt=1.0, reset_mode='reset')
Convert a NIR graph/source to an SC-NeuroCore network.
Source code in src/sc_neurocore/nir_bridge/__init__.py
| Python |
|---|
| def from_nir(source: Any, dt: float = 1.0, reset_mode: str = "reset") -> Any:
"""Convert a NIR graph/source to an SC-NeuroCore network."""
if _from_nir_impl is None:
if _NIR_IMPORT_ERROR is None:
raise ImportError("NIR import failed")
raise _NIR_IMPORT_ERROR
return _from_nir_impl(source, dt=dt, reset_mode=reset_mode)
|
to_nir(network, path=None)
Export an SC-NeuroCore network to NIR.
Source code in src/sc_neurocore/nir_bridge/__init__.py
| Python |
|---|
| def to_nir(network: Any, path: str | Path | None = None) -> Any:
"""Export an SC-NeuroCore network to NIR."""
if _to_nir_impl is None:
if _NIR_IMPORT_ERROR is None:
raise ImportError("NIR import failed")
raise _NIR_IMPORT_ERROR
return _to_nir_impl(network, path=path)
|
Parser
sc_neurocore.nir_bridge.parser
SCNetwork
dataclass
Executable network parsed from a NIR graph.
Nodes are stored by name. Edges define the forward pass order.
Calling run() feeds input through the graph for the given
number of timesteps and returns the output node's accumulated result.
Recurrent edges (cycles) are automatically handled by inserting
unit-delay nodes that feed from the previous timestep.
Source code in src/sc_neurocore/nir_bridge/parser.py
| Python |
|---|
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271 | @dataclass
class SCNetwork:
"""Executable network parsed from a NIR graph.
Nodes are stored by name. Edges define the forward pass order.
Calling ``run()`` feeds input through the graph for the given
number of timesteps and returns the output node's accumulated result.
Recurrent edges (cycles) are automatically handled by inserting
unit-delay nodes that feed from the previous timestep.
"""
nodes: dict[str, Any] = field(default_factory=dict)
edges: list[tuple[str, str]] = field(default_factory=list)
input_nodes: list[str] = field(default_factory=list)
output_nodes: list[str] = field(default_factory=list)
_topo_order: list[str] | None = None
# Maps delay_node_name → source_node_name for recurrent connections
_recurrent_map: dict[str, str] = field(default_factory=dict)
def _find_back_edges(self) -> list[tuple[str, str]]:
"""DFS-based back-edge detection."""
WHITE, GRAY, BLACK = 0, 1, 2
color: dict[str, int] = {n: WHITE for n in self.nodes}
adj: dict[str, list[str]] = {n: [] for n in self.nodes}
for src, dst in self.edges:
adj[src].append(dst)
back_edges: list[tuple[str, str]] = []
def dfs(u: str) -> None:
color[u] = GRAY
for v in adj[u]:
if v not in color:
continue
if color[v] == GRAY:
back_edges.append((u, v))
elif color[v] == WHITE:
dfs(v)
color[u] = BLACK
for n in self.nodes:
if color[n] == WHITE:
dfs(n)
return back_edges
def _break_cycles(self) -> None:
"""Replace back edges with unit-delay source nodes."""
back_edges = self._find_back_edges()
if not back_edges:
return
for src, dst in back_edges:
delay_name = f"_delay_{src}_to_{dst}"
self.edges.remove((src, dst))
# Delay node is a DAG source (no incoming edges) — feeds dst
self.nodes[delay_name] = _UnitDelayNode(name=delay_name)
self.edges.append((delay_name, dst))
self._recurrent_map[delay_name] = src
def _topological_sort(self) -> list[str]:
"""Kahn's algorithm with automatic cycle breaking via delay nodes."""
self._break_cycles()
adj: dict[str, list[str]] = {n: [] for n in self.nodes}
in_deg: dict[str, int] = {n: 0 for n in self.nodes}
for src, dst in self.edges:
adj[src].append(dst)
in_deg[dst] = in_deg.get(dst, 0) + 1
queue = [n for n, d in in_deg.items() if d == 0]
order = []
while queue:
node = queue.pop(0)
order.append(node)
for nxt in adj[node]:
in_deg[nxt] -= 1
if in_deg[nxt] == 0:
queue.append(nxt)
if len(order) != len(self.nodes):
raise ValueError("NIR graph contains a cycle that cannot be broken by delay insertion")
return order
@property
def topo_order(self) -> list[str]:
if self._topo_order is None:
self._topo_order = self._topological_sort()
return self._topo_order
def step(self, inputs: dict[str, np.ndarray]) -> dict[str, np.ndarray]:
"""Execute one timestep through the graph.
Parameters
----------
inputs : dict mapping input node name → input array
Returns
-------
dict mapping output node name → output array
"""
values: dict[str, np.ndarray] = {}
for name in self.topo_order:
node = self.nodes[name]
if name in self.input_nodes:
x = inputs.get(name, np.array([0.0]))
values[name] = node.forward(x)
elif isinstance(node, _UnitDelayNode):
# Delay nodes are sources — forward() returns buffered value
values[name] = node.forward(np.array([0.0]))
else:
predecessors = [src for src, dst in self.edges if dst == name]
if len(predecessors) == 1:
x = values[predecessors[0]]
elif len(predecessors) > 1:
x = sum(values[p] for p in predecessors) # type: ignore[assignment]
else:
x = np.array([0.0])
values[name] = node.forward(x)
# Update delay buffers with this timestep's source values
for delay_name, src_name in self._recurrent_map.items():
if src_name in values:
self.nodes[delay_name].update_buffer(values[src_name])
return {name: values[name] for name in self.output_nodes if name in values}
def run(self, inputs: dict[str, np.ndarray], steps: int = 100) -> dict[str, list[np.ndarray]]:
"""Run the network for multiple timesteps.
Parameters
----------
inputs : dict mapping input node name → input array (constant across steps)
steps : number of timesteps
Returns
-------
dict mapping output node name → list of output arrays per timestep
"""
results: dict[str, list[np.ndarray]] = {n: [] for n in self.output_nodes}
for _ in range(steps):
out = self.step(inputs)
for name, val in out.items():
results[name].append(val.copy())
return results
def reset(self) -> None:
"""Reset all stateful nodes."""
for node in self.nodes.values():
if hasattr(node, "reset"):
node.reset()
def summary(self) -> str:
"""Human-readable network summary."""
lines = [f"SCNetwork: {len(self.nodes)} nodes, {len(self.edges)} edges"]
for name in self.topo_order:
node = self.nodes[name]
lines.append(f" {name}: {type(node).__name__}")
if self._recurrent_map:
lines.append(f" recurrent: {list(self._recurrent_map.values())}")
lines.append(f" inputs: {self.input_nodes}")
lines.append(f" outputs: {self.output_nodes}")
return "\n".join(lines)
|
step(inputs)
Execute one timestep through the graph.
Parameters
inputs : dict mapping input node name → input array
Returns
dict mapping output node name → output array
Source code in src/sc_neurocore/nir_bridge/parser.py
| Python |
|---|
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234 | def step(self, inputs: dict[str, np.ndarray]) -> dict[str, np.ndarray]:
"""Execute one timestep through the graph.
Parameters
----------
inputs : dict mapping input node name → input array
Returns
-------
dict mapping output node name → output array
"""
values: dict[str, np.ndarray] = {}
for name in self.topo_order:
node = self.nodes[name]
if name in self.input_nodes:
x = inputs.get(name, np.array([0.0]))
values[name] = node.forward(x)
elif isinstance(node, _UnitDelayNode):
# Delay nodes are sources — forward() returns buffered value
values[name] = node.forward(np.array([0.0]))
else:
predecessors = [src for src, dst in self.edges if dst == name]
if len(predecessors) == 1:
x = values[predecessors[0]]
elif len(predecessors) > 1:
x = sum(values[p] for p in predecessors) # type: ignore[assignment]
else:
x = np.array([0.0])
values[name] = node.forward(x)
# Update delay buffers with this timestep's source values
for delay_name, src_name in self._recurrent_map.items():
if src_name in values:
self.nodes[delay_name].update_buffer(values[src_name])
return {name: values[name] for name in self.output_nodes if name in values}
|
run(inputs, steps=100)
Run the network for multiple timesteps.
Parameters
inputs : dict mapping input node name → input array (constant across steps)
steps : number of timesteps
Returns
dict mapping output node name → list of output arrays per timestep
Source code in src/sc_neurocore/nir_bridge/parser.py
| Python |
|---|
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253 | def run(self, inputs: dict[str, np.ndarray], steps: int = 100) -> dict[str, list[np.ndarray]]:
"""Run the network for multiple timesteps.
Parameters
----------
inputs : dict mapping input node name → input array (constant across steps)
steps : number of timesteps
Returns
-------
dict mapping output node name → list of output arrays per timestep
"""
results: dict[str, list[np.ndarray]] = {n: [] for n in self.output_nodes}
for _ in range(steps):
out = self.step(inputs)
for name, val in out.items():
results[name].append(val.copy())
return results
|
reset()
Reset all stateful nodes.
Source code in src/sc_neurocore/nir_bridge/parser.py
| Python |
|---|
| def reset(self) -> None:
"""Reset all stateful nodes."""
for node in self.nodes.values():
if hasattr(node, "reset"):
node.reset()
|
summary()
Human-readable network summary.
Source code in src/sc_neurocore/nir_bridge/parser.py
| Python |
|---|
261
262
263
264
265
266
267
268
269
270
271 | def summary(self) -> str:
"""Human-readable network summary."""
lines = [f"SCNetwork: {len(self.nodes)} nodes, {len(self.edges)} edges"]
for name in self.topo_order:
node = self.nodes[name]
lines.append(f" {name}: {type(node).__name__}")
if self._recurrent_map:
lines.append(f" recurrent: {list(self._recurrent_map.values())}")
lines.append(f" inputs: {self.input_nodes}")
lines.append(f" outputs: {self.output_nodes}")
return "\n".join(lines)
|
SCSubgraphNode
dataclass
Executable wrapper for a nested NIR subgraph (single I/O port).
Source code in src/sc_neurocore/nir_bridge/parser.py
| Python |
|---|
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67 | @dataclass
class SCSubgraphNode:
"""Executable wrapper for a nested NIR subgraph (single I/O port)."""
name: str
network: SCNetwork
def __post_init__(self) -> None:
if len(self.network.input_nodes) != 1 or len(self.network.output_nodes) != 1:
raise ValueError("Nested NIRGraph nodes must expose exactly one input and one output")
def forward(self, x: np.ndarray) -> np.ndarray:
outputs = self.network.step({self.network.input_nodes[0]: np.atleast_1d(np.asarray(x))})
return outputs[self.network.output_nodes[0]]
def reset(self) -> None:
self.network.reset()
|
SCMultiPortSubgraphNode
dataclass
Executable wrapper for a nested NIR subgraph with multiple I/O ports.
Supports modular architectures where subgraphs expose multiple named
inputs and outputs (e.g., encoder-decoder, skip connections).
Source code in src/sc_neurocore/nir_bridge/parser.py
| Python |
|---|
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104 | @dataclass
class SCMultiPortSubgraphNode:
"""Executable wrapper for a nested NIR subgraph with multiple I/O ports.
Supports modular architectures where subgraphs expose multiple named
inputs and outputs (e.g., encoder-decoder, skip connections).
"""
name: str
network: SCNetwork
def __post_init__(self) -> None:
if not self.network.input_nodes or not self.network.output_nodes:
raise ValueError("Multi-port subgraph must have at least one input and one output")
@property
def input_ports(self) -> list[str]:
return self.network.input_nodes
@property
def output_ports(self) -> list[str]:
return self.network.output_nodes
def forward(self, x: np.ndarray) -> np.ndarray:
"""Single-input convenience: feeds x to first input, returns first output."""
inputs = {self.network.input_nodes[0]: np.atleast_1d(np.asarray(x))}
outputs = self.network.step(inputs)
return outputs[self.network.output_nodes[0]]
def forward_multi(self, inputs: dict[str, np.ndarray]) -> dict[str, np.ndarray]:
"""Multi-port forward: provide named inputs, get named outputs."""
return self.network.step(inputs)
def reset(self) -> None:
self.network.reset()
|
forward(x)
Single-input convenience: feeds x to first input, returns first output.
Source code in src/sc_neurocore/nir_bridge/parser.py
| Python |
|---|
| def forward(self, x: np.ndarray) -> np.ndarray:
"""Single-input convenience: feeds x to first input, returns first output."""
inputs = {self.network.input_nodes[0]: np.atleast_1d(np.asarray(x))}
outputs = self.network.step(inputs)
return outputs[self.network.output_nodes[0]]
|
forward_multi(inputs)
Multi-port forward: provide named inputs, get named outputs.
Source code in src/sc_neurocore/nir_bridge/parser.py
| Python |
|---|
| def forward_multi(self, inputs: dict[str, np.ndarray]) -> dict[str, np.ndarray]:
"""Multi-port forward: provide named inputs, get named outputs."""
return self.network.step(inputs)
|
from_nir(source, dt=1.0, reset_mode='reset')
Convert a NIR graph to an executable SC-NeuroCore network.
Parameters
source : nir.NIRGraph or str or Path
NIR graph object, or path to a .nir file.
dt : float
Timestep for leaky integrator dynamics.
reset_mode : str
Spike reset mechanism: "reset" (v = v_reset, NIR spec default)
or "subtract" (v = v - v_threshold, used by snnTorch).
Returns
SCNetwork
Executable network with topologically sorted forward pass.
Source code in src/sc_neurocore/nir_bridge/parser.py
| Python |
|---|
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302 | def from_nir(source, dt: float = 1.0, reset_mode: str = "reset") -> SCNetwork: # type: ignore[no-untyped-def]
"""Convert a NIR graph to an executable SC-NeuroCore network.
Parameters
----------
source : nir.NIRGraph or str or Path
NIR graph object, or path to a .nir file.
dt : float
Timestep for leaky integrator dynamics.
reset_mode : str
Spike reset mechanism: "reset" (v = v_reset, NIR spec default)
or "subtract" (v = v - v_threshold, used by snnTorch).
Returns
-------
SCNetwork
Executable network with topologically sorted forward pass.
"""
_validate_import_options(dt, reset_mode)
if isinstance(source, (str, Path)):
graph = _read_nir_file(source)
elif isinstance(source, nir.NIRGraph):
graph = source
else:
raise TypeError(f"Expected NIRGraph or path, got {type(source)}")
_validate_nir_graph_boundary(graph)
return _parse_graph(graph, dt=dt, reset_mode=reset_mode)
|
Recurrent Edge Handling
Graphs with cycles (feedback connections) are automatically handled by
inserting unit-delay nodes on back edges. The delay node buffers the
previous timestep's value, breaking algebraic loops while preserving
temporal dynamics. See _UnitDelayNode.
Multi-Port Subgraphs
Nested NIR graphs with multiple inputs/outputs use SCMultiPortSubgraphNode,
which exposes forward_multi(inputs_dict) → outputs_dict for named I/O ports.
Import Boundary Validation
from_nir() accepts a nir.NIRGraph, string path, or Path. File reads are
wrapped as ValueError on malformed or unreadable NIR payloads. Parsed graphs
must expose mapping-like nodes and sequence-like edges, all node names and edge
endpoints must be non-empty strings, and every edge endpoint must reference an
existing node before the graph is lowered.
Node Map
sc_neurocore.nir_bridge.node_map
NODE_MAP = {nir.Input: lambda name, node, **kw: SCInputNode(name=name, shape=(tuple((int(x)) for x in (next(iter(node.input_type.values())).flatten())) if node.input_type else ())), nir.Output: lambda name, node, **kw: SCOutputNode(name=name, shape=(tuple((int(x)) for x in (next(iter(node.output_type.values())).flatten())) if node.output_type else ())), nir.LIF: lambda name, node, **kw: SCLIFNode.from_nir(name, node, dt=(kw.get('dt', 1.0)), reset_mode=(kw.get('reset_mode', 'reset'))), nir.IF: lambda name, node, **kw: SCIFNode.from_nir(name, node, dt=(kw.get('dt', 1.0)), reset_mode=(kw.get('reset_mode', 'reset'))), nir.LI: lambda name, node, **kw: SCLINode.from_nir(name, node, dt=(kw.get('dt', 1.0))), nir.I: lambda name, node, **kw: SCIntegratorNode.from_nir(name, node, dt=(kw.get('dt', 1.0))), nir.Affine: lambda name, node, **kw: SCAffineNode.from_nir(name, node), nir.Linear: lambda name, node, **kw: SCLinearNode.from_nir(name, node), nir.Scale: lambda name, node, **kw: SCScaleNode.from_nir(name, node), nir.Threshold: lambda name, node, **kw: SCThresholdNode.from_nir(name, node), nir.Flatten: lambda name, node, **kw: SCFlattenNode.from_nir(name, node), nir.Delay: lambda name, node, **kw: SCDelayNode.from_nir(name, node, dt=(kw.get('dt', 1.0))), nir.CubaLIF: lambda name, node, **kw: SCCubaLIFNode.from_nir(name, node, dt=(kw.get('dt', 1.0)), reset_mode=(kw.get('reset_mode', 'reset'))), nir.CubaLI: lambda name, node, **kw: SCCubaLINode.from_nir(name, node, dt=(kw.get('dt', 1.0))), nir.SumPool2d: lambda name, node, **kw: SCSumPool2dNode.from_nir(name, node), nir.AvgPool2d: lambda name, node, **kw: SCAvgPool2dNode.from_nir(name, node), nir.Conv1d: lambda name, node, **kw: SCConv1dNode.from_nir(name, node), nir.Conv2d: lambda name, node, **kw: SCConv2dNode.from_nir(name, node)}
module-attribute
SCLIFNode
dataclass
LIF neuron mapped from NIR LIF primitive.
NIR LIF: taudv/dt = (v_leak - v) + RI, spike when v > v_threshold
Euler: v += ((v_leak - v) + R*I) * dt/tau
Source code in src/sc_neurocore/nir_bridge/node_map.py
| Python |
|---|
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122 | @dataclass
class SCLIFNode:
"""LIF neuron mapped from NIR LIF primitive.
NIR LIF: tau*dv/dt = (v_leak - v) + R*I, spike when v > v_threshold
Euler: v += ((v_leak - v) + R*I) * dt/tau
"""
name: str
n_neurons: int
tau: np.ndarray
r: np.ndarray
v_leak: np.ndarray
v_threshold: np.ndarray
v_reset: np.ndarray
v: np.ndarray | None = None
dt: float = 1.0
reset_mode: str = "reset"
@classmethod
def from_nir(
cls,
name: str,
node: nir.LIF,
dt: float = 1.0,
reset_mode: str = "reset",
) -> SCLIFNode:
tau = np.atleast_1d(node.tau).flatten()
r = np.atleast_1d(node.r).flatten()
v_leak = np.atleast_1d(node.v_leak).flatten()
v_threshold = np.atleast_1d(node.v_threshold).flatten()
v_reset = (
np.atleast_1d(node.v_reset).flatten()
if node.v_reset is not None
else np.zeros_like(v_threshold)
)
return cls(
name=name,
n_neurons=len(tau),
tau=tau,
r=r,
v_leak=v_leak,
v_threshold=v_threshold,
v_reset=v_reset,
dt=dt,
reset_mode=reset_mode,
)
def __post_init__(self) -> None:
if self.v is None:
self.v = self.v_leak.copy()
def _broadcast_to(self, size: int) -> None:
self.n_neurons = size
for attr in ("tau", "r", "v_leak", "v_threshold", "v_reset"):
arr = getattr(self, attr)
if len(arr) == 1 and size > 1:
setattr(self, attr, np.broadcast_to(arr, (size,)).copy())
assert self.v is not None
self.v = np.broadcast_to(self.v, (size,)).copy()
def forward(self, x: np.ndarray) -> np.ndarray:
x = np.atleast_1d(x).flatten()
if self.n_neurons == 1 and len(x) > 1:
self._broadcast_to(len(x))
x = x[: self.n_neurons]
dv = (self.v_leak - self.v + self.r * x) * (self.dt / self.tau)
self.v += dv
spikes = (self.v > self.v_threshold).astype(np.float64)
if self.reset_mode == "subtract":
self.v = np.where(spikes > 0, self.v - self.v_threshold, self.v)
else:
self.v = np.where(spikes > 0, self.v_reset, self.v)
return spikes
def reset(self) -> None:
self.v = self.v_leak.copy()
|
SCIFNode
dataclass
IF neuron — integrator with threshold, no leak.
NIR IF: dv/dt = RI, spike when v > v_threshold
Euler: v += RI*dt
Source code in src/sc_neurocore/nir_bridge/node_map.py
| Python |
|---|
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191 | @dataclass
class SCIFNode:
"""IF neuron — integrator with threshold, no leak.
NIR IF: dv/dt = R*I, spike when v > v_threshold
Euler: v += R*I*dt
"""
name: str
n_neurons: int
r: np.ndarray
v_threshold: np.ndarray
v_reset: np.ndarray
v: np.ndarray | None = None
dt: float = 1.0
reset_mode: str = "reset"
@classmethod
def from_nir(
cls,
name: str,
node: nir.IF,
dt: float = 1.0,
reset_mode: str = "reset",
) -> SCIFNode:
r = np.atleast_1d(node.r).flatten()
v_threshold = np.atleast_1d(node.v_threshold).flatten()
v_reset = (
np.atleast_1d(node.v_reset).flatten() if node.v_reset is not None else np.zeros_like(r)
)
return cls(
name=name,
n_neurons=len(r),
r=r,
v_threshold=v_threshold,
v_reset=v_reset,
dt=dt,
reset_mode=reset_mode,
)
def __post_init__(self) -> None:
if self.v is None:
self.v = np.zeros(self.n_neurons)
def _broadcast_to(self, size: int) -> None:
self.n_neurons = size
for attr in ("r", "v_threshold", "v_reset"):
arr = getattr(self, attr)
if len(arr) == 1 and size > 1:
setattr(self, attr, np.broadcast_to(arr, (size,)).copy())
self.v = np.zeros(size)
def forward(self, x: np.ndarray) -> np.ndarray:
x = np.atleast_1d(x).flatten()
if self.n_neurons == 1 and len(x) > 1:
self._broadcast_to(len(x))
x = x[: self.n_neurons]
self.v += self.r * x * self.dt
spikes = (self.v > self.v_threshold).astype(np.float64)
if self.reset_mode == "subtract":
self.v = np.where(spikes > 0, self.v - self.v_threshold, self.v)
else:
self.v = np.where(spikes > 0, self.v_reset, self.v)
return spikes
def reset(self) -> None:
self.v = np.zeros(self.n_neurons)
|
SCLINode
dataclass
Leaky integrator — LIF without threshold.
NIR LI: taudv/dt = (v_leak - v) + RI
Source code in src/sc_neurocore/nir_bridge/node_map.py
| Python |
|---|
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240 | @dataclass
class SCLINode:
"""Leaky integrator — LIF without threshold.
NIR LI: tau*dv/dt = (v_leak - v) + R*I
"""
name: str
n_neurons: int
tau: np.ndarray
r: np.ndarray
v_leak: np.ndarray
v: np.ndarray | None = None
dt: float = 1.0
@classmethod
def from_nir(cls, name: str, node: nir.LI, dt: float = 1.0) -> SCLINode:
tau = np.atleast_1d(node.tau).flatten()
r = np.atleast_1d(node.r).flatten()
v_leak = np.atleast_1d(node.v_leak).flatten()
return cls(name=name, n_neurons=len(tau), tau=tau, r=r, v_leak=v_leak, dt=dt)
def __post_init__(self) -> None:
if self.v is None:
self.v = self.v_leak.copy()
def _broadcast_to(self, size: int) -> None:
self.n_neurons = size
for attr in ("tau", "r", "v_leak"):
arr = getattr(self, attr)
if len(arr) == 1 and size > 1:
setattr(self, attr, np.broadcast_to(arr, (size,)).copy())
assert self.v is not None
self.v = np.broadcast_to(self.v, (size,)).copy()
def forward(self, x: np.ndarray) -> np.ndarray:
assert self.v is not None
x = np.atleast_1d(x).flatten()
if self.n_neurons == 1 and len(x) > 1:
self._broadcast_to(len(x))
x = x[: self.n_neurons]
dv = (self.v_leak - self.v + self.r * x) * (self.dt / self.tau)
self.v += dv
return self.v.copy()
def reset(self) -> None:
self.v = self.v_leak.copy()
|
SCIntegratorNode
dataclass
Pure integrator: dv/dt = RI (no leak, no threshold). Euler: v += RI*dt
Source code in src/sc_neurocore/nir_bridge/node_map.py
| Python |
|---|
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365 | @dataclass
class SCIntegratorNode:
"""Pure integrator: dv/dt = R*I (no leak, no threshold). Euler: v += R*I*dt"""
name: str
r: np.ndarray
v: np.ndarray | None = None
dt: float = 1.0
@classmethod
def from_nir(cls, name: str, node: nir.I, dt: float = 1.0) -> SCIntegratorNode:
r = np.atleast_1d(node.r).flatten()
return cls(name=name, r=r, dt=dt)
def __post_init__(self) -> None:
if self.v is None:
self.v = np.zeros_like(self.r)
def forward(self, x: np.ndarray) -> np.ndarray:
x = np.atleast_1d(x).flatten()[: len(self.r)]
self.v += self.r * x * self.dt
return self.v.copy()
def reset(self) -> None:
self.v = np.zeros_like(self.r)
|
SCAffineNode
dataclass
Dense linear transform with bias: y = Wx + b
Source code in src/sc_neurocore/nir_bridge/node_map.py
| Python |
|---|
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257 | @dataclass
class SCAffineNode:
"""Dense linear transform with bias: y = Wx + b"""
name: str
weight: np.ndarray
bias: np.ndarray
@classmethod
def from_nir(cls, name: str, node: nir.Affine) -> SCAffineNode:
return cls(name=name, weight=node.weight, bias=node.bias)
def forward(self, x: np.ndarray) -> np.ndarray:
x = np.atleast_1d(x).flatten()
return self.weight @ x + self.bias
|
SCLinearNode
dataclass
Matrix multiply without bias: y = Wx
Source code in src/sc_neurocore/nir_bridge/node_map.py
| Python |
|---|
260
261
262
263
264
265
266
267
268
269
270
271
272
273 | @dataclass
class SCLinearNode:
"""Matrix multiply without bias: y = Wx"""
name: str
weight: np.ndarray
@classmethod
def from_nir(cls, name: str, node: nir.Linear) -> SCLinearNode:
return cls(name=name, weight=node.weight)
def forward(self, x: np.ndarray) -> np.ndarray:
x = np.atleast_1d(x).flatten()
return self.weight @ x
|
SCScaleNode
dataclass
Element-wise scaling: y = s * x
Source code in src/sc_neurocore/nir_bridge/node_map.py
| Python |
|---|
276
277
278
279
280
281
282
283
284
285
286
287
288 | @dataclass
class SCScaleNode:
"""Element-wise scaling: y = s * x"""
name: str
scale: np.ndarray
@classmethod
def from_nir(cls, name: str, node: nir.Scale) -> SCScaleNode:
return cls(name=name, scale=node.scale)
def forward(self, x: np.ndarray) -> np.ndarray:
return self.scale * x
|
SCThresholdNode
dataclass
Spike threshold: y = 1 if x >= threshold else 0
Source code in src/sc_neurocore/nir_bridge/node_map.py
| Python |
|---|
291
292
293
294
295
296
297
298
299
300
301
302
303 | @dataclass
class SCThresholdNode:
"""Spike threshold: y = 1 if x >= threshold else 0"""
name: str
threshold: np.ndarray
@classmethod
def from_nir(cls, name: str, node: nir.Threshold) -> SCThresholdNode:
return cls(name=name, threshold=node.threshold)
def forward(self, x: np.ndarray) -> np.ndarray:
return (x >= self.threshold).astype(np.float64)
|
SCFlattenNode
dataclass
Reshape tensor — flatten dimensions.
Source code in src/sc_neurocore/nir_bridge/node_map.py
| Python |
|---|
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338 | @dataclass
class SCFlattenNode:
"""Reshape tensor — flatten dimensions."""
name: str
start_dim: int
end_dim: int
@classmethod
def from_nir(cls, name: str, node: nir.Flatten) -> SCFlattenNode:
return cls(name=name, start_dim=node.start_dim, end_dim=node.end_dim)
def forward(self, x: np.ndarray) -> np.ndarray:
x = np.asarray(x)
if x.ndim == 0:
if self.start_dim not in (0, -1) or self.end_dim not in (0, -1):
raise ValueError(
f"Invalid flatten dims {self.start_dim}:{self.end_dim} for shape {x.shape}"
)
return x.reshape(1)
start = self.start_dim if self.start_dim >= 0 else x.ndim + self.start_dim
end = self.end_dim if self.end_dim >= 0 else x.ndim + self.end_dim
if not 0 <= start < x.ndim or not 0 <= end < x.ndim or start > end:
raise ValueError(
f"Invalid flatten dims {self.start_dim}:{self.end_dim} for shape {x.shape}"
)
if start == end:
return x.copy()
merged = int(np.prod(x.shape[start : end + 1], dtype=np.int64))
new_shape = x.shape[:start] + (merged,) + x.shape[end + 1 :]
return x.reshape(new_shape)
|
Graph entry point — passes input through unchanged.
Source code in src/sc_neurocore/nir_bridge/node_map.py
| Python |
|---|
22
23
24
25
26
27
28
29
30 | @dataclass
class SCInputNode:
"""Graph entry point — passes input through unchanged."""
name: str
shape: tuple
def forward(self, x: np.ndarray) -> np.ndarray:
return x
|
SCOutputNode
dataclass
Graph exit point — collects output.
Source code in src/sc_neurocore/nir_bridge/node_map.py
| Python |
|---|
33
34
35
36
37
38
39
40
41
42
43 | @dataclass
class SCOutputNode:
"""Graph exit point — collects output."""
name: str
shape: tuple
last_output: np.ndarray | None = None
def forward(self, x: np.ndarray) -> np.ndarray:
self.last_output = x
return x
|
SCDelayNode
dataclass
Temporal delay: output = input(t - delay).
NIR Delay: I(t - tau). Implemented as a circular buffer per element.
Delay values are rounded to integer timesteps.
Source code in src/sc_neurocore/nir_bridge/node_map.py
| Python |
|---|
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406 | @dataclass
class SCDelayNode:
"""Temporal delay: output = input(t - delay).
NIR Delay: I(t - tau). Implemented as a circular buffer per element.
Delay values are rounded to integer timesteps.
"""
name: str
delay_steps: np.ndarray
delay_time: np.ndarray | None = None # original physical time for lossless export
_buffers: list[list[np.ndarray]] | None = None
@classmethod
def from_nir(cls, name: str, node: nir.Delay, dt: float = 1.0) -> SCDelayNode:
delay = np.atleast_1d(node.delay).flatten()
steps = np.round(delay / dt).astype(int)
return cls(name=name, delay_steps=steps, delay_time=delay.copy())
def __post_init__(self) -> None:
if self._buffers is None:
self._buffers = [[np.zeros(1) for _ in range(int(d))] for d in self.delay_steps]
def forward(self, x: np.ndarray) -> np.ndarray:
assert self._buffers is not None
x = np.atleast_1d(x).flatten()
out = np.zeros(len(self.delay_steps))
for i, buf in enumerate(self._buffers):
xi = float(x[i]) if i < len(x) else 0.0
if len(buf) == 0:
out[i] = xi # zero-delay passthrough
else:
out[i] = buf[0][0]
buf.append(np.array([xi]))
buf.pop(0)
return out
def reset(self) -> None:
self._buffers = [[np.zeros(1) for _ in range(int(d))] for d in self.delay_steps]
|
SCCubaLIFNode
dataclass
Current-based LIF with synaptic filter.
tau_syn * dI_syn/dt = -I_syn + w_in * I
tau_mem * dv/dt = (v_leak - v) + R * I_syn
spike when v > v_threshold, reset to v_reset
Source code in src/sc_neurocore/nir_bridge/node_map.py
| Python |
|---|
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501 | @dataclass
class SCCubaLIFNode:
"""Current-based LIF with synaptic filter.
NIR CubaLIF: tau_syn * dI_syn/dt = -I_syn + w_in * I
tau_mem * dv/dt = (v_leak - v) + R * I_syn
spike when v > v_threshold, reset to v_reset
"""
name: str
n_neurons: int
tau_syn: np.ndarray
tau_mem: np.ndarray
r: np.ndarray
v_leak: np.ndarray
v_threshold: np.ndarray
v_reset: np.ndarray
w_in: np.ndarray
v: np.ndarray | None = None
i_syn: np.ndarray | None = None
dt: float = 1.0
reset_mode: str = "reset"
@classmethod
def from_nir(
cls,
name: str,
node: nir.CubaLIF,
dt: float = 1.0,
reset_mode: str = "reset",
) -> SCCubaLIFNode:
tau_syn = np.atleast_1d(node.tau_syn).flatten()
tau_mem = np.atleast_1d(node.tau_mem).flatten()
r = np.atleast_1d(node.r).flatten()
v_leak = np.atleast_1d(node.v_leak).flatten()
v_threshold = np.atleast_1d(node.v_threshold).flatten()
v_reset = (
np.atleast_1d(node.v_reset).flatten()
if node.v_reset is not None
else np.zeros_like(v_threshold)
)
w_in = np.atleast_1d(node.w_in).flatten()
return cls(
name=name,
n_neurons=len(tau_mem),
tau_syn=tau_syn,
tau_mem=tau_mem,
r=r,
v_leak=v_leak,
v_threshold=v_threshold,
v_reset=v_reset,
w_in=w_in,
dt=dt,
reset_mode=reset_mode,
)
def __post_init__(self) -> None:
if self.v is None:
self.v = self.v_leak.copy()
if self.i_syn is None:
self.i_syn = np.zeros(self.n_neurons)
def _broadcast_to(self, size: int) -> None:
"""Broadcast scalar params to match actual input size."""
self.n_neurons = size
for attr in ("tau_syn", "tau_mem", "r", "v_leak", "v_threshold", "v_reset", "w_in"):
arr = getattr(self, attr)
if len(arr) == 1 and size > 1:
setattr(self, attr, np.broadcast_to(arr, (size,)).copy())
assert self.v is not None
self.v = np.broadcast_to(self.v, (size,)).copy()
self.i_syn = np.zeros(size)
def forward(self, x: np.ndarray) -> np.ndarray:
assert self.v is not None and self.i_syn is not None
x = np.atleast_1d(x).flatten()
if self.n_neurons == 1 and len(x) > 1:
self._broadcast_to(len(x))
x = x[: self.n_neurons]
di = (-self.i_syn + self.w_in * x) * (self.dt / self.tau_syn)
self.i_syn += di
dv = (self.v_leak - self.v + self.r * self.i_syn) * (self.dt / self.tau_mem)
self.v += dv
spikes = (self.v > self.v_threshold).astype(np.float64)
if self.reset_mode == "subtract":
self.v = np.where(spikes > 0, self.v - self.v_threshold, self.v)
else:
self.v = np.where(spikes > 0, self.v_reset, self.v)
return spikes
def reset(self) -> None:
self.v = self.v_leak.copy()
self.i_syn = np.zeros(self.n_neurons)
|
SCCubaLINode
dataclass
Current-based leaky integrator (CubaLIF without threshold).
tau_syn * dI_syn/dt = -I_syn + w_in * I
tau_mem * dv/dt = (v_leak - v) + R * I_syn
Source code in src/sc_neurocore/nir_bridge/node_map.py
| Python |
|---|
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571 | @dataclass
class SCCubaLINode:
"""Current-based leaky integrator (CubaLIF without threshold).
NIR CubaLI: tau_syn * dI_syn/dt = -I_syn + w_in * I
tau_mem * dv/dt = (v_leak - v) + R * I_syn
"""
name: str
n_neurons: int
tau_syn: np.ndarray
tau_mem: np.ndarray
r: np.ndarray
v_leak: np.ndarray
w_in: np.ndarray
v: np.ndarray | None = None
i_syn: np.ndarray | None = None
dt: float = 1.0
@classmethod
def from_nir(cls, name: str, node: nir.CubaLI, dt: float = 1.0) -> SCCubaLINode:
tau_syn = np.atleast_1d(node.tau_syn).flatten()
tau_mem = np.atleast_1d(node.tau_mem).flatten()
r = np.atleast_1d(node.r).flatten()
v_leak = np.atleast_1d(node.v_leak).flatten()
w_in = np.atleast_1d(node.w_in).flatten()
return cls(
name=name,
n_neurons=len(tau_mem),
tau_syn=tau_syn,
tau_mem=tau_mem,
r=r,
v_leak=v_leak,
w_in=w_in,
dt=dt,
)
def __post_init__(self) -> None:
if self.v is None:
self.v = self.v_leak.copy()
if self.i_syn is None:
self.i_syn = np.zeros(self.n_neurons)
def _broadcast_to(self, size: int) -> None:
self.n_neurons = size
for attr in ("tau_syn", "tau_mem", "r", "v_leak", "w_in"):
arr = getattr(self, attr)
if len(arr) == 1 and size > 1:
setattr(self, attr, np.broadcast_to(arr, (size,)).copy())
assert self.v is not None
self.v = np.broadcast_to(self.v, (size,)).copy()
self.i_syn = np.zeros(size)
def forward(self, x: np.ndarray) -> np.ndarray:
assert self.v is not None and self.i_syn is not None
x = np.atleast_1d(x).flatten()
if self.n_neurons == 1 and len(x) > 1:
self._broadcast_to(len(x))
x = x[: self.n_neurons]
di = (-self.i_syn + self.w_in * x) * (self.dt / self.tau_syn)
self.i_syn += di
dv = (self.v_leak - self.v + self.r * self.i_syn) * (self.dt / self.tau_mem)
self.v += dv
return self.v.copy()
def reset(self) -> None:
self.v = self.v_leak.copy()
self.i_syn = np.zeros(self.n_neurons)
|
SCConv1dNode
dataclass
1D convolution: y = conv1d(x, weight) + bias.
Source code in src/sc_neurocore/nir_bridge/node_map.py
| Python |
|---|
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699 | @dataclass
class SCConv1dNode:
"""1D convolution: y = conv1d(x, weight) + bias."""
name: str
weight: np.ndarray
bias: np.ndarray
stride: int
padding: int
dilation: int
groups: int
input_shape: int | None = None
@classmethod
def from_nir(cls, name: str, node: nir.Conv1d) -> SCConv1dNode:
if isinstance(node.padding, str):
raise NotImplementedError(
f"String padding '{node.padding}' not supported; use integer padding"
)
padding = int(node.padding)
return cls(
name=name,
weight=node.weight,
bias=node.bias if node.bias is not None else np.zeros(node.weight.shape[0]),
stride=node.stride,
padding=padding,
dilation=node.dilation,
groups=node.groups,
input_shape=getattr(node, "input_shape", None),
)
def forward(self, x: np.ndarray) -> np.ndarray:
# x: (C_in, L) or (L,)
if x.ndim == 1:
x = x[np.newaxis, :]
c_out, c_in_per_group, k = self.weight.shape
c_in, length = x.shape
if self.padding > 0:
x = np.pad(x, ((0, 0), (self.padding, self.padding)), mode="constant")
length = x.shape[1]
out_len = (length - self.dilation * (k - 1) - 1) // self.stride + 1
out = np.zeros((c_out, out_len))
for o in range(c_out):
g = o // (c_out // self.groups)
c_start = g * c_in_per_group
for l in range(out_len):
val = 0.0
for ci in range(c_in_per_group):
for ki in range(k):
idx = l * self.stride + ki * self.dilation
if 0 <= idx < x.shape[1]:
val += self.weight[o, ci, ki] * x[c_start + ci, idx]
out[o, l] = val + self.bias[o]
return out.squeeze()
|
SCConv2dNode
dataclass
2D convolution: y = conv2d(x, weight) + bias.
Source code in src/sc_neurocore/nir_bridge/node_map.py
| Python |
|---|
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766 | @dataclass
class SCConv2dNode:
"""2D convolution: y = conv2d(x, weight) + bias."""
name: str
weight: np.ndarray
bias: np.ndarray
stride: tuple[int, int]
padding: tuple[int, int]
dilation: tuple[int, int]
groups: int
input_shape: tuple[int, int] | None = None
@classmethod
def from_nir(cls, name: str, node: nir.Conv2d) -> SCConv2dNode:
stride = node.stride if isinstance(node.stride, tuple) else (node.stride, node.stride)
padding = node.padding if isinstance(node.padding, tuple) else (node.padding, node.padding)
if isinstance(padding[0], str):
raise NotImplementedError(
f"String padding '{padding[0]}' not supported; use integer padding"
)
dilation = (
node.dilation if isinstance(node.dilation, tuple) else (node.dilation, node.dilation)
)
return cls(
name=name,
weight=node.weight,
bias=node.bias if node.bias is not None else np.zeros(node.weight.shape[0]),
stride=stride,
padding=padding,
dilation=dilation,
groups=node.groups,
input_shape=getattr(node, "input_shape", None),
)
def forward(self, x: np.ndarray) -> np.ndarray:
# x: (C_in, H, W) or (H, W)
if x.ndim == 2:
x = x[np.newaxis, :, :]
c_out, c_in_per_group, kh, kw = self.weight.shape
c_in, h, w = x.shape
ph, pw = self.padding
if ph > 0 or pw > 0:
x = np.pad(x, ((0, 0), (ph, ph), (pw, pw)), mode="constant")
h, w = x.shape[1], x.shape[2]
sh, sw = self.stride
dh, dw = self.dilation
oh = (h - dh * (kh - 1) - 1) // sh + 1
ow = (w - dw * (kw - 1) - 1) // sw + 1
out = np.zeros((c_out, oh, ow))
for o in range(c_out):
g = o // (c_out // self.groups)
c_start = g * c_in_per_group
for i in range(oh):
for j in range(ow):
val = 0.0
for ci in range(c_in_per_group):
for ki in range(kh):
for kj in range(kw):
ii = i * sh + ki * dh
jj = j * sw + kj * dw
if 0 <= ii < h and 0 <= jj < w:
val += self.weight[o, ci, ki, kj] * x[c_start + ci, ii, jj]
out[o, i, j] = val + self.bias[o]
return out.squeeze()
|
SCSumPool2dNode
dataclass
2D sum pooling: sum over spatial kernel windows.
Source code in src/sc_neurocore/nir_bridge/node_map.py
| Python |
|---|
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612 | @dataclass
class SCSumPool2dNode:
"""2D sum pooling: sum over spatial kernel windows."""
name: str
kernel_size: tuple[int, int]
stride: tuple[int, int]
padding: tuple[int, int]
@classmethod
def from_nir(cls, name: str, node: nir.SumPool2d) -> SCSumPool2dNode:
ks_raw = tuple(int(x) for x in np.atleast_1d(node.kernel_size).flatten()[:2])
st_raw = tuple(int(x) for x in np.atleast_1d(node.stride).flatten()[:2])
pad_raw = tuple(int(x) for x in np.atleast_1d(node.padding).flatten()[:2])
ks = (ks_raw[0], ks_raw[0]) if len(ks_raw) == 1 else (ks_raw[0], ks_raw[1])
st = (st_raw[0], st_raw[0]) if len(st_raw) == 1 else (st_raw[0], st_raw[1])
pad = (pad_raw[0], pad_raw[0]) if len(pad_raw) == 1 else (pad_raw[0], pad_raw[1])
return cls(name=name, kernel_size=ks, stride=st, padding=pad)
def forward(self, x: np.ndarray) -> np.ndarray:
if x.ndim < 2:
return x
# Expect (C, H, W) or (H, W)
if x.ndim == 2:
x = x[np.newaxis, :, :]
c, h, w = x.shape
ph, pw = self.padding
if ph > 0 or pw > 0:
x = np.pad(x, ((0, 0), (ph, ph), (pw, pw)), mode="constant")
h, w = x.shape[1], x.shape[2]
kh, kw = self.kernel_size
sh, sw = self.stride
oh = (h - kh) // sh + 1
ow = (w - kw) // sw + 1
out = np.zeros((c, oh, ow))
for i in range(oh):
for j in range(ow):
out[:, i, j] = x[:, i * sh : i * sh + kh, j * sw : j * sw + kw].sum(axis=(1, 2))
return out.squeeze()
|
SCAvgPool2dNode
dataclass
2D average pooling: SumPool / kernel_area.
Source code in src/sc_neurocore/nir_bridge/node_map.py
| Python |
|---|
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643 | @dataclass
class SCAvgPool2dNode:
"""2D average pooling: SumPool / kernel_area."""
name: str
kernel_size: tuple[int, int]
stride: tuple[int, int]
padding: tuple[int, int]
@classmethod
def from_nir(cls, name: str, node: nir.AvgPool2d) -> SCAvgPool2dNode:
ks_raw = tuple(int(x) for x in np.atleast_1d(node.kernel_size).flatten()[:2])
st_raw = tuple(int(x) for x in np.atleast_1d(node.stride).flatten()[:2])
pad_raw = tuple(int(x) for x in np.atleast_1d(node.padding).flatten()[:2])
ks = (ks_raw[0], ks_raw[0]) if len(ks_raw) == 1 else (ks_raw[0], ks_raw[1])
st = (st_raw[0], st_raw[0]) if len(st_raw) == 1 else (st_raw[0], st_raw[1])
pad = (pad_raw[0], pad_raw[0]) if len(pad_raw) == 1 else (pad_raw[0], pad_raw[1])
return cls(name=name, kernel_size=ks, stride=st, padding=pad)
def forward(self, x: np.ndarray) -> np.ndarray:
sum_node = SCSumPool2dNode(
name=self.name + "_sum",
kernel_size=self.kernel_size,
stride=self.stride,
padding=self.padding,
)
summed = sum_node.forward(x)
area = self.kernel_size[0] * self.kernel_size[1]
return summed / area
|
map_node(name, node, **kwargs)
Convert a single NIR node to its SC-NeuroCore equivalent.
Source code in src/sc_neurocore/nir_bridge/node_map.py
| Python |
|---|
808
809
810
811
812
813
814
815 | def map_node(name: str, node: nir.NIRNode, **kwargs: Any) -> Any:
"""Convert a single NIR node to its SC-NeuroCore equivalent."""
factory = NODE_MAP.get(type(node))
if factory is None:
raise NotImplementedError(
f"NIR node type {type(node).__name__} not yet supported (node: {name!r})"
)
return factory(name, node, **kwargs)
|
Export
sc_neurocore.nir_bridge.export
to_nir(network, path=None)
Export an SC-NeuroCore SCNetwork to NIR format.
Parameters
network : SCNetwork
The network to export.
path : str or Path, optional
If provided, write the NIR graph to this file.
Returns
nir.NIRGraph
Source code in src/sc_neurocore/nir_bridge/export.py
| Python |
|---|
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194 | def to_nir(network, path: str | Path | None = None) -> nir.NIRGraph: # type: ignore[no-untyped-def]
"""Export an SC-NeuroCore SCNetwork to NIR format.
Parameters
----------
network : SCNetwork
The network to export.
path : str or Path, optional
If provided, write the NIR graph to this file.
Returns
-------
nir.NIRGraph
"""
from .parser import SCMultiPortSubgraphNode, SCNetwork, SCSubgraphNode, _UnitDelayNode
if not isinstance(network, SCNetwork):
raise TypeError(f"Expected SCNetwork, got {type(network)}")
# Ensure topo_order has been computed (triggers delay insertion)
_ = network.topo_order
nodes = {}
edges = list(network.edges)
for name, node in network.nodes.items():
# Skip internal delay nodes — reconstruct as direct recurrent edges
if isinstance(node, _UnitDelayNode):
continue
# Recursively export subgraphs
if isinstance(node, (SCSubgraphNode, SCMultiPortSubgraphNode)):
nodes[name] = to_nir(node.network)
continue
nir_node = _node_to_nir(name, node)
if nir_node is None:
raise ValueError(f"Cannot export node {name!r} of type {type(node).__name__} to NIR")
nodes[name] = nir_node
# Replace delay edges with original recurrent edges
clean_edges = []
for src, dst in edges:
if src.startswith("_delay_") and src in network._recurrent_map:
# Restore original back edge: recurrent_source -> dst
original_src = network._recurrent_map[src]
clean_edges.append((original_src, dst))
elif dst.startswith("_delay_"):
# Skip the edge feeding INTO the delay node (it's implicit)
continue
else:
clean_edges.append((src, dst))
graph = nir.NIRGraph(nodes=nodes, edges=clean_edges)
if path is not None:
nir.write(str(path), graph)
return graph
|
Hardware Target Manifests
sc_neurocore.nir_bridge.hardware_targets
Capability manifests for NIR-to-neuromorphic-hardware planning.
SCMappingConstraints
dataclass
SC-specific constraints used before lowering NIR graphs to a target.
Source code in src/sc_neurocore/nir_bridge/hardware_targets.py
| Python |
|---|
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37 | @dataclass(frozen=True)
class SCMappingConstraints:
"""SC-specific constraints used before lowering NIR graphs to a target."""
bitstream_lengths: tuple[int, ...]
stream_transport: str
precision_modes: tuple[str, ...]
stochastic_sources: tuple[str, ...]
back_annotation_channels: tuple[str, ...]
def to_dict(self) -> dict[str, Any]:
"""Return a JSON-serialisable representation."""
return {
"bitstream_lengths": list(self.bitstream_lengths),
"stream_transport": self.stream_transport,
"precision_modes": list(self.precision_modes),
"stochastic_sources": list(self.stochastic_sources),
"back_annotation_channels": list(self.back_annotation_channels),
}
|
to_dict()
Return a JSON-serialisable representation.
Source code in src/sc_neurocore/nir_bridge/hardware_targets.py
| Python |
|---|
28
29
30
31
32
33
34
35
36
37 | def to_dict(self) -> dict[str, Any]:
"""Return a JSON-serialisable representation."""
return {
"bitstream_lengths": list(self.bitstream_lengths),
"stream_transport": self.stream_transport,
"precision_modes": list(self.precision_modes),
"stochastic_sources": list(self.stochastic_sources),
"back_annotation_channels": list(self.back_annotation_channels),
}
|
NeuromorphicHardwareProfile
dataclass
NIR extension profile for a named neuromorphic target.
Source code in src/sc_neurocore/nir_bridge/hardware_targets.py
| Python |
|---|
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63 | @dataclass(frozen=True)
class NeuromorphicHardwareProfile:
"""NIR extension profile for a named neuromorphic target."""
target_id: str
display_name: str
backend_status: str
supported_nir_nodes: tuple[str, ...]
unsupported_nir_nodes: tuple[str, ...]
sc_constraints: SCMappingConstraints
notes: tuple[str, ...] = ()
def to_manifest(self) -> dict[str, Any]:
"""Return the profile in deterministic manifest form."""
return {
"backend_status": self.backend_status,
"display_name": self.display_name,
"notes": list(self.notes),
"sc_constraints": self.sc_constraints.to_dict(),
"supported_nir_nodes": list(self.supported_nir_nodes),
"target_id": self.target_id,
"unsupported_nir_nodes": list(self.unsupported_nir_nodes),
}
|
to_manifest()
Return the profile in deterministic manifest form.
Source code in src/sc_neurocore/nir_bridge/hardware_targets.py
| Python |
|---|
52
53
54
55
56
57
58
59
60
61
62
63 | def to_manifest(self) -> dict[str, Any]:
"""Return the profile in deterministic manifest form."""
return {
"backend_status": self.backend_status,
"display_name": self.display_name,
"notes": list(self.notes),
"sc_constraints": self.sc_constraints.to_dict(),
"supported_nir_nodes": list(self.supported_nir_nodes),
"target_id": self.target_id,
"unsupported_nir_nodes": list(self.unsupported_nir_nodes),
}
|
HardwareNoiseAnnotation
dataclass
Measured target noise that can be replayed in simulation.
Source code in src/sc_neurocore/nir_bridge/hardware_targets.py
| Python |
|---|
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81 | @dataclass(frozen=True)
class HardwareNoiseAnnotation:
"""Measured target noise that can be replayed in simulation."""
target_id: str
observations: dict[str, float]
simulation_contract: dict[str, Any]
def to_dict(self) -> dict[str, Any]:
"""Return a JSON-serialisable noise annotation."""
return {
"observations": dict(self.observations),
"simulation_contract": dict(self.simulation_contract),
"target_id": self.target_id,
}
|
to_dict()
Return a JSON-serialisable noise annotation.
Source code in src/sc_neurocore/nir_bridge/hardware_targets.py
| Python |
|---|
| def to_dict(self) -> dict[str, Any]:
"""Return a JSON-serialisable noise annotation."""
return {
"observations": dict(self.observations),
"simulation_contract": dict(self.simulation_contract),
"target_id": self.target_id,
}
|
available_hardware_profiles()
Return all known hardware profiles in deterministic order.
Source code in src/sc_neurocore/nir_bridge/hardware_targets.py
| Python |
|---|
| def available_hardware_profiles() -> tuple[NeuromorphicHardwareProfile, ...]:
"""Return all known hardware profiles in deterministic order."""
return tuple(_PROFILES[key] for key in sorted(_PROFILES))
|
get_hardware_profile(target_id)
Return one hardware profile by identifier.
Source code in src/sc_neurocore/nir_bridge/hardware_targets.py
| Python |
|---|
229
230
231
232
233
234
235
236 | def get_hardware_profile(target_id: str) -> NeuromorphicHardwareProfile:
"""Return one hardware profile by identifier."""
key = target_id.lower().replace("-", "_")
if key not in _PROFILES:
known = ", ".join(sorted(_PROFILES))
raise KeyError(f"unknown neuromorphic target '{target_id}'. Known targets: {known}")
return _PROFILES[key]
|
build_nir_hardware_manifest(targets=None)
Build a deterministic manifest for NIR hardware-extension planning.
Source code in src/sc_neurocore/nir_bridge/hardware_targets.py
| Python |
|---|
239
240
241
242
243
244
245
246
247
248 | def build_nir_hardware_manifest(targets: tuple[str, ...] | None = None) -> dict[str, Any]:
"""Build a deterministic manifest for NIR hardware-extension planning."""
selected = tuple(sorted(_PROFILES)) if targets is None else targets
profiles = [get_hardware_profile(target).to_manifest() for target in selected]
return {
"schema_version": "1.0",
"extension": "sc_neurocore.nir_hardware_targets",
"profiles": profiles,
}
|
build_noise_annotation(target_id, observations)
Validate measured hardware noise and prepare it for simulation replay.
Source code in src/sc_neurocore/nir_bridge/hardware_targets.py
| Python |
|---|
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278 | def build_noise_annotation(
target_id: str,
observations: Mapping[str, float],
) -> HardwareNoiseAnnotation:
"""Validate measured hardware noise and prepare it for simulation replay."""
profile = get_hardware_profile(target_id)
allowed = set(profile.sc_constraints.back_annotation_channels)
unknown = sorted(set(observations) - allowed)
if unknown:
raise ValueError(f"unknown noise channels for {profile.target_id}: {', '.join(unknown)}")
clean: dict[str, float] = {}
for name, value in observations.items():
numeric = float(value)
if not math.isfinite(numeric) or numeric < 0:
raise ValueError(f"noise channel '{name}' must be finite and non-negative")
clean[name] = numeric
return HardwareNoiseAnnotation(
target_id=profile.target_id,
observations=clean,
simulation_contract={
"apply_to": "sc_probability_and_event_timing",
"replay_mode": "deterministic_seeded",
"requires_measured_hardware": True,
},
)
|
build_nir_hardware_manifest() records capability manifests for Akida,
Loihi 2, BrainScaleS-3, SpiNNaker2, and DYNAP-SE. These entries are planning
metadata, not live SDK integrations: each profile carries backend_status:
capability_manifest and only records NIR node support, SC bitstream ranges,
stream transport, stochastic sources, and noise channels that can be measured
and replayed in simulation.
Pythonfrom sc_neurocore.nir_bridge import build_nir_hardware_manifest, build_noise_annotation
manifest = build_nir_hardware_manifest(("loihi2", "spinnaker2", "akida"))
noise = build_noise_annotation("loihi2", {"spike_drop_rate": 0.001})
Noise annotations validate channel names and reject non-finite or negative
measurements before they can influence simulation.
Loihi 2 / SpiNNaker2 Adapter Packages
sc_neurocore.nir_bridge.neuromorphic_adapters
SDK-free adapter packages for Loihi 2 and SpiNNaker2 planning.
The functions in this module deliberately do not invoke Lava, SpiNNTools, or
physical hardware. They create deterministic handoff artefacts from a NIR graph
and the existing silicon-mapping report so downstream vendor-specific runs have
an explicit manifest, fallback list, and hardware-noise contract.
NeuromorphicAdapterPackage
dataclass
Deterministic handoff package for one neuromorphic hardware target.
Source code in src/sc_neurocore/nir_bridge/neuromorphic_adapters.py
| Python |
|---|
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117 | @dataclass(frozen=True)
class NeuromorphicAdapterPackage:
"""Deterministic handoff package for one neuromorphic hardware target."""
target_id: str
adapter_name: str
vendor_stack: str
sdk_dependency: str
handoff_entrypoint: str
hardware_status: str
mapping_report: dict[str, Any]
target_report: dict[str, Any]
def manifest(self) -> dict[str, Any]:
"""Return a JSON-serialisable adapter manifest."""
return {
"adapter_name": self.adapter_name,
"fallback_requirements": list(self.target_report["fallback_requirements"]),
"handoff_entrypoint": self.handoff_entrypoint,
"hardware_status": self.hardware_status,
"lowering_status": self.target_report["lowering_status"],
"noise_back_annotation_hooks": list(self.target_report["noise_back_annotation_hooks"]),
"schema_version": ADAPTER_SCHEMA_VERSION,
"sdk_dependency": self.sdk_dependency,
"summary": dict(self.target_report["summary"]),
"target_id": self.target_id,
"vendor_stack": self.vendor_stack,
}
def files(self) -> dict[str, str]:
"""Return deterministic package files keyed by relative path."""
manifest = self.manifest()
limitations = "\n".join(f"- {item}" for item in self.target_report["limitations"])
fallback = "\n".join(
f"- {item['node']} ({item['node_type']}): {item['requirement']}"
for item in self.target_report["fallback_requirements"]
)
if not fallback:
fallback = "- none"
readme = (
f"# {self.adapter_name}\n\n"
f"Target: `{self.target_id}`\n\n"
f"Vendor stack: {self.vendor_stack}\n\n"
f"SDK dependency: `{self.sdk_dependency}`\n\n"
f"Lowering status: `{self.target_report['lowering_status']}`\n\n"
"## Handoff Boundary\n\n"
f"{self.handoff_entrypoint}. {self.hardware_status}.\n\n"
"This package is a deterministic SC-NeuroCore planning artefact. "
"It does not claim execution on vendor hardware until the vendor SDK "
"run and board logs are attached.\n\n"
"## Fallback Requirements\n\n"
f"{fallback}\n\n"
"## Limitations\n\n"
f"{limitations}\n"
)
return {
f"{self.target_id}/adapter_manifest.json": json.dumps(
manifest, indent=2, sort_keys=True
)
+ "\n",
f"{self.target_id}/nir_silicon_mapping_report.json": json.dumps(
self.mapping_report, indent=2, sort_keys=True
)
+ "\n",
f"{self.target_id}/README.md": readme,
}
|
manifest()
Return a JSON-serialisable adapter manifest.
Source code in src/sc_neurocore/nir_bridge/neuromorphic_adapters.py
| Python |
|---|
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78 | def manifest(self) -> dict[str, Any]:
"""Return a JSON-serialisable adapter manifest."""
return {
"adapter_name": self.adapter_name,
"fallback_requirements": list(self.target_report["fallback_requirements"]),
"handoff_entrypoint": self.handoff_entrypoint,
"hardware_status": self.hardware_status,
"lowering_status": self.target_report["lowering_status"],
"noise_back_annotation_hooks": list(self.target_report["noise_back_annotation_hooks"]),
"schema_version": ADAPTER_SCHEMA_VERSION,
"sdk_dependency": self.sdk_dependency,
"summary": dict(self.target_report["summary"]),
"target_id": self.target_id,
"vendor_stack": self.vendor_stack,
}
|
files()
Return deterministic package files keyed by relative path.
Source code in src/sc_neurocore/nir_bridge/neuromorphic_adapters.py
| Python |
|---|
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117 | def files(self) -> dict[str, str]:
"""Return deterministic package files keyed by relative path."""
manifest = self.manifest()
limitations = "\n".join(f"- {item}" for item in self.target_report["limitations"])
fallback = "\n".join(
f"- {item['node']} ({item['node_type']}): {item['requirement']}"
for item in self.target_report["fallback_requirements"]
)
if not fallback:
fallback = "- none"
readme = (
f"# {self.adapter_name}\n\n"
f"Target: `{self.target_id}`\n\n"
f"Vendor stack: {self.vendor_stack}\n\n"
f"SDK dependency: `{self.sdk_dependency}`\n\n"
f"Lowering status: `{self.target_report['lowering_status']}`\n\n"
"## Handoff Boundary\n\n"
f"{self.handoff_entrypoint}. {self.hardware_status}.\n\n"
"This package is a deterministic SC-NeuroCore planning artefact. "
"It does not claim execution on vendor hardware until the vendor SDK "
"run and board logs are attached.\n\n"
"## Fallback Requirements\n\n"
f"{fallback}\n\n"
"## Limitations\n\n"
f"{limitations}\n"
)
return {
f"{self.target_id}/adapter_manifest.json": json.dumps(
manifest, indent=2, sort_keys=True
)
+ "\n",
f"{self.target_id}/nir_silicon_mapping_report.json": json.dumps(
self.mapping_report, indent=2, sort_keys=True
)
+ "\n",
f"{self.target_id}/README.md": readme,
}
|
build_neuromorphic_adapter_package(source, target_id, config=None)
Build one Loihi 2 or SpiNNaker2 adapter handoff package.
Source code in src/sc_neurocore/nir_bridge/neuromorphic_adapters.py
| Python |
|---|
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141 | def build_neuromorphic_adapter_package(
source: Any,
target_id: str,
config: SiliconMappingConfig | None = None,
) -> NeuromorphicAdapterPackage:
"""Build one Loihi 2 or SpiNNaker2 adapter handoff package."""
target = _normalise_adapter_target(target_id)
cfg = _target_config(target, config)
report = build_silicon_mapping_report(source, cfg)
target_report = report["targets"][0]
handoff = _TARGET_HANDOFFS[target]
return NeuromorphicAdapterPackage(
target_id=target,
adapter_name=handoff["adapter_name"],
vendor_stack=handoff["vendor_stack"],
sdk_dependency=handoff["sdk_dependency"],
handoff_entrypoint=handoff["handoff_entrypoint"],
hardware_status=handoff["hardware_status"],
mapping_report=report,
target_report=target_report,
)
|
build_neuromorphic_adapter_bundle(source, targets=SUPPORTED_ADAPTER_TARGETS, config=None)
Build deterministic adapter packages for multiple targets.
Source code in src/sc_neurocore/nir_bridge/neuromorphic_adapters.py
| Python |
|---|
144
145
146
147
148
149
150
151
152
153
154
155
156 | def build_neuromorphic_adapter_bundle(
source: Any,
targets: tuple[str, ...] = SUPPORTED_ADAPTER_TARGETS,
config: SiliconMappingConfig | None = None,
) -> dict[str, NeuromorphicAdapterPackage]:
"""Build deterministic adapter packages for multiple targets."""
return {
_normalise_adapter_target(target): build_neuromorphic_adapter_package(
source, target, config
)
for target in targets
}
|
write_neuromorphic_adapter_bundle(output_dir, source, targets=SUPPORTED_ADAPTER_TARGETS, config=None)
Write Loihi 2/SpiNNaker2 adapter manifests and reports to disk.
Source code in src/sc_neurocore/nir_bridge/neuromorphic_adapters.py
| Python |
|---|
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176 | def write_neuromorphic_adapter_bundle(
output_dir: str | Path,
source: Any,
targets: tuple[str, ...] = SUPPORTED_ADAPTER_TARGETS,
config: SiliconMappingConfig | None = None,
) -> dict[str, Path]:
"""Write Loihi 2/SpiNNaker2 adapter manifests and reports to disk."""
output = Path(output_dir)
packages = build_neuromorphic_adapter_bundle(source, targets, config)
written: dict[str, Path] = {}
for target, package in packages.items():
for rel_path, content in package.files().items():
path = output / rel_path
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content, encoding="utf-8")
written[f"{target}:{rel_path}"] = path
return written
|
build_neuromorphic_adapter_package() turns a parsed NIR graph into a
deterministic handoff package for either loihi2 or spinnaker2. The package
contains:
adapter_manifest.json with lowering status, fallback requirements, selected
bitstream length, and noise back-annotation hooks;
nir_silicon_mapping_report.json, the full mapping report used to build the
manifest;
README.md documenting the vendor SDK boundary.
The adapter package is intentionally SDK-free. Loihi 2 execution still requires
Lava/Loihi access, and SpiNNaker2 execution still requires the SpiNNaker2 SDK
and board access. The package is therefore a reproducible planning and handoff
artefact, not a hardware-execution claim.
Pythonfrom sc_neurocore.nir_bridge import write_neuromorphic_adapter_bundle
write_neuromorphic_adapter_bundle(
"build/neuromorphic_targets",
nir_graph,
targets=("loihi2", "spinnaker2"),
)