Skip to content

SC-NIR API

SC-NIR is the SC-NeuroCore metadata layer for stochastic-computing semantics that plain NIR does not encode. It records bitstream length, stochastic encoding, fixed-point precision, random-source metadata, and stream correlation constraints before a model reaches hardware compilation or experiment handoff.

The schema is intentionally strict. Unknown fields, missing fields, duplicate stream identifiers, invalid random-source metadata, and dangling correlation references are rejected rather than ignored.

JSON Schema

The reference schema is tracked at:

Text Only
schemas/scnir/scnir.schema.json

Current schema version:

Text Only
sc-neurocore.scnir.v0.1

Each stream entry must provide:

Field Purpose
stream_id Stable identifier used by correlation constraints
layer Producer layer or graph node name
bitstream_length Positive integer SC stream length
encoding unipolar, bipolar, low-discrepancy, replay, LFSR, or hardware-source encoding
precision Signedness, total bits, fractional bits, accumulator bits, rounding, overflow
source LFSR, Sobol, Halton, replay, or hardware source metadata
correlation_constraints Pairwise policy metadata between streams

CLI

Validate a document:

Bash
sc-neurocore scnir validate model.scnir.json

Exit code 0 means the document passed the SC-NIR validator. Exit code 1 means it failed validation or could not be read.

Python API

Python
from sc_neurocore.ir import (
    SCNIRDocument,
    SCNIRPrecision,
    SCNIRSource,
    SCNIRStream,
    load_scnir,
    validate_scnir_dict,
    write_scnir,
)

sc_neurocore.ir.scnir_schema

SC-aware NIR metadata schema and validator.

The SC-NIR layer records stochastic-computing semantics that plain NIR does not carry: stream length, encoding, fixed-point precision, random-source metadata, and correlation constraints. Validation is intentionally fail-closed so unrecognised or under-specified metadata cannot silently reach hardware generation.

SCNIR_SCHEMA_VERSION = 'sc-neurocore.scnir.v0.1' module-attribute

SCNIRValidationError

Bases: ValueError

Raised when an SC-NIR payload violates the fail-closed contract.

Source code in src/sc_neurocore/ir/scnir_schema.py
Python
73
74
class SCNIRValidationError(ValueError):
    """Raised when an SC-NIR payload violates the fail-closed contract."""

SCNIRPrecision dataclass

Fixed-point interpretation attached to one stochastic stream.

Source code in src/sc_neurocore/ir/scnir_schema.py
Python
77
78
79
80
81
82
83
84
85
86
@dataclass(frozen=True, slots=True)
class SCNIRPrecision:
    """Fixed-point interpretation attached to one stochastic stream."""

    signed: bool
    total_bits: int
    fractional_bits: int
    accumulator_bits: int
    rounding: SCNIRRounding
    overflow: SCNIROverflow

SCNIRSource dataclass

Random or deterministic source metadata for a stochastic stream.

Source code in src/sc_neurocore/ir/scnir_schema.py
Python
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
@dataclass(frozen=True, slots=True)
class SCNIRSource:
    """Random or deterministic source metadata for a stochastic stream."""

    kind: SCNIRSourceKind
    seed: int | None = None
    lfsr_polynomial: str | None = None
    tap_mask: int | None = None
    sobol_dimension: int | None = None
    halton_base: int | None = None
    replay_uri: str | None = None
    hardware_id: str | None = None

SCNIRCorrelationConstraint dataclass

Correlation rule between two stochastic streams.

Source code in src/sc_neurocore/ir/scnir_schema.py
Python
103
104
105
106
107
108
109
110
@dataclass(frozen=True, slots=True)
class SCNIRCorrelationConstraint:
    """Correlation rule between two stochastic streams."""

    peer_stream_id: str
    policy: SCNIRCorrelationPolicy
    max_abs_correlation: float | None = None
    seed_domain: str | None = None

SCNIRStream dataclass

SC metadata for one logical stochastic bitstream.

Source code in src/sc_neurocore/ir/scnir_schema.py
Python
113
114
115
116
117
118
119
120
121
122
123
@dataclass(frozen=True, slots=True)
class SCNIRStream:
    """SC metadata for one logical stochastic bitstream."""

    stream_id: str
    layer: str
    bitstream_length: int
    encoding: SCNIREncoding
    precision: SCNIRPrecision
    source: SCNIRSource
    correlation_constraints: Sequence[SCNIRCorrelationConstraint] = field(default_factory=tuple)

SCNIRDocument dataclass

Top-level SC-NIR metadata document.

Source code in src/sc_neurocore/ir/scnir_schema.py
Python
126
127
128
129
130
131
132
@dataclass(frozen=True, slots=True)
class SCNIRDocument:
    """Top-level SC-NIR metadata document."""

    producer: str
    streams: Sequence[SCNIRStream]
    schema_version: str = SCNIR_SCHEMA_VERSION

validate_scnir_dict(payload)

Validate a decoded SC-NIR payload or raise SCNIRValidationError.

Source code in src/sc_neurocore/ir/scnir_schema.py
Python
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
def validate_scnir_dict(payload: Mapping[str, Any]) -> None:
    """Validate a decoded SC-NIR payload or raise ``SCNIRValidationError``."""

    _expect_keys(payload, {"schema_version", "producer", "streams"}, "document")
    if payload["schema_version"] != SCNIR_SCHEMA_VERSION:
        raise SCNIRValidationError(
            f"schema_version must be {SCNIR_SCHEMA_VERSION!r}, got {payload['schema_version']!r}"
        )
    _expect_non_empty_string(payload["producer"], "producer")
    streams = _expect_sequence(payload["streams"], "streams")
    if not streams:
        raise SCNIRValidationError("streams must contain at least one stream")

    stream_ids: set[str] = set()
    stream_payloads: list[Mapping[str, Any]] = []
    for index, item in enumerate(streams):
        stream = _expect_mapping(item, f"streams[{index}]")
        _validate_stream(stream, f"streams[{index}]")
        stream_id = cast(str, stream["stream_id"])
        if stream_id in stream_ids:
            raise SCNIRValidationError(f"duplicate stream_id {stream_id!r}")
        stream_ids.add(stream_id)
        stream_payloads.append(stream)

    for index, stream in enumerate(stream_payloads):
        constraints = _expect_sequence(
            stream.get("correlation_constraints", ()), f"streams[{index}].correlation_constraints"
        )
        for c_index, item in enumerate(constraints):
            constraint = _expect_mapping(
                item, f"streams[{index}].correlation_constraints[{c_index}]"
            )
            peer = cast(str, constraint["peer_stream_id"])
            if peer not in stream_ids:
                raise SCNIRValidationError(
                    f"streams[{index}].correlation_constraints[{c_index}].peer_stream_id "
                    f"{peer!r} does not reference an existing stream"
                )

scnir_from_dict(payload)

Build a typed SC-NIR document from a decoded mapping.

Source code in src/sc_neurocore/ir/scnir_schema.py
Python
175
176
177
178
179
180
181
182
183
184
185
186
187
188
def scnir_from_dict(payload: Mapping[str, Any]) -> SCNIRDocument:
    """Build a typed SC-NIR document from a decoded mapping."""

    validate_scnir_dict(payload)
    streams_payload = _expect_sequence(payload["streams"], "streams")
    streams = tuple(
        _stream_from_dict(_expect_mapping(item, f"streams[{index}]"))
        for index, item in enumerate(streams_payload)
    )
    return SCNIRDocument(
        schema_version=cast(str, payload["schema_version"]),
        producer=cast(str, payload["producer"]),
        streams=streams,
    )

scnir_to_dict(document)

Convert a typed SC-NIR document to deterministic JSON-ready data.

Source code in src/sc_neurocore/ir/scnir_schema.py
Python
191
192
193
194
195
196
197
198
199
200
def scnir_to_dict(document: SCNIRDocument) -> dict[str, Any]:
    """Convert a typed SC-NIR document to deterministic JSON-ready data."""

    payload: dict[str, Any] = {
        "schema_version": document.schema_version,
        "producer": document.producer,
        "streams": [_stream_to_dict(stream) for stream in document.streams],
    }
    validate_scnir_dict(payload)
    return payload

load_scnir(path)

Load and validate an SC-NIR JSON document.

Source code in src/sc_neurocore/ir/scnir_schema.py
Python
203
204
205
206
207
def load_scnir(path: str | Path) -> SCNIRDocument:
    """Load and validate an SC-NIR JSON document."""

    raw = json.loads(Path(path).read_text(encoding="utf-8"))
    return scnir_from_dict(_expect_mapping(raw, "document"))

write_scnir(path, document)

Write an SC-NIR JSON document after validating it.

Source code in src/sc_neurocore/ir/scnir_schema.py
Python
210
211
212
213
214
215
216
217
def write_scnir(path: str | Path, document: SCNIRDocument) -> None:
    """Write an SC-NIR JSON document after validating it."""

    payload = scnir_to_dict(document)
    Path(path).write_text(
        json.dumps(payload, indent=2, sort_keys=True) + "\n",
        encoding="utf-8",
    )