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

Describe a weighted edge between neuron populations.

Parameters

src : str Source population name. dst : str Destination population name. weights : numpy.ndarray Weight matrix with shape (n_dst, n_src). bias : numpy.ndarray or None Optional destination bias vector with shape (n_dst,). delay_steps : int or tuple[int, ...] Scalar delay or one explicit delay per source column. source_threshold : numpy.ndarray or None Optional threshold applied before the weight matrix. destination_threshold : numpy.ndarray or None Optional threshold applied after affine accumulation.

Source code in src/sc_neurocore/nir_bridge/neuron_graph_contracts.py
Python
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
@dataclass
class ConnectionSpec:
    """Describe a weighted edge between neuron populations.

    Parameters
    ----------
    src : str
        Source population name.
    dst : str
        Destination population name.
    weights : numpy.ndarray
        Weight matrix with shape ``(n_dst, n_src)``.
    bias : numpy.ndarray or None
        Optional destination bias vector with shape ``(n_dst,)``.
    delay_steps : int or tuple[int, ...]
        Scalar delay or one explicit delay per source column.
    source_threshold : numpy.ndarray or None
        Optional threshold applied before the weight matrix.
    destination_threshold : numpy.ndarray or None
        Optional threshold applied after affine accumulation.
    """

    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

Describe a complete network ready for FPGA compilation.

Parameters

populations : list[NeuronSpec] Populations in deterministic topological order. connections : list[ConnectionSpec] Weighted connections between populations. input_pop : str Input boundary or first population name. output_pop : str Output boundary or final population name. dt : float Global simulation timestep. hierarchy : tuple[HierarchyInstanceSpec, ...] Nested instances flattened for hardware lowering.

Source code in src/sc_neurocore/nir_bridge/neuron_graph_contracts.py
Python
 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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
@dataclass
class NeuronGraph:
    """Describe a complete network ready for FPGA compilation.

    Parameters
    ----------
    populations : list[NeuronSpec]
        Populations in deterministic topological order.
    connections : list[ConnectionSpec]
        Weighted connections between populations.
    input_pop : str
        Input boundary or first population name.
    output_pop : str
        Output boundary or final population name.
    dt : float
        Global simulation timestep.
    hierarchy : tuple[HierarchyInstanceSpec, ...]
        Nested instances flattened for hardware lowering.
    """

    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:
        """Return the neuron count across all populations."""
        return sum(population.n_neurons for population in self.populations)

    @property
    def total_synapses(self) -> int:
        """Return the matrix-entry count across all connections."""
        return sum(connection.weights.size for connection in self.connections)

    @property
    def neuron_types(self) -> set[str]:
        """Return the canonical neuron types present in the graph."""
        return {population.neuron_type for population in self.populations}

    def summary(self) -> str:
        """Return a deterministic human-readable graph summary."""
        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 population in self.populations:
            lines.append(
                f"    {population.name}: {population.neuron_type} × {population.n_neurons}"
            )
        lines.extend(("", "  Connections:"))
        for connection in self.connections:
            shape = f"{connection.weights.shape[1]}{connection.weights.shape[0]}"
            bias = " +bias" if connection.bias is not None else ""
            delay = f" delay={connection.delay_steps}" if connection.delay_steps else ""
            lines.append(f"    {connection.src}{connection.dst}: {shape}{bias}{delay}")
        return "\n".join(lines)

total_neurons property

Return the neuron count across all populations.

total_synapses property

Return the matrix-entry count across all connections.

neuron_types property

Return the canonical neuron types present in the graph.

summary()

Return a deterministic human-readable graph summary.

Source code in src/sc_neurocore/nir_bridge/neuron_graph_contracts.py
Python
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
def summary(self) -> str:
    """Return a deterministic human-readable graph summary."""
    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 population in self.populations:
        lines.append(
            f"    {population.name}: {population.neuron_type} × {population.n_neurons}"
        )
    lines.extend(("", "  Connections:"))
    for connection in self.connections:
        shape = f"{connection.weights.shape[1]}{connection.weights.shape[0]}"
        bias = " +bias" if connection.bias is not None else ""
        delay = f" delay={connection.delay_steps}" if connection.delay_steps else ""
        lines.append(f"    {connection.src}{connection.dst}: {shape}{bias}{delay}")
    return "\n".join(lines)

NeuronSpec dataclass

Describe one neuron population in the compiled graph.

Parameters

name : str Unique population identifier matching the NIR node name. neuron_type : str Canonical neuron type such as "lif", "if", "li", "cuba_lif", or "cuba_li". n_neurons : int Number of neurons in the population. params : dict[str, numpy.ndarray] Canonical neuron parameters stored as arrays. dt : float Simulation timestep inherited from NIR import.

Source code in src/sc_neurocore/nir_bridge/neuron_graph_contracts.py
Python
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
@dataclass
class NeuronSpec:
    """Describe one neuron population in the compiled graph.

    Parameters
    ----------
    name : str
        Unique population identifier matching the NIR node name.
    neuron_type : str
        Canonical neuron type such as ``"lif"``, ``"if"``, ``"li"``,
        ``"cuba_lif"``, or ``"cuba_li"``.
    n_neurons : int
        Number of neurons in the population.
    params : dict[str, numpy.ndarray]
        Canonical neuron parameters stored as arrays.
    dt : float
        Simulation timestep inherited from 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

FoldedResourceMetrics dataclass

Architectural resource summary of a folded (time-multiplexed) interconnect.

Quantifies what the shared-datapath fold buys versus the direct interconnect's one-module-instance-per-neuron unrolling: one processing element per distinct neuron type is reused across every neuron of that type (a per-type PE pool), with per-neuron state held in BRAM, at the cost of cycles_per_tick cycles to advance the whole network by one timestep.

Attributes

neurons : int Total neurons sharing the datapath across all folded populations. state_vars_per_neuron : int Widest per-neuron state-variable count across the folded types (the largest BRAM word = state_vars_per_neuron × data width). Equal to the single type's count for a homogeneous network. pe_instances : int Physical processing elements instantiated: one per distinct neuron type. A single population, or several populations all of one type, share one PE. shared_multipliers : int Multipliers in the shared weighted fan-in, summed over external-source columns across all populations and reused across each population's neurons. Spiking fan-in (recurrent or inter-population) is spike-gated and uses none. state_ram_bits : int Total BRAM-backed neuron-state storage, in bits, summed over populations (each population contributes neurons × its type's state-var count × data width). cycles_per_tick : int Clock cycles to advance the whole network by one timestep (neurons process cycles + 1 commit cycle). direct_neuron_instances : int Neuron module instances the direct interconnect would unroll (= neurons); the count the fold collapses to pe_instances. populations : int Number of folded populations sharing the one sequencer and the global spike bus. param_rom_bits : int Total per-neuron parameter-ROM storage, in bits, for heterogeneous populations (each contributes neurons × its count of per-neuron-varying parameters × data width). Zero for a network whose populations all have uniform parameters (the PE bakes them). The parameter-space analogue of state_ram_bits.

Source code in src/sc_neurocore/nir_bridge/fpga_compilation_result.py
Python
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
@dataclass(frozen=True)
class FoldedResourceMetrics:
    """Architectural resource summary of a folded (time-multiplexed) interconnect.

    Quantifies what the shared-datapath fold buys versus the direct interconnect's
    one-module-instance-per-neuron unrolling: one processing element per distinct
    neuron type is reused across every neuron of that type (a per-type PE pool), with
    per-neuron state held in BRAM, at the cost of ``cycles_per_tick`` cycles to advance
    the whole network by one timestep.

    Attributes
    ----------
    neurons : int
        Total neurons sharing the datapath across all folded populations.
    state_vars_per_neuron : int
        Widest per-neuron state-variable count across the folded types (the largest
        BRAM word = ``state_vars_per_neuron`` × data width). Equal to the single type's
        count for a homogeneous network.
    pe_instances : int
        Physical processing elements instantiated: one per distinct neuron type. A
        single population, or several populations all of one type, share one PE.
    shared_multipliers : int
        Multipliers in the shared weighted fan-in, summed over external-source columns
        across all populations and reused across each population's neurons. Spiking
        fan-in (recurrent or inter-population) is spike-gated and uses none.
    state_ram_bits : int
        Total BRAM-backed neuron-state storage, in bits, summed over populations
        (each population contributes ``neurons`` × its type's state-var count × data width).
    cycles_per_tick : int
        Clock cycles to advance the whole network by one timestep
        (``neurons`` process cycles + 1 commit cycle).
    direct_neuron_instances : int
        Neuron module instances the direct interconnect would unroll (= ``neurons``);
        the count the fold collapses to ``pe_instances``.
    populations : int
        Number of folded populations sharing the one sequencer and the global spike bus.
    param_rom_bits : int
        Total per-neuron parameter-ROM storage, in bits, for heterogeneous populations
        (each contributes ``neurons`` × its count of per-neuron-varying parameters × data
        width). Zero for a network whose populations all have uniform parameters (the PE
        bakes them). The parameter-space analogue of ``state_ram_bits``.
    """

    neurons: int
    state_vars_per_neuron: int
    pe_instances: int
    shared_multipliers: int
    state_ram_bits: int
    cycles_per_tick: int
    direct_neuron_instances: int
    populations: int = 1
    param_rom_bits: int = 0

    def as_dict(self) -> dict[str, int]:
        """Return a deterministic plain-``int`` mapping for manifests/JSON."""
        return {
            "neurons": self.neurons,
            "state_vars_per_neuron": self.state_vars_per_neuron,
            "pe_instances": self.pe_instances,
            "shared_multipliers": self.shared_multipliers,
            "state_ram_bits": self.state_ram_bits,
            "cycles_per_tick": self.cycles_per_tick,
            "direct_neuron_instances": self.direct_neuron_instances,
            "populations": self.populations,
            "param_rom_bits": self.param_rom_bits,
        }

as_dict()

Return a deterministic plain-int mapping for manifests/JSON.

Source code in src/sc_neurocore/nir_bridge/fpga_compilation_result.py
Python
86
87
88
89
90
91
92
93
94
95
96
97
98
def as_dict(self) -> dict[str, int]:
    """Return a deterministic plain-``int`` mapping for manifests/JSON."""
    return {
        "neurons": self.neurons,
        "state_vars_per_neuron": self.state_vars_per_neuron,
        "pe_instances": self.pe_instances,
        "shared_multipliers": self.shared_multipliers,
        "state_ram_bits": self.state_ram_bits,
        "cycles_per_tick": self.cycles_per_tick,
        "direct_neuron_instances": self.direct_neuron_instances,
        "populations": self.populations,
        "param_rom_bits": self.param_rom_bits,
    }

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", "aer", or "folded" (the time-multiplexed shared datapath). folded_metrics : FoldedResourceMetrics | None Architectural fold resource summary when interconnect == "folded"; None for the direct/AER paths. 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_compilation_result.py
Python
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
150
151
152
153
154
@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"``, ``"aer"``, or ``"folded"`` (the time-multiplexed shared datapath).
    folded_metrics : FoldedResourceMetrics | None
        Architectural fold resource summary when ``interconnect == "folded"``; ``None``
        for the direct/AER paths.
    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]
    folded_metrics: FoldedResourceMetrics | None = None
    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 the FPGA-targeted neuron graph.

Parameters

network : SCNetwork Parsed SC-NeuroCore network returned by :func:from_nir. dt : float or None, optional Simulation timestep override. When omitted, each neuron node retains its imported timestep and the first population supplies the graph timestep.

Returns

NeuronGraph Ordered populations, lowered weighted connections, graph boundaries, and preserved nested hierarchy metadata.

Raises

ValueError If nested graph boundaries are ambiguous, pass-through metadata cannot be represented exactly, or no neuron population remains after lowering.

Source code in src/sc_neurocore/nir_bridge/neuron_graph_builder.py
Python
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
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
def from_scnetwork(network: Any, dt: float | None = None) -> NeuronGraph:
    """Convert a parsed SCNetwork to the FPGA-targeted neuron graph.

    Parameters
    ----------
    network : SCNetwork
        Parsed SC-NeuroCore network returned by :func:`from_nir`.
    dt : float or None, optional
        Simulation timestep override. When omitted, each neuron node retains
        its imported timestep and the first population supplies the graph
        timestep.

    Returns
    -------
    NeuronGraph
        Ordered populations, lowered weighted connections, graph boundaries,
        and preserved nested hierarchy metadata.

    Raises
    ------
    ValueError
        If nested graph boundaries are ambiguous, pass-through metadata cannot
        be represented exactly, or no neuron population remains after lowering.
    """
    network.topo_order
    (
        nodes,
        edges,
        topo_order,
        boundary_inputs,
        boundary_outputs,
        recurrent_map,
        hierarchy,
    ) = _inline_single_port_subgraphs(network)

    successors: dict[str, list[str]] = {}
    predecessors: dict[str, list[str]] = {}
    for source, destination in edges:
        successors.setdefault(source, []).append(destination)
        predecessors.setdefault(destination, []).append(source)

    populations: list[NeuronSpec] = []
    connections: list[ConnectionSpec] = []
    input_pop = ""
    output_pop = ""
    pending_weights: dict[
        str,
        tuple[np.ndarray[Any, Any], np.ndarray[Any, Any] | None],
    ] = {}
    weight_source_for: dict[
        str,
        tuple[str, np.ndarray[Any, Any] | None, int | None, np.ndarray[Any, Any] | None],
    ] = {}

    for name in topo_order:
        node = nodes[name]
        class_name = type(node).__name__
        if class_name == "SCInputNode":
            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, bias = _weight_matrix_and_bias(node, name)
            pending_weights[name] = (weight, bias)
            for successor in successors.get(name, []):
                resolved_destination = _resolve_weight_destination(
                    successor,
                    nodes=nodes,
                    successors=successors,
                )
                if resolved_destination is not None:
                    (
                        destination_name,
                        destination_scale,
                        destination_flatten_width,
                        destination_threshold,
                    ) = resolved_destination
                    weight_source_for[destination_name] = (
                        name,
                        destination_scale,
                        destination_flatten_width,
                        destination_threshold,
                    )
            continue
        if class_name in _SC_PASSTHROUGH_NODES:
            continue

        neuron_type = _SC_NODE_TO_TYPE.get(class_name)
        if neuron_type is None:
            logger.warning(
                "Skipping unsupported node type %s (%s) in FPGA compilation",
                class_name,
                name,
            )
            continue

        n_neurons = getattr(node, "n_neurons", 1)
        node_dt = dt if dt is not None else getattr(node, "dt", 1.0)
        populations.append(
            NeuronSpec(
                name=name,
                neuron_type=neuron_type,
                n_neurons=max(1, n_neurons),
                params=_extract_neuron_params(node, neuron_type),
                dt=node_dt,
            )
        )

    for population in populations:
        weight_source = weight_source_for.get(population.name)
        if weight_source is None:
            continue
        (
            weight_node_name,
            destination_scale,
            destination_flatten_width,
            destination_threshold,
        ) = weight_source
        weights, bias = pending_weights[weight_node_name]

        source_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 predecessor in predecessors.get(weight_node_name, []):
            resolved_source = _resolve_weight_source(
                predecessor,
                nodes=nodes,
                predecessors=predecessors,
            )
            if resolved_source is not None:
                (
                    source_name,
                    delay_steps,
                    source_scale,
                    source_flatten_width,
                    source_threshold,
                ) = resolved_source
                break

        if not source_name:
            candidate_predecessors = predecessors.get(weight_node_name, [])
            if candidate_predecessors:
                source_name = candidate_predecessors[0]
            else:
                source_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 "
                f"{source_name}->{population.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 "
                f"{source_name}->{population.name}"
            )
        source_threshold = _broadcast_threshold(
            source_threshold,
            int(weights.shape[1]),
            f"source-side Threshold for connection {source_name}->{population.name}",
        )
        destination_threshold = _broadcast_threshold(
            destination_threshold,
            int(weights.shape[0]),
            f"post-weight Threshold for connection {source_name}->{population.name}",
        )
        folded_weights, folded_bias = _fold_connection_scales(
            weights,
            bias,
            source_scale=source_scale,
            destination_scale=destination_scale,
            src=source_name,
            dst=population.name,
        )
        connections.append(
            ConnectionSpec(
                src=source_name,
                dst=population.name,
                weights=folded_weights,
                bias=folded_bias,
                delay_steps=delay_steps,
                source_threshold=source_threshold,
                destination_threshold=destination_threshold,
            )
        )

    for delay_name, recurrent_source in recurrent_map.items():
        weight_data = pending_weights.get(recurrent_source)
        if weight_data is None:
            continue

        source_name = ""
        for predecessor in predecessors.get(recurrent_source, []):
            if type(nodes[predecessor]).__name__ in _SC_NODE_TO_TYPE:
                source_name = predecessor
                break
        if not source_name:
            continue

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

        weights, bias = weight_data
        for destination_name in destination_names:
            connections.append(
                ConnectionSpec(
                    src=source_name,
                    dst=destination_name,
                    weights=weights,
                    bias=bias,
                    delay_steps=1,
                )
            )

    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
    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, interconnect=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". interconnect : str | None None (default) auto-selects direct (small) or AER (large) wiring; "direct" forces direct; "folded" opts into the time-multiplexed shared-datapath interconnect (one PE per neuron type + per-population BRAM state, swept by a single sequencer), which supports the :func:_can_fold subset: any number of populations with external-weighted, recurrent, or inter-population spiking fan-in.

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
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
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,
    interconnect: str | 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"``.
    interconnect : str | None
        ``None`` (default) auto-selects direct (small) or AER (large) wiring;
        ``"direct"`` forces direct; ``"folded"`` opts into the time-multiplexed
        shared-datapath interconnect (one PE per neuron type + per-population BRAM
        state, swept by a single sequencer), which supports the :func:`_can_fold`
        subset: any number of populations with external-weighted, recurrent, or
        inter-population spiking fan-in.

    Returns
    -------
    NetworkCompilationResult
        All generated Verilog sources and compilation metadata.

    Raises
    ------
    ValueError
        If the graph is empty or contains unsupported neuron types.
    """
    _check_synthesis_resource_bounds(
        total_neurons=graph.total_neurons,
        total_synapses=graph.total_synapses,
        data_width=data_width,
        fraction=fraction,
        interconnect=interconnect,
    )
    _validate_connection_routing(graph)
    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():
        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)

    # 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
    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)
    folded_metrics: FoldedResourceMetrics | None = None

    if interconnect == "folded":
        # Opt-in time-multiplexed interconnect; never auto-selected. Restricted to the
        # _can_fold subset (any number of populations of supported types with
        # external-weighted, recurrent, inter-population, delayed, thresholded, biased
        # spiking, or analogue-voltage fan-in).
        if not _can_fold(qgraph, data_width=data_width):
            raise ValueError(
                "interconnect='folded' supports populations of supported neuron types with "
                "external-weighted, recurrent, inter-population, delayed, NIR-thresholded, "
                "biased spiking, or analogue source connections (the folded subset), and only "
                "when every population's per-neuron parameters are uniform (the shared PE has no "
                "per-neuron parameter RAM); a delayed external (non-population) source connection "
                "or a heterogeneous population is not folded — use 'direct' or auto otherwise"
            )
        selected_interconnect = "folded"
        pe_modules, top_module = _build_top_folded(
            module_name, qgraph, data_width=data_width, fraction=fraction
        )
        neuron_modules.update(pe_modules)
        folded_metrics = _folded_resource_metrics(qgraph, data_width=data_width)
    elif interconnect not in (None, "direct"):
        raise ValueError(
            f"unknown interconnect {interconnect!r}; choose 'folded', 'direct', or None (auto)"
        )
    elif (
        interconnect is None
        and total_neurons > _AER_THRESHOLD
        and not has_delayed_connections
        and not has_threshold_connections
    ):
        selected_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:
        selected_interconnect = "direct"
        if interconnect is None and total_neurons > _AER_THRESHOLD and has_delayed_connections:
            warnings.append(
                "Using direct interconnect because delayed recurrent connections require "
                "registered one-step source semantics"
            )
        if interconnect is None and 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=selected_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,
        ),
        folded_metrics=folded_metrics,
        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
80
81
82
83
84
85
86
87
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
90
91
92
93
94
95
96
97
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)

FPGA Network Compiler

sc_neurocore.nir_bridge.fpga_compiler

Compile a NeuronGraph to synthesisable Verilog RTL.

End-to-end pipeline: NeuronGraph → quantisation → per-type neuron modules + weight ROM artefact + top-level interconnect.

Interconnect Strategy ~~~~~~~~~~~~~~~~~~~~~ Small networks emit an explicit per-neuron direct interconnect. Larger networks emit a weighted address-event fan-out block for spike-producing source populations, while external analogue inputs and analogue source populations remain exact fixed-point multiply-accumulate terms. Both paths preserve the NIR weighted affine semantics.

Usage ~~~~~ ::

Text Only
from sc_neurocore.nir_bridge.neuron_graph import from_scnetwork
from sc_neurocore.nir_bridge.fpga_compiler import compile_network_to_fpga

graph = from_scnetwork(network)
result = compile_network_to_fpga(graph, module_name="my_snn")
# result.top_module   → top-level Verilog
# result.neuron_modules → per-type Verilog dict
# result.weight_rom   → weight ROM Verilog

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", "aer", or "folded" (the time-multiplexed shared datapath). folded_metrics : FoldedResourceMetrics | None Architectural fold resource summary when interconnect == "folded"; None for the direct/AER paths. 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_compilation_result.py
Python
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
150
151
152
153
154
@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"``, ``"aer"``, or ``"folded"`` (the time-multiplexed shared datapath).
    folded_metrics : FoldedResourceMetrics | None
        Architectural fold resource summary when ``interconnect == "folded"``; ``None``
        for the direct/AER paths.
    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]
    folded_metrics: FoldedResourceMetrics | None = None
    warnings: list[str] = field(default_factory=list)

FoldedResourceMetrics dataclass

Architectural resource summary of a folded (time-multiplexed) interconnect.

Quantifies what the shared-datapath fold buys versus the direct interconnect's one-module-instance-per-neuron unrolling: one processing element per distinct neuron type is reused across every neuron of that type (a per-type PE pool), with per-neuron state held in BRAM, at the cost of cycles_per_tick cycles to advance the whole network by one timestep.

Attributes

neurons : int Total neurons sharing the datapath across all folded populations. state_vars_per_neuron : int Widest per-neuron state-variable count across the folded types (the largest BRAM word = state_vars_per_neuron × data width). Equal to the single type's count for a homogeneous network. pe_instances : int Physical processing elements instantiated: one per distinct neuron type. A single population, or several populations all of one type, share one PE. shared_multipliers : int Multipliers in the shared weighted fan-in, summed over external-source columns across all populations and reused across each population's neurons. Spiking fan-in (recurrent or inter-population) is spike-gated and uses none. state_ram_bits : int Total BRAM-backed neuron-state storage, in bits, summed over populations (each population contributes neurons × its type's state-var count × data width). cycles_per_tick : int Clock cycles to advance the whole network by one timestep (neurons process cycles + 1 commit cycle). direct_neuron_instances : int Neuron module instances the direct interconnect would unroll (= neurons); the count the fold collapses to pe_instances. populations : int Number of folded populations sharing the one sequencer and the global spike bus. param_rom_bits : int Total per-neuron parameter-ROM storage, in bits, for heterogeneous populations (each contributes neurons × its count of per-neuron-varying parameters × data width). Zero for a network whose populations all have uniform parameters (the PE bakes them). The parameter-space analogue of state_ram_bits.

Source code in src/sc_neurocore/nir_bridge/fpga_compilation_result.py
Python
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
@dataclass(frozen=True)
class FoldedResourceMetrics:
    """Architectural resource summary of a folded (time-multiplexed) interconnect.

    Quantifies what the shared-datapath fold buys versus the direct interconnect's
    one-module-instance-per-neuron unrolling: one processing element per distinct
    neuron type is reused across every neuron of that type (a per-type PE pool), with
    per-neuron state held in BRAM, at the cost of ``cycles_per_tick`` cycles to advance
    the whole network by one timestep.

    Attributes
    ----------
    neurons : int
        Total neurons sharing the datapath across all folded populations.
    state_vars_per_neuron : int
        Widest per-neuron state-variable count across the folded types (the largest
        BRAM word = ``state_vars_per_neuron`` × data width). Equal to the single type's
        count for a homogeneous network.
    pe_instances : int
        Physical processing elements instantiated: one per distinct neuron type. A
        single population, or several populations all of one type, share one PE.
    shared_multipliers : int
        Multipliers in the shared weighted fan-in, summed over external-source columns
        across all populations and reused across each population's neurons. Spiking
        fan-in (recurrent or inter-population) is spike-gated and uses none.
    state_ram_bits : int
        Total BRAM-backed neuron-state storage, in bits, summed over populations
        (each population contributes ``neurons`` × its type's state-var count × data width).
    cycles_per_tick : int
        Clock cycles to advance the whole network by one timestep
        (``neurons`` process cycles + 1 commit cycle).
    direct_neuron_instances : int
        Neuron module instances the direct interconnect would unroll (= ``neurons``);
        the count the fold collapses to ``pe_instances``.
    populations : int
        Number of folded populations sharing the one sequencer and the global spike bus.
    param_rom_bits : int
        Total per-neuron parameter-ROM storage, in bits, for heterogeneous populations
        (each contributes ``neurons`` × its count of per-neuron-varying parameters × data
        width). Zero for a network whose populations all have uniform parameters (the PE
        bakes them). The parameter-space analogue of ``state_ram_bits``.
    """

    neurons: int
    state_vars_per_neuron: int
    pe_instances: int
    shared_multipliers: int
    state_ram_bits: int
    cycles_per_tick: int
    direct_neuron_instances: int
    populations: int = 1
    param_rom_bits: int = 0

    def as_dict(self) -> dict[str, int]:
        """Return a deterministic plain-``int`` mapping for manifests/JSON."""
        return {
            "neurons": self.neurons,
            "state_vars_per_neuron": self.state_vars_per_neuron,
            "pe_instances": self.pe_instances,
            "shared_multipliers": self.shared_multipliers,
            "state_ram_bits": self.state_ram_bits,
            "cycles_per_tick": self.cycles_per_tick,
            "direct_neuron_instances": self.direct_neuron_instances,
            "populations": self.populations,
            "param_rom_bits": self.param_rom_bits,
        }

as_dict()

Return a deterministic plain-int mapping for manifests/JSON.

Source code in src/sc_neurocore/nir_bridge/fpga_compilation_result.py
Python
86
87
88
89
90
91
92
93
94
95
96
97
98
def as_dict(self) -> dict[str, int]:
    """Return a deterministic plain-``int`` mapping for manifests/JSON."""
    return {
        "neurons": self.neurons,
        "state_vars_per_neuron": self.state_vars_per_neuron,
        "pe_instances": self.pe_instances,
        "shared_multipliers": self.shared_multipliers,
        "state_ram_bits": self.state_ram_bits,
        "cycles_per_tick": self.cycles_per_tick,
        "direct_neuron_instances": self.direct_neuron_instances,
        "populations": self.populations,
        "param_rom_bits": self.param_rom_bits,
    }

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, interconnect=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". interconnect : str | None None (default) auto-selects direct (small) or AER (large) wiring; "direct" forces direct; "folded" opts into the time-multiplexed shared-datapath interconnect (one PE per neuron type + per-population BRAM state, swept by a single sequencer), which supports the :func:_can_fold subset: any number of populations with external-weighted, recurrent, or inter-population spiking fan-in.

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
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
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,
    interconnect: str | 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"``.
    interconnect : str | None
        ``None`` (default) auto-selects direct (small) or AER (large) wiring;
        ``"direct"`` forces direct; ``"folded"`` opts into the time-multiplexed
        shared-datapath interconnect (one PE per neuron type + per-population BRAM
        state, swept by a single sequencer), which supports the :func:`_can_fold`
        subset: any number of populations with external-weighted, recurrent, or
        inter-population spiking fan-in.

    Returns
    -------
    NetworkCompilationResult
        All generated Verilog sources and compilation metadata.

    Raises
    ------
    ValueError
        If the graph is empty or contains unsupported neuron types.
    """
    _check_synthesis_resource_bounds(
        total_neurons=graph.total_neurons,
        total_synapses=graph.total_synapses,
        data_width=data_width,
        fraction=fraction,
        interconnect=interconnect,
    )
    _validate_connection_routing(graph)
    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():
        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)

    # 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
    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)
    folded_metrics: FoldedResourceMetrics | None = None

    if interconnect == "folded":
        # Opt-in time-multiplexed interconnect; never auto-selected. Restricted to the
        # _can_fold subset (any number of populations of supported types with
        # external-weighted, recurrent, inter-population, delayed, thresholded, biased
        # spiking, or analogue-voltage fan-in).
        if not _can_fold(qgraph, data_width=data_width):
            raise ValueError(
                "interconnect='folded' supports populations of supported neuron types with "
                "external-weighted, recurrent, inter-population, delayed, NIR-thresholded, "
                "biased spiking, or analogue source connections (the folded subset), and only "
                "when every population's per-neuron parameters are uniform (the shared PE has no "
                "per-neuron parameter RAM); a delayed external (non-population) source connection "
                "or a heterogeneous population is not folded — use 'direct' or auto otherwise"
            )
        selected_interconnect = "folded"
        pe_modules, top_module = _build_top_folded(
            module_name, qgraph, data_width=data_width, fraction=fraction
        )
        neuron_modules.update(pe_modules)
        folded_metrics = _folded_resource_metrics(qgraph, data_width=data_width)
    elif interconnect not in (None, "direct"):
        raise ValueError(
            f"unknown interconnect {interconnect!r}; choose 'folded', 'direct', or None (auto)"
        )
    elif (
        interconnect is None
        and total_neurons > _AER_THRESHOLD
        and not has_delayed_connections
        and not has_threshold_connections
    ):
        selected_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:
        selected_interconnect = "direct"
        if interconnect is None and total_neurons > _AER_THRESHOLD and has_delayed_connections:
            warnings.append(
                "Using direct interconnect because delayed recurrent connections require "
                "registered one-step source semantics"
            )
        if interconnect is None and 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=selected_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,
        ),
        folded_metrics=folded_metrics,
        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

compile_network_to_fpga() remains the stable public composition boundary. Its implementation delegates to responsibility-specific modules for connection validation, neuron RTL, weight ROMs, SC-NIR hierarchy boundaries, and the direct, address-event, and folded interconnects. Result classes retain their historical sc_neurocore.nir_bridge.fpga_compiler serialisation path.

Malformed direct NeuronGraph inputs fail before SC-NIR conversion or HDL emission: the compiler rejects empty networks, non-matrix weights, inconsistent source/destination widths, invalid bias or threshold vectors, and invalid connection delays with stable ValueError contracts.

Hardware Neuron Graph

sc_neurocore.nir_bridge.neuron_graph

Preserve the historical neuron-graph API over responsibility modules.

The graph contracts and :func:from_scnetwork remain import-compatible while node classification, hierarchy flattening, dense lowering, metadata handling, connection resolution, and conversion orchestration live in focused modules.

NeuronSpec dataclass

Describe one neuron population in the compiled graph.

Parameters

name : str Unique population identifier matching the NIR node name. neuron_type : str Canonical neuron type such as "lif", "if", "li", "cuba_lif", or "cuba_li". n_neurons : int Number of neurons in the population. params : dict[str, numpy.ndarray] Canonical neuron parameters stored as arrays. dt : float Simulation timestep inherited from NIR import.

Source code in src/sc_neurocore/nir_bridge/neuron_graph_contracts.py
Python
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
@dataclass
class NeuronSpec:
    """Describe one neuron population in the compiled graph.

    Parameters
    ----------
    name : str
        Unique population identifier matching the NIR node name.
    neuron_type : str
        Canonical neuron type such as ``"lif"``, ``"if"``, ``"li"``,
        ``"cuba_lif"``, or ``"cuba_li"``.
    n_neurons : int
        Number of neurons in the population.
    params : dict[str, numpy.ndarray]
        Canonical neuron parameters stored as arrays.
    dt : float
        Simulation timestep inherited from 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

ConnectionSpec dataclass

Describe a weighted edge between neuron populations.

Parameters

src : str Source population name. dst : str Destination population name. weights : numpy.ndarray Weight matrix with shape (n_dst, n_src). bias : numpy.ndarray or None Optional destination bias vector with shape (n_dst,). delay_steps : int or tuple[int, ...] Scalar delay or one explicit delay per source column. source_threshold : numpy.ndarray or None Optional threshold applied before the weight matrix. destination_threshold : numpy.ndarray or None Optional threshold applied after affine accumulation.

Source code in src/sc_neurocore/nir_bridge/neuron_graph_contracts.py
Python
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
@dataclass
class ConnectionSpec:
    """Describe a weighted edge between neuron populations.

    Parameters
    ----------
    src : str
        Source population name.
    dst : str
        Destination population name.
    weights : numpy.ndarray
        Weight matrix with shape ``(n_dst, n_src)``.
    bias : numpy.ndarray or None
        Optional destination bias vector with shape ``(n_dst,)``.
    delay_steps : int or tuple[int, ...]
        Scalar delay or one explicit delay per source column.
    source_threshold : numpy.ndarray or None
        Optional threshold applied before the weight matrix.
    destination_threshold : numpy.ndarray or None
        Optional threshold applied after affine accumulation.
    """

    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

HierarchyInstanceSpec dataclass

Preserve provenance for a nested graph flattened into hardware IR.

Parameters

instance_id : str Parent-graph node name of the nested graph instance. module_name : str Stable HDL module identifier assigned to the instance boundary. node_name_prefix : str Namespace prefix applied to the nested nodes during flattening.

Source code in src/sc_neurocore/nir_bridge/neuron_graph_contracts.py
Python
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
@dataclass(frozen=True, slots=True)
class HierarchyInstanceSpec:
    """Preserve provenance for a nested graph flattened into hardware IR.

    Parameters
    ----------
    instance_id : str
        Parent-graph node name of the nested graph instance.
    module_name : str
        Stable HDL module identifier assigned to the instance boundary.
    node_name_prefix : str
        Namespace prefix applied to the nested nodes during flattening.
    """

    instance_id: str
    module_name: str
    node_name_prefix: str

NeuronGraph dataclass

Describe a complete network ready for FPGA compilation.

Parameters

populations : list[NeuronSpec] Populations in deterministic topological order. connections : list[ConnectionSpec] Weighted connections between populations. input_pop : str Input boundary or first population name. output_pop : str Output boundary or final population name. dt : float Global simulation timestep. hierarchy : tuple[HierarchyInstanceSpec, ...] Nested instances flattened for hardware lowering.

Source code in src/sc_neurocore/nir_bridge/neuron_graph_contracts.py
Python
 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
150
151
152
153
154
155
156
157
158
159
160
161
162
163
@dataclass
class NeuronGraph:
    """Describe a complete network ready for FPGA compilation.

    Parameters
    ----------
    populations : list[NeuronSpec]
        Populations in deterministic topological order.
    connections : list[ConnectionSpec]
        Weighted connections between populations.
    input_pop : str
        Input boundary or first population name.
    output_pop : str
        Output boundary or final population name.
    dt : float
        Global simulation timestep.
    hierarchy : tuple[HierarchyInstanceSpec, ...]
        Nested instances flattened for hardware lowering.
    """

    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:
        """Return the neuron count across all populations."""
        return sum(population.n_neurons for population in self.populations)

    @property
    def total_synapses(self) -> int:
        """Return the matrix-entry count across all connections."""
        return sum(connection.weights.size for connection in self.connections)

    @property
    def neuron_types(self) -> set[str]:
        """Return the canonical neuron types present in the graph."""
        return {population.neuron_type for population in self.populations}

    def summary(self) -> str:
        """Return a deterministic human-readable graph summary."""
        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 population in self.populations:
            lines.append(
                f"    {population.name}: {population.neuron_type} × {population.n_neurons}"
            )
        lines.extend(("", "  Connections:"))
        for connection in self.connections:
            shape = f"{connection.weights.shape[1]}{connection.weights.shape[0]}"
            bias = " +bias" if connection.bias is not None else ""
            delay = f" delay={connection.delay_steps}" if connection.delay_steps else ""
            lines.append(f"    {connection.src}{connection.dst}: {shape}{bias}{delay}")
        return "\n".join(lines)

total_neurons property

Return the neuron count across all populations.

total_synapses property

Return the matrix-entry count across all connections.

neuron_types property

Return the canonical neuron types present in the graph.

summary()

Return a deterministic human-readable graph summary.

Source code in src/sc_neurocore/nir_bridge/neuron_graph_contracts.py
Python
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
def summary(self) -> str:
    """Return a deterministic human-readable graph summary."""
    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 population in self.populations:
        lines.append(
            f"    {population.name}: {population.neuron_type} × {population.n_neurons}"
        )
    lines.extend(("", "  Connections:"))
    for connection in self.connections:
        shape = f"{connection.weights.shape[1]}{connection.weights.shape[0]}"
        bias = " +bias" if connection.bias is not None else ""
        delay = f" delay={connection.delay_steps}" if connection.delay_steps else ""
        lines.append(f"    {connection.src}{connection.dst}: {shape}{bias}{delay}")
    return "\n".join(lines)

from_scnetwork(network, dt=None)

Convert a parsed SCNetwork to the FPGA-targeted neuron graph.

Parameters

network : SCNetwork Parsed SC-NeuroCore network returned by :func:from_nir. dt : float or None, optional Simulation timestep override. When omitted, each neuron node retains its imported timestep and the first population supplies the graph timestep.

Returns

NeuronGraph Ordered populations, lowered weighted connections, graph boundaries, and preserved nested hierarchy metadata.

Raises

ValueError If nested graph boundaries are ambiguous, pass-through metadata cannot be represented exactly, or no neuron population remains after lowering.

Source code in src/sc_neurocore/nir_bridge/neuron_graph_builder.py
Python
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
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
def from_scnetwork(network: Any, dt: float | None = None) -> NeuronGraph:
    """Convert a parsed SCNetwork to the FPGA-targeted neuron graph.

    Parameters
    ----------
    network : SCNetwork
        Parsed SC-NeuroCore network returned by :func:`from_nir`.
    dt : float or None, optional
        Simulation timestep override. When omitted, each neuron node retains
        its imported timestep and the first population supplies the graph
        timestep.

    Returns
    -------
    NeuronGraph
        Ordered populations, lowered weighted connections, graph boundaries,
        and preserved nested hierarchy metadata.

    Raises
    ------
    ValueError
        If nested graph boundaries are ambiguous, pass-through metadata cannot
        be represented exactly, or no neuron population remains after lowering.
    """
    network.topo_order
    (
        nodes,
        edges,
        topo_order,
        boundary_inputs,
        boundary_outputs,
        recurrent_map,
        hierarchy,
    ) = _inline_single_port_subgraphs(network)

    successors: dict[str, list[str]] = {}
    predecessors: dict[str, list[str]] = {}
    for source, destination in edges:
        successors.setdefault(source, []).append(destination)
        predecessors.setdefault(destination, []).append(source)

    populations: list[NeuronSpec] = []
    connections: list[ConnectionSpec] = []
    input_pop = ""
    output_pop = ""
    pending_weights: dict[
        str,
        tuple[np.ndarray[Any, Any], np.ndarray[Any, Any] | None],
    ] = {}
    weight_source_for: dict[
        str,
        tuple[str, np.ndarray[Any, Any] | None, int | None, np.ndarray[Any, Any] | None],
    ] = {}

    for name in topo_order:
        node = nodes[name]
        class_name = type(node).__name__
        if class_name == "SCInputNode":
            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, bias = _weight_matrix_and_bias(node, name)
            pending_weights[name] = (weight, bias)
            for successor in successors.get(name, []):
                resolved_destination = _resolve_weight_destination(
                    successor,
                    nodes=nodes,
                    successors=successors,
                )
                if resolved_destination is not None:
                    (
                        destination_name,
                        destination_scale,
                        destination_flatten_width,
                        destination_threshold,
                    ) = resolved_destination
                    weight_source_for[destination_name] = (
                        name,
                        destination_scale,
                        destination_flatten_width,
                        destination_threshold,
                    )
            continue
        if class_name in _SC_PASSTHROUGH_NODES:
            continue

        neuron_type = _SC_NODE_TO_TYPE.get(class_name)
        if neuron_type is None:
            logger.warning(
                "Skipping unsupported node type %s (%s) in FPGA compilation",
                class_name,
                name,
            )
            continue

        n_neurons = getattr(node, "n_neurons", 1)
        node_dt = dt if dt is not None else getattr(node, "dt", 1.0)
        populations.append(
            NeuronSpec(
                name=name,
                neuron_type=neuron_type,
                n_neurons=max(1, n_neurons),
                params=_extract_neuron_params(node, neuron_type),
                dt=node_dt,
            )
        )

    for population in populations:
        weight_source = weight_source_for.get(population.name)
        if weight_source is None:
            continue
        (
            weight_node_name,
            destination_scale,
            destination_flatten_width,
            destination_threshold,
        ) = weight_source
        weights, bias = pending_weights[weight_node_name]

        source_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 predecessor in predecessors.get(weight_node_name, []):
            resolved_source = _resolve_weight_source(
                predecessor,
                nodes=nodes,
                predecessors=predecessors,
            )
            if resolved_source is not None:
                (
                    source_name,
                    delay_steps,
                    source_scale,
                    source_flatten_width,
                    source_threshold,
                ) = resolved_source
                break

        if not source_name:
            candidate_predecessors = predecessors.get(weight_node_name, [])
            if candidate_predecessors:
                source_name = candidate_predecessors[0]
            else:
                source_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 "
                f"{source_name}->{population.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 "
                f"{source_name}->{population.name}"
            )
        source_threshold = _broadcast_threshold(
            source_threshold,
            int(weights.shape[1]),
            f"source-side Threshold for connection {source_name}->{population.name}",
        )
        destination_threshold = _broadcast_threshold(
            destination_threshold,
            int(weights.shape[0]),
            f"post-weight Threshold for connection {source_name}->{population.name}",
        )
        folded_weights, folded_bias = _fold_connection_scales(
            weights,
            bias,
            source_scale=source_scale,
            destination_scale=destination_scale,
            src=source_name,
            dst=population.name,
        )
        connections.append(
            ConnectionSpec(
                src=source_name,
                dst=population.name,
                weights=folded_weights,
                bias=folded_bias,
                delay_steps=delay_steps,
                source_threshold=source_threshold,
                destination_threshold=destination_threshold,
            )
        )

    for delay_name, recurrent_source in recurrent_map.items():
        weight_data = pending_weights.get(recurrent_source)
        if weight_data is None:
            continue

        source_name = ""
        for predecessor in predecessors.get(recurrent_source, []):
            if type(nodes[predecessor]).__name__ in _SC_NODE_TO_TYPE:
                source_name = predecessor
                break
        if not source_name:
            continue

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

        weights, bias = weight_data
        for destination_name in destination_names:
            connections.append(
                ConnectionSpec(
                    src=source_name,
                    dst=destination_name,
                    weights=weights,
                    bias=bias,
                    delay_steps=1,
                )
            )

    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
    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

from_scnetwork() is the boundary between the executable parser graph and FPGA lowering. The historical module remains a compatibility facade: graph records and the converter retain their established qualified names and pickle paths, while focused modules own contracts, node classification, nested hierarchy, dense operators, connection traversal, metadata, and conversion orchestration.

The lowering path preserves source and destination scales, scalar or per-channel delays, thresholds, flatten widths, nested-instance provenance, and recurrent delayed edges. Ambiguous pass-through fan-in/fan-out, malformed flatten dimensions, non-finite dense parameters, unsupported nested boundaries, and hierarchy cycles fail before an incomplete hardware graph can be emitted. The resulting NeuronGraph is consumed directly by compile_network_to_fpga() and SC-NIR conversion.

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
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
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
@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:
        padding = _resolve_conv_padding(
            node.padding,
            kernel=int(node.weight.shape[2]),
            dilation=node.dilation,
            stride=node.stride,
        )
        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
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
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
@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)
        dilation = (
            node.dilation if isinstance(node.dilation, tuple) else (node.dilation, node.dilation)
        )
        kh, kw = int(node.weight.shape[2]), int(node.weight.shape[3])
        raw_padding = (
            node.padding if isinstance(node.padding, tuple) else (node.padding, node.padding)
        )
        padding = (
            _resolve_conv_padding(
                raw_padding[0], kernel=kh, dilation=dilation[0], stride=stride[0]
            ),
            _resolve_conv_padding(
                raw_padding[1], kernel=kw, dilation=dilation[1], stride=stride[1]
            ),
        )
        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
912
913
914
915
916
917
918
919
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 : sc_neurocore.nir_bridge.parser.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
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
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 : sc_neurocore.nir_bridge.parser.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"),
)