Skip to content

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
74
75
76
77
78
79
80
81
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[Any, Any] 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[Any, Any] | None Optional bias vector of shape (n_dst,). delay_steps : int | tuple[int, ...] Number of explicit unit-delay timesteps on this connection. A scalar applies to all source columns; a tuple carries one delay per source column for heterogeneous NIR Delay vectors. source_threshold : np.ndarray[Any, Any] | None Optional threshold vector applied to source signals before the weight matrix. Represents NIR Threshold on the source side. destination_threshold : np.ndarray[Any, Any] | None Optional threshold vector applied after this connection's affine accumulation and before the destination population input.

Source code in src/sc_neurocore/nir_bridge/neuron_graph.py
Python
103
104
105
106
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
@dataclass
class ConnectionSpec:
    """Weighted edge between two neuron populations.

    Attributes
    ----------
    src : str
        Source population name.
    dst : str
        Destination population name.
    weights : np.ndarray[Any, Any]
        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[Any, Any] | None
        Optional bias vector of shape ``(n_dst,)``.
    delay_steps : int | tuple[int, ...]
        Number of explicit unit-delay timesteps on this connection.  A scalar
        applies to all source columns; a tuple carries one delay per source
        column for heterogeneous NIR ``Delay`` vectors.
    source_threshold : np.ndarray[Any, Any] | None
        Optional threshold vector applied to source signals before the weight
        matrix.  Represents NIR ``Threshold`` on the source side.
    destination_threshold : np.ndarray[Any, Any] | None
        Optional threshold vector applied after this connection's affine
        accumulation and before the destination population input.
    """

    src: str
    dst: str
    weights: np.ndarray[Any, Any]
    bias: np.ndarray[Any, Any] | None = None
    delay_steps: DelaySteps = 0
    source_threshold: np.ndarray[Any, Any] | None = None
    destination_threshold: np.ndarray[Any, Any] | 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. hierarchy : tuple[HierarchyInstanceSpec, ...] Nested NIR graph instances that were inlined for flat hardware lowering but must remain visible in SC-NIR hierarchy metadata.

Source code in src/sc_neurocore/nir_bridge/neuron_graph.py
Python
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
@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.
    hierarchy : tuple[HierarchyInstanceSpec, ...]
        Nested NIR graph instances that were inlined for flat hardware lowering
        but must remain visible in SC-NIR hierarchy metadata.
    """

    populations: list[NeuronSpec]
    connections: list[ConnectionSpec]
    input_pop: str
    output_pop: str
    dt: float = 1.0
    hierarchy: tuple[HierarchyInstanceSpec, ...] = ()

    @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 ""
            delay_str = f" delay={conn.delay_steps}" if conn.delay_steps else ""
            lines.append(f"    {conn.src}{conn.dst}: {shape}{bias_str}{delay_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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
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 ""
        delay_str = f" delay={conn.delay_steps}" if conn.delay_steps else ""
        lines.append(f"    {conn.src}{conn.dst}: {shape}{bias_str}{delay_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[Any, Any]] 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
 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
@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[Any, Any]]
        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[Any, Any]] = 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
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
@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. scnir_document : SCNIRDocument SC-aware metadata document consumed by the compilation artefacts. scnir_source_modules : dict[str, str] Concrete stochastic source HDL modules keyed by Verilog module name. scnir_source_manifest : tuple[SCNIRHDLSourceManifestEntry, ...] Deterministic manifest mapping SC-NIR streams to source modules. scnir_external_inputs : tuple[SCNIRExternalInputManifestEntry, ...] Deterministic flattened input-bus layout for external source names. scnir_hierarchy_modules : dict[str, str] Standalone SC-NIR hierarchy boundary modules keyed by module name.

Source code in src/sc_neurocore/nir_bridge/fpga_compiler.py
Python
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
@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.
    scnir_document : SCNIRDocument
        SC-aware metadata document consumed by the compilation artefacts.
    scnir_source_modules : dict[str, str]
        Concrete stochastic source HDL modules keyed by Verilog module name.
    scnir_source_manifest : tuple[SCNIRHDLSourceManifestEntry, ...]
        Deterministic manifest mapping SC-NIR streams to source modules.
    scnir_external_inputs : tuple[SCNIRExternalInputManifestEntry, ...]
        Deterministic flattened input-bus layout for external source names.
    scnir_hierarchy_modules : dict[str, str]
        Standalone SC-NIR hierarchy boundary modules keyed by module name.
    """

    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
    scnir_document: SCNIRDocument
    scnir_source_modules: dict[str, str]
    scnir_source_manifest: tuple[SCNIRHDLSourceManifestEntry, ...]
    scnir_external_inputs: tuple[SCNIRExternalInputManifestEntry, ...]
    scnir_hierarchy_modules: dict[str, 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
223
224
225
226
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
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
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.
    """
    network.topo_order
    (
        nodes,
        edges,
        topo_order,
        boundary_inputs,
        boundary_outputs,
        flattened_recurrent_map,
        hierarchy,
    ) = _inline_single_port_subgraphs(network)

    # 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[Any, Any], np.ndarray[Any, Any] | None]] = {}
    # Maps a neuron node name → (weight node, post-weight scale, flatten width, threshold)
    weight_source_for: dict[
        str,
        tuple[str, np.ndarray[Any, Any] | None, int | None, np.ndarray[Any, Any] | None],
    ] = {}

    # 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 name in boundary_inputs or not input_pop:
                input_pop = name
            continue

        if class_name == "SCOutputNode":
            if name in boundary_outputs or not output_pop:
                output_pop = name
            continue

        if class_name in _SC_WEIGHT_NODES:
            # Weight-carrying node: store weights for the downstream neuron
            weight, bias = _weight_matrix_and_bias(node, name)
            pending_weights[name] = (weight, bias)

            # Find the neuron this feeds into, preserving post-weight
            # Scale nodes as row/bias multipliers.
            for succ in successors.get(name, []):
                resolved_dst = _resolve_weight_destination(
                    succ,
                    nodes=nodes,
                    successors=successors,
                )
                if resolved_dst is not None:
                    (
                        dst_name,
                        destination_scale,
                        destination_flatten_width,
                        destination_threshold,
                    ) = resolved_dst
                    weight_source_for[dst_name] = (
                        name,
                        destination_scale,
                        destination_flatten_width,
                        destination_threshold,
                    )
            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:
            if class_name in {_SINGLE_PORT_SUBGRAPH_NODE, _MULTIPORT_SUBGRAPH_NODE}:
                raise ValueError(
                    f"Nested NIRGraph node {name!r} is parser-executable but is not "
                    "supported by SC-NIR/FPGA lowering; flatten or pre-lower the "
                    "subgraph before hardware compilation"
                )
            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 pop in populations:
        weight_source = weight_source_for.get(pop.name)
        if weight_source is None:
            continue
        (
            weight_node_name,
            destination_scale,
            destination_flatten_width,
            destination_threshold,
        ) = weight_source

        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, preserving homogeneous explicit NIR Delay nodes along
        # the immediate source path as scalar connection delay metadata.
        src_name = ""
        delay_steps: DelaySteps = 0
        source_scale: np.ndarray[Any, Any] | None = None
        source_flatten_width: int | None = None
        source_threshold: np.ndarray[Any, Any] | None = None
        for pred in predecessors.get(weight_node_name, []):
            resolved = _resolve_weight_source(pred, nodes=nodes, predecessors=predecessors)
            if resolved is not None:
                (
                    src_name,
                    delay_steps,
                    source_scale,
                    source_flatten_width,
                    source_threshold,
                ) = resolved
                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"

        if source_flatten_width is not None and source_flatten_width != int(weights.shape[1]):
            raise ValueError(
                f"Flatten output width {source_flatten_width} does not match "
                f"weight input width {int(weights.shape[1])} for connection {src_name}->{pop.name}"
            )
        if destination_flatten_width is not None and destination_flatten_width != int(
            weights.shape[0]
        ):
            raise ValueError(
                f"Flatten input width {destination_flatten_width} does not match "
                f"weight output width {int(weights.shape[0])} for connection {src_name}->{pop.name}"
            )
        source_threshold = _broadcast_threshold(
            source_threshold,
            int(weights.shape[1]),
            f"source-side Threshold for connection {src_name}->{pop.name}",
        )
        destination_threshold = _broadcast_threshold(
            destination_threshold,
            int(weights.shape[0]),
            f"post-weight Threshold for connection {src_name}->{pop.name}",
        )

        folded_weights, folded_bias = _fold_connection_scales(
            weights,
            bias,
            source_scale=source_scale,
            destination_scale=destination_scale,
            src=src_name,
            dst=pop.name,
        )

        connections.append(
            ConnectionSpec(
                src=src_name,
                dst=pop.name,
                weights=folded_weights,
                bias=folded_bias,
                delay_steps=delay_steps,
                source_threshold=source_threshold,
                destination_threshold=destination_threshold,
            )
        )

    # Recurrent edges are broken into _UnitDelayNode sources by SCNetwork.
    # If the delayed source is a weight-carrying node, rebuild the original
    # weighted recurrent connection with an explicit one-step delay marker so
    # SC-NIR and downstream HDL do not silently lose the feedback stream.
    recurrent_map = flattened_recurrent_map
    for delay_name, recurrent_src in recurrent_map.items():
        weight_data = pending_weights.get(recurrent_src)
        if weight_data is None:
            continue

        src_name = ""
        for pred in predecessors.get(recurrent_src, []):
            if type(nodes[pred]).__name__ in _SC_NODE_TO_TYPE:
                src_name = pred
                break
        if not src_name:
            continue

        dst_names = [
            dst
            for dst in successors.get(delay_name, [])
            if type(nodes[dst]).__name__ in _SC_NODE_TO_TYPE
        ]
        if not dst_names:
            continue

        weights, bias = weight_data
        for dst_name in dst_names:
            connections.append(
                ConnectionSpec(
                    src=src_name,
                    dst=dst_name,
                    weights=weights,
                    bias=bias,
                    delay_steps=1,
                )
            )

    # 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,
        hierarchy=hierarchy,
    )

    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
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
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[Any, Any]] = {}
        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_source_threshold = None
        if conn.source_threshold is not None:
            q_source_threshold = _quantise_array(
                conn.source_threshold,
                q,
                label=f"source_threshold[{conn.src}{conn.dst}]",
                warnings=warnings,
            )
        q_destination_threshold = None
        if conn.destination_threshold is not None:
            q_destination_threshold = _quantise_array(
                conn.destination_threshold,
                q,
                label=f"destination_threshold[{conn.src}{conn.dst}]",
                warnings=warnings,
            )
        q_connections.append(
            ConnectionSpec(
                src=conn.src,
                dst=conn.dst,
                weights=q_weights,
                bias=q_bias,
                delay_steps=conn.delay_steps,
                source_threshold=q_source_threshold,
                destination_threshold=q_destination_threshold,
            )
        )

    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, bitstream_length=256, source_kind='lfsr', base_seed=1, target='artix7', online_learning=None)

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. bitstream_length : int SC-NIR bitstream length metadata propagated into compilation artefacts. source_kind : {"lfsr", "sobol"} Hardware stochastic source family materialised from SC-NIR metadata. base_seed : int First deterministic source seed; stream index increments from this base. target : str FPGA target for resource estimation hints. online_learning : Mapping[str, Mapping[str, Any]] | None Optional validated per-weight-stream SC-NIR online-learning annotations, keyed by deterministic stream id such as "conn.src_to_dst.weight".

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
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
def compile_network_to_fpga(
    graph: NeuronGraph,
    *,
    module_name: str = "sc_nir_network",
    data_width: int = 16,
    fraction: int = 8,
    bitstream_length: int = 256,
    source_kind: Literal["lfsr", "sobol"] = "lfsr",
    base_seed: int = 1,
    target: str = "artix7",
    online_learning: Mapping[str, Mapping[str, Any]] | None = None,
) -> 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.
    bitstream_length : int
        SC-NIR bitstream length metadata propagated into compilation artefacts.
    source_kind : {"lfsr", "sobol"}
        Hardware stochastic source family materialised from SC-NIR metadata.
    base_seed : int
        First deterministic source seed; stream index increments from this base.
    target : str
        FPGA target for resource estimation hints.
    online_learning : Mapping[str, Mapping[str, Any]] | None
        Optional validated per-weight-stream SC-NIR online-learning annotations,
        keyed by deterministic stream id such as ``"conn.src_to_dst.weight"``.

    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)
    if source_kind == "lfsr" or source_kind == "sobol":
        resolved_source_kind: Literal["lfsr", "sobol"] = source_kind
    else:
        raise ValueError("source_kind must be 'lfsr' or 'sobol' for FPGA source emission")

    scnir_config = SCNIRConversionConfig(
        bitstream_length=bitstream_length,
        data_width=data_width,
        fraction=fraction,
        base_seed=base_seed,
        source_kind=resolved_source_kind,
        online_learning=dict(online_learning or {}),
    )
    scnir_document = build_scnir_from_neuron_graph(graph, config=scnir_config)
    scnir_source_bundle = build_scnir_source_bundle(scnir_document)
    warnings: list[str] = []

    # Step 1: Quantise
    qgraph = quantise_graph(graph, q)
    warnings.extend(qgraph.warnings)
    hierarchy_weight_literals = _hierarchy_weight_literals(scnir_document, qgraph)

    # 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"
    has_delayed_connections = any(
        any(
            _normalise_connection_delay_steps(
                getattr(conn, "delay_steps", 0),
                int(np.asarray(conn.weights).shape[1]),
                f"Connection {conn.src}->{conn.dst}",
            )
        )
        for conn in qgraph.connections
    )
    has_threshold_connections = any(_connection_has_thresholds(conn) for conn in qgraph.connections)
    if (
        total_neurons > _AER_THRESHOLD
        and not has_delayed_connections
        and not has_threshold_connections
    ):
        interconnect = "aer"
        top_module = _build_top_aer(
            module_name,
            qgraph,
            data_width=data_width,
            fraction=fraction,
            bitstream_length=bitstream_length,
            scnir_stream_count=len(scnir_document.streams),
            scnir_source_module_count=len(scnir_source_bundle.manifest),
            scnir_hierarchy=scnir_document.hierarchy,
            scnir_semantic_hierarchy_stream_ids=frozenset(hierarchy_weight_literals),
        )
    else:
        if total_neurons > _AER_THRESHOLD and has_delayed_connections:
            warnings.append(
                "Using direct interconnect because delayed recurrent connections require "
                "registered one-step source semantics"
            )
        if total_neurons > _AER_THRESHOLD and has_threshold_connections:
            warnings.append(
                "Using direct interconnect because NIR Threshold transforms require exact "
                "fixed-point comparator semantics"
            )
        top_module = _build_top_direct(
            module_name,
            qgraph,
            data_width=data_width,
            fraction=fraction,
            bitstream_length=bitstream_length,
            scnir_stream_count=len(scnir_document.streams),
            scnir_source_module_count=len(scnir_source_bundle.manifest),
            scnir_hierarchy=scnir_document.hierarchy,
            scnir_semantic_hierarchy_stream_ids=frozenset(hierarchy_weight_literals),
        )

    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,
        scnir_document=scnir_document,
        scnir_source_modules=dict(scnir_source_bundle.modules),
        scnir_source_manifest=scnir_source_bundle.manifest,
        scnir_external_inputs=_external_input_manifest(qgraph),
        scnir_hierarchy_modules=_build_scnir_hierarchy_modules(
            scnir_document,
            weight_literals=hierarchy_weight_literals,
        ),
        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
79
80
81
82
83
84
85
86
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
89
90
91
92
93
94
95
96
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
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
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
@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)

    @classmethod
    def from_nir(cls, source: Any, dt: float = 1.0, reset_mode: str = "reset") -> SCNetwork:
        """Build an ``SCNetwork`` directly from a NIR graph or file path."""

        network = from_nir(source, dt=dt, reset_mode=reset_mode)
        if not isinstance(network, cls):
            raise TypeError(f"Expected {cls.__name__}, got {type(network).__name__}")
        return network

    def to_hardware(
        self,
        *,
        module_name: str = "sc_nir_network",
        data_width: int = 16,
        fraction: int = 8,
        bitstream_length: int = 256,
        source_kind: Literal["lfsr", "sobol"] = "lfsr",
        base_seed: int = 1,
        target: str = "artix7",
        dt: float | None = None,
        online_learning: Mapping[str, Mapping[str, Any]] | None = None,
    ) -> Any:
        """Compile this parsed network to the existing FPGA artefact bundle."""

        from .fpga_compiler import compile_network_to_fpga
        from .neuron_graph import from_scnetwork

        neuron_graph = from_scnetwork(self, dt=dt)
        return compile_network_to_fpga(
            neuron_graph,
            module_name=module_name,
            data_width=data_width,
            fraction=fraction,
            bitstream_length=bitstream_length,
            source_kind=source_kind,
            base_seed=base_seed,
            target=target,
            online_learning=online_learning,
        )

    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[Any, Any]]) -> dict[str, np.ndarray[Any, Any]]:
        """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[Any, Any]] = {}

        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[Any, Any]], steps: int = 100
    ) -> dict[str, list[np.ndarray[Any, Any]]]:
        """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[Any, Any]]] = {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)

from_nir(source, dt=1.0, reset_mode='reset') classmethod

Build an SCNetwork directly from a NIR graph or file path.

Source code in src/sc_neurocore/nir_bridge/parser.py
Python
129
130
131
132
133
134
135
136
@classmethod
def from_nir(cls, source: Any, dt: float = 1.0, reset_mode: str = "reset") -> SCNetwork:
    """Build an ``SCNetwork`` directly from a NIR graph or file path."""

    network = from_nir(source, dt=dt, reset_mode=reset_mode)
    if not isinstance(network, cls):
        raise TypeError(f"Expected {cls.__name__}, got {type(network).__name__}")
    return network

to_hardware(*, module_name='sc_nir_network', data_width=16, fraction=8, bitstream_length=256, source_kind='lfsr', base_seed=1, target='artix7', dt=None, online_learning=None)

Compile this parsed network to the existing FPGA artefact bundle.

Source code in src/sc_neurocore/nir_bridge/parser.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
def to_hardware(
    self,
    *,
    module_name: str = "sc_nir_network",
    data_width: int = 16,
    fraction: int = 8,
    bitstream_length: int = 256,
    source_kind: Literal["lfsr", "sobol"] = "lfsr",
    base_seed: int = 1,
    target: str = "artix7",
    dt: float | None = None,
    online_learning: Mapping[str, Mapping[str, Any]] | None = None,
) -> Any:
    """Compile this parsed network to the existing FPGA artefact bundle."""

    from .fpga_compiler import compile_network_to_fpga
    from .neuron_graph import from_scnetwork

    neuron_graph = from_scnetwork(self, dt=dt)
    return compile_network_to_fpga(
        neuron_graph,
        module_name=module_name,
        data_width=data_width,
        fraction=fraction,
        bitstream_length=bitstream_length,
        source_kind=source_kind,
        base_seed=base_seed,
        target=target,
        online_learning=online_learning,
    )

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
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
def step(self, inputs: dict[str, np.ndarray[Any, Any]]) -> dict[str, np.ndarray[Any, Any]]:
    """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[Any, Any]] = {}

    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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
def run(
    self, inputs: dict[str, np.ndarray[Any, Any]], steps: int = 100
) -> dict[str, list[np.ndarray[Any, Any]]]:
    """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[Any, Any]]] = {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
299
300
301
302
303
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
305
306
307
308
309
310
311
312
313
314
315
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[Any, Any]) -> np.ndarray[Any, Any]:
        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
105
106
@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[Any, Any]) -> np.ndarray[Any, Any]:
        """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[Any, Any]]
    ) -> dict[str, np.ndarray[Any, Any]]:
        """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
93
94
95
96
97
def forward(self, x: np.ndarray[Any, Any]) -> np.ndarray[Any, Any]:
    """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
 99
100
101
102
103
def forward_multi(
    self, inputs: dict[str, np.ndarray[Any, Any]]
) -> dict[str, np.ndarray[Any, Any]]:
    """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
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
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.

High-Level Hardware Path

SCNNetwork is the public alias for the parsed NIR SCNetwork. It supports SCNNetwork.from_nir(...) for import and network.to_hardware(...) for lowering through the same from_scnetwork() and compile_network_to_fpga() pipeline used by the lower-level compiler API.

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
 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
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
@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[Any, Any]
    r: np.ndarray[Any, Any]
    v_leak: np.ndarray[Any, Any]
    v_threshold: np.ndarray[Any, Any]
    v_reset: np.ndarray[Any, Any]
    v: np.ndarray[Any, Any] | 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[Any, Any]) -> np.ndarray[Any, Any]:
        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
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
@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[Any, Any]
    v_threshold: np.ndarray[Any, Any]
    v_reset: np.ndarray[Any, Any]
    v: np.ndarray[Any, Any] | 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[Any, Any]) -> np.ndarray[Any, Any]:
        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
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
@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[Any, Any]
    r: np.ndarray[Any, Any]
    v_leak: np.ndarray[Any, Any]
    v: np.ndarray[Any, Any] | 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[Any, Any]) -> np.ndarray[Any, Any]:
        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
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
@dataclass
class SCIntegratorNode:
    """Pure integrator: dv/dt = R*I (no leak, no threshold). Euler: v += R*I*dt"""

    name: str
    r: np.ndarray[Any, Any]
    v: np.ndarray[Any, Any] | 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)

    @property
    def n_neurons(self) -> int:
        """Number of integrator state channels."""

        return int(self.r.size)

    def __post_init__(self) -> None:
        if self.v is None:
            self.v = np.zeros_like(self.r)

    def forward(self, x: np.ndarray[Any, Any]) -> np.ndarray[Any, Any]:
        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)

n_neurons property

Number of integrator state channels.

SCAffineNode dataclass

Dense linear transform with bias: y = Wx + b

Source code in src/sc_neurocore/nir_bridge/node_map.py
Python
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
@dataclass
class SCAffineNode:
    """Dense linear transform with bias: y = Wx + b"""

    name: str
    weight: np.ndarray[Any, Any]
    bias: np.ndarray[Any, Any]

    @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[Any, Any]) -> np.ndarray[Any, Any]:
        x = np.atleast_1d(x).flatten()
        result: np.ndarray[Any, Any] = self.weight @ x + self.bias
        return result

SCLinearNode dataclass

Matrix multiply without bias: y = Wx

Source code in src/sc_neurocore/nir_bridge/node_map.py
Python
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
@dataclass
class SCLinearNode:
    """Matrix multiply without bias: y = Wx"""

    name: str
    weight: np.ndarray[Any, Any]

    @classmethod
    def from_nir(cls, name: str, node: nir.Linear) -> SCLinearNode:
        return cls(name=name, weight=node.weight)

    def forward(self, x: np.ndarray[Any, Any]) -> np.ndarray[Any, Any]:
        x = np.atleast_1d(x).flatten()
        projected: np.ndarray[Any, Any] = self.weight @ x
        return projected

SCScaleNode dataclass

Element-wise scaling: y = s * x

Source code in src/sc_neurocore/nir_bridge/node_map.py
Python
305
306
307
308
309
310
311
312
313
314
315
316
317
318
@dataclass
class SCScaleNode:
    """Element-wise scaling: y = s * x"""

    name: str
    scale: np.ndarray[Any, Any]

    @classmethod
    def from_nir(cls, name: str, node: nir.Scale) -> SCScaleNode:
        return cls(name=name, scale=node.scale)

    def forward(self, x: np.ndarray[Any, Any]) -> np.ndarray[Any, Any]:
        scaled: np.ndarray[Any, Any] = self.scale * x
        return scaled

SCThresholdNode dataclass

Spike threshold: y = 1 if x > threshold else 0

Source code in src/sc_neurocore/nir_bridge/node_map.py
Python
321
322
323
324
325
326
327
328
329
330
331
332
333
@dataclass
class SCThresholdNode:
    """Spike threshold: y = 1 if x > threshold else 0"""

    name: str
    threshold: np.ndarray[Any, Any]

    @classmethod
    def from_nir(cls, name: str, node: nir.Threshold) -> SCThresholdNode:
        return cls(name=name, threshold=node.threshold)

    def forward(self, x: np.ndarray[Any, Any]) -> np.ndarray[Any, Any]:
        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
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
@dataclass
class SCFlattenNode:
    """Reshape tensor — flatten dimensions."""

    name: str
    start_dim: int
    end_dim: int
    input_shape: tuple[int, ...] | None = None
    output_shape: tuple[int, ...] | None = None

    @classmethod
    def from_nir(cls, name: str, node: nir.Flatten) -> SCFlattenNode:
        input_shape = _shape_tuple_from_type(getattr(node, "input_type", None), "input")
        output_shape = _shape_tuple_from_type(getattr(node, "output_type", None), "output")
        return cls(
            name=name,
            start_dim=node.start_dim,
            end_dim=node.end_dim,
            input_shape=input_shape,
            output_shape=output_shape,
        )

    def forward(self, x: np.ndarray[Any, Any]) -> np.ndarray[Any, Any]:
        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)

SCInputNode dataclass

Graph entry point — passes input through unchanged.

Source code in src/sc_neurocore/nir_bridge/node_map.py
Python
49
50
51
52
53
54
55
56
57
@dataclass
class SCInputNode:
    """Graph entry point — passes input through unchanged."""

    name: str
    shape: tuple[int, ...]

    def forward(self, x: np.ndarray[Any, Any]) -> np.ndarray[Any, Any]:
        return x

SCOutputNode dataclass

Graph exit point — collects output.

Source code in src/sc_neurocore/nir_bridge/node_map.py
Python
60
61
62
63
64
65
66
67
68
69
70
@dataclass
class SCOutputNode:
    """Graph exit point — collects output."""

    name: str
    shape: tuple[int, ...]
    last_output: np.ndarray[Any, Any] | None = None

    def forward(self, x: np.ndarray[Any, Any]) -> np.ndarray[Any, Any]:
        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
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
@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[Any, Any]
    delay_time: np.ndarray[Any, Any] | None = None  # original physical time for lossless export
    _buffers: list[list[np.ndarray[Any, Any]]] | 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[Any, Any]) -> np.ndarray[Any, Any]:
        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
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
502
503
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
@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[Any, Any]
    tau_mem: np.ndarray[Any, Any]
    r: np.ndarray[Any, Any]
    v_leak: np.ndarray[Any, Any]
    v_threshold: np.ndarray[Any, Any]
    v_reset: np.ndarray[Any, Any]
    w_in: np.ndarray[Any, Any]
    v: np.ndarray[Any, Any] | None = None
    i_syn: np.ndarray[Any, Any] | 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[Any, Any]) -> np.ndarray[Any, Any]:
        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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
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
613
614
615
616
617
@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[Any, Any]
    tau_mem: np.ndarray[Any, Any]
    r: np.ndarray[Any, Any]
    v_leak: np.ndarray[Any, Any]
    w_in: np.ndarray[Any, Any]
    v: np.ndarray[Any, Any] | None = None
    i_syn: np.ndarray[Any, Any] | 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[Any, Any]) -> np.ndarray[Any, Any]:
        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
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
@dataclass
class SCConv1dNode:
    """1D convolution: y = conv1d(x, weight) + bias."""

    name: str
    weight: np.ndarray[Any, Any]
    bias: np.ndarray[Any, Any]
    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[Any, Any]) -> np.ndarray[Any, Any]:
        # 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
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
@dataclass
class SCConv2dNode:
    """2D convolution: y = conv2d(x, weight) + bias."""

    name: str
    weight: np.ndarray[Any, Any]
    bias: np.ndarray[Any, Any]
    stride: tuple[int, int]
    padding: tuple[int, int]
    dilation: tuple[int, int]
    groups: int
    input_shape: tuple[int, int] | None = None
    output_shape: tuple[int, 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),
            output_shape=_shape3_tuple_from_type(getattr(node, "output_type", None), "output"),
        )

    def forward(self, x: np.ndarray[Any, Any]) -> np.ndarray[Any, Any]:
        # 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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
@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]
    input_shape: tuple[int, int, int] | None = None
    output_shape: tuple[int, int, int] | None = None

    @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,
            input_shape=_shape3_tuple_from_type(getattr(node, "input_type", None), "input"),
            output_shape=_shape3_tuple_from_type(getattr(node, "output_type", None), "output"),
        )

    def forward(self, x: np.ndarray[Any, Any]) -> np.ndarray[Any, Any]:
        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
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
700
701
702
703
704
705
706
707
@dataclass
class SCAvgPool2dNode:
    """2D average pooling: SumPool / kernel_area."""

    name: str
    kernel_size: tuple[int, int]
    stride: tuple[int, int]
    padding: tuple[int, int]
    input_shape: tuple[int, int, int] | None = None
    output_shape: tuple[int, int, int] | None = None

    @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,
            input_shape=_shape3_tuple_from_type(getattr(node, "input_type", None), "input"),
            output_shape=_shape3_tuple_from_type(getattr(node, "output_type", None), "output"),
        )

    def forward(self, x: np.ndarray[Any, Any]) -> np.ndarray[Any, Any]:
        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
874
875
876
877
878
879
880
881
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
74
75
76
77
78
79
80
81
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
223
224
225
226
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.

Python
from 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.

Python
from sc_neurocore.nir_bridge import write_neuromorphic_adapter_bundle

write_neuromorphic_adapter_bundle(
    "build/neuromorphic_targets",
    nir_graph,
    targets=("loihi2", "spinnaker2"),
)