Skip to content

Explainability

Bitstream-level explainability and causal attribution for SC decisions. Anchored to formal verification properties.

Quick Start

Python
from sc_neurocore.explainability.explainability import (
    ExplainabilityEngine, CausalAttributor, FormalPropertyLink,
)

sc_neurocore.explainability.explainability

Bitstream-level explainability with deterministic replay and provenance.

Leverages bit-true deterministic SC streams and LFSR replay to generate full provenance traces: "why this spike fired" as a verifiable bitstream decision tree. Integrates with the predictive_coding.ReasoningTrace for neuro-symbolic explanations and produces hash-verified audit trails.

LFSRReplay

Deterministic LFSR-16 replay engine.

Mirrors core_engine::Lfsr16 polynomial: x^16 + x^14 + x^13 + x^11 + 1. Given the same seed, reproduces the exact same bitstream for formal verification and replay-based auditing.

Source code in src/sc_neurocore/explainability/explainability.py
Python
32
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
class LFSRReplay:
    """Deterministic LFSR-16 replay engine.

    Mirrors ``core_engine::Lfsr16`` polynomial: x^16 + x^14 + x^13 + x^11 + 1.
    Given the same seed, reproduces the exact same bitstream for formal
    verification and replay-based auditing.
    """

    def __init__(self, seed: int):
        if seed == 0:
            raise ValueError("LFSR seed must be non-zero")
        self.initial_seed = seed
        self.reg = seed & 0xFFFF

    def step(self) -> int:
        """Advance one step, return new register value."""
        feedback = ((self.reg >> 15) ^ (self.reg >> 13) ^ (self.reg >> 12) ^ (self.reg >> 10)) & 1
        self.reg = ((self.reg << 1) | feedback) & 0xFFFF
        return self.reg

    def encode(self, threshold: int, length: int) -> np.ndarray:
        """Generate a bitstream by comparing LFSR output against threshold."""
        bits = np.zeros(length, dtype=np.uint8)
        for i in range(length):
            bits[i] = 1 if self.reg < threshold else 0
            self.step()
        return bits

    def reset(self) -> None:
        """Reset to initial seed for replay."""
        self.reg = self.initial_seed

step()

Advance one step, return new register value.

Source code in src/sc_neurocore/explainability/explainability.py
Python
46
47
48
49
50
def step(self) -> int:
    """Advance one step, return new register value."""
    feedback = ((self.reg >> 15) ^ (self.reg >> 13) ^ (self.reg >> 12) ^ (self.reg >> 10)) & 1
    self.reg = ((self.reg << 1) | feedback) & 0xFFFF
    return self.reg

encode(threshold, length)

Generate a bitstream by comparing LFSR output against threshold.

Source code in src/sc_neurocore/explainability/explainability.py
Python
52
53
54
55
56
57
58
def encode(self, threshold: int, length: int) -> np.ndarray:
    """Generate a bitstream by comparing LFSR output against threshold."""
    bits = np.zeros(length, dtype=np.uint8)
    for i in range(length):
        bits[i] = 1 if self.reg < threshold else 0
        self.step()
    return bits

reset()

Reset to initial seed for replay.

Source code in src/sc_neurocore/explainability/explainability.py
Python
60
61
62
def reset(self) -> None:
    """Reset to initial seed for replay."""
    self.reg = self.initial_seed

DecisionMargin dataclass

How close a decision was to flipping.

Source code in src/sc_neurocore/explainability/explainability.py
Python
74
75
76
77
78
79
80
81
@dataclass
class DecisionMargin:
    """How close a decision was to flipping."""

    popcount: int
    threshold: int
    margin: int  # popcount - threshold (negative = no spike)
    confidence: float  # |margin| / bitstream_length

DecisionNode dataclass

One node in a spike decision tree.

Source code in src/sc_neurocore/explainability/explainability.py
Python
 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
@dataclass
class DecisionNode:
    """One node in a spike decision tree."""

    neuron_id: str
    popcount: int
    threshold: int
    bitstream_length: int
    probability: float
    scc_context: float = 0.0
    scc_influence: float = 0.0
    decision: SpikeDecision = SpikeDecision.UNDETERMINED
    children: List[DecisionNode] = field(default_factory=list)
    bitstream_hash: str = ""
    timestep: int = 0
    threshold_q16: int = 0
    layer_id: str = ""
    contributing_neurons: List[str] = field(default_factory=list)

    @property
    def is_leaf(self) -> bool:
        return len(self.children) == 0

    @property
    def margin(self) -> DecisionMargin:
        m = self.popcount - self.threshold
        conf = abs(m) / self.bitstream_length if self.bitstream_length > 0 else 0.0
        return DecisionMargin(self.popcount, self.threshold, m, conf)

SpikeDecisionTree

Captures "why this spike fired" as a verifiable decision tree.

Source code in src/sc_neurocore/explainability/explainability.py
Python
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
class SpikeDecisionTree:
    """Captures "why this spike fired" as a verifiable decision tree."""

    def __init__(self):
        self.root: Optional[DecisionNode] = None
        self._nodes: List[DecisionNode] = []

    def add_decision(
        self,
        neuron_id: str,
        bitstream: np.ndarray,
        threshold: int,
        scc: float = 0.0,
        parent: Optional[DecisionNode] = None,
        timestep: int = 0,
        layer_id: str = "",
        contributing_neurons: Optional[List[str]] = None,
        threshold_q16: int = 0,
    ) -> DecisionNode:
        """Record a spike decision from bitstream observation."""
        popcount = int(np.sum(bitstream))
        length = len(bitstream)
        prob = popcount / length if length > 0 else 0.0
        decision = SpikeDecision.SPIKE if popcount >= threshold else SpikeDecision.NO_SPIKE
        bs_hash = hashlib.sha256(bitstream.tobytes()).hexdigest()[:16]

        scc_influence = abs(scc) * (popcount / max(length, 1))

        node = DecisionNode(
            neuron_id=neuron_id,
            popcount=popcount,
            threshold=threshold,
            bitstream_length=length,
            probability=prob,
            scc_context=scc,
            scc_influence=scc_influence,
            decision=decision,
            bitstream_hash=bs_hash,
            timestep=timestep,
            layer_id=layer_id,
            contributing_neurons=contributing_neurons or [],
            threshold_q16=threshold_q16,
        )

        if parent is not None:
            parent.children.append(node)
        elif self.root is None:
            self.root = node

        self._nodes.append(node)
        return node

    @property
    def depth(self) -> int:
        if self.root is None:
            return 0
        return self._compute_depth(self.root)

    def _compute_depth(self, node: DecisionNode) -> int:
        if not node.children:
            return 1
        return 1 + max(self._compute_depth(c) for c in node.children)

    @property
    def num_spikes(self) -> int:
        return sum(1 for n in self._nodes if n.decision == SpikeDecision.SPIKE)

    @property
    def num_nodes(self) -> int:
        return len(self._nodes)

    def nodes_at_layer(self, layer_id: str) -> List[DecisionNode]:
        """Return all nodes at a given layer."""
        return [n for n in self._nodes if n.layer_id == layer_id]

    def nodes_at_timestep(self, timestep: int) -> List[DecisionNode]:
        """Return all nodes at a given timestep."""
        return [n for n in self._nodes if n.timestep == timestep]

    def get_node(self, neuron_id: str) -> Optional[DecisionNode]:
        """Look up a node by neuron ID."""
        for n in self._nodes:
            if n.neuron_id == neuron_id:
                return n
        return None

    def spike_path(self) -> List[DecisionNode]:
        """Return the chain of spiking nodes from root down."""
        if self.root is None:
            return []
        path = []
        self._collect_spike_path(self.root, path)
        return path

    def _collect_spike_path(self, node: DecisionNode, path: List[DecisionNode]) -> None:
        if node.decision == SpikeDecision.SPIKE:
            path.append(node)
        for c in node.children:
            self._collect_spike_path(c, path)

    def to_dict(self) -> Dict[str, Any]:
        if self.root is None:
            return {}
        return self._node_to_dict(self.root)

    def _node_to_dict(self, node: DecisionNode) -> Dict[str, Any]:
        return {
            "neuron_id": node.neuron_id,
            "popcount": node.popcount,
            "threshold": node.threshold,
            "probability": node.probability,
            "decision": node.decision.value,
            "bitstream_hash": node.bitstream_hash,
            "scc_influence": node.scc_influence,
            "margin": node.margin.margin,
            "confidence": node.margin.confidence,
            "timestep": node.timestep,
            "layer_id": node.layer_id,
            "contributing_neurons": node.contributing_neurons,
            "children": [self._node_to_dict(c) for c in node.children],
        }

add_decision(neuron_id, bitstream, threshold, scc=0.0, parent=None, timestep=0, layer_id='', contributing_neurons=None, threshold_q16=0)

Record a spike decision from bitstream observation.

Source code in src/sc_neurocore/explainability/explainability.py
Python
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
def add_decision(
    self,
    neuron_id: str,
    bitstream: np.ndarray,
    threshold: int,
    scc: float = 0.0,
    parent: Optional[DecisionNode] = None,
    timestep: int = 0,
    layer_id: str = "",
    contributing_neurons: Optional[List[str]] = None,
    threshold_q16: int = 0,
) -> DecisionNode:
    """Record a spike decision from bitstream observation."""
    popcount = int(np.sum(bitstream))
    length = len(bitstream)
    prob = popcount / length if length > 0 else 0.0
    decision = SpikeDecision.SPIKE if popcount >= threshold else SpikeDecision.NO_SPIKE
    bs_hash = hashlib.sha256(bitstream.tobytes()).hexdigest()[:16]

    scc_influence = abs(scc) * (popcount / max(length, 1))

    node = DecisionNode(
        neuron_id=neuron_id,
        popcount=popcount,
        threshold=threshold,
        bitstream_length=length,
        probability=prob,
        scc_context=scc,
        scc_influence=scc_influence,
        decision=decision,
        bitstream_hash=bs_hash,
        timestep=timestep,
        layer_id=layer_id,
        contributing_neurons=contributing_neurons or [],
        threshold_q16=threshold_q16,
    )

    if parent is not None:
        parent.children.append(node)
    elif self.root is None:
        self.root = node

    self._nodes.append(node)
    return node

nodes_at_layer(layer_id)

Return all nodes at a given layer.

Source code in src/sc_neurocore/explainability/explainability.py
Python
185
186
187
def nodes_at_layer(self, layer_id: str) -> List[DecisionNode]:
    """Return all nodes at a given layer."""
    return [n for n in self._nodes if n.layer_id == layer_id]

nodes_at_timestep(timestep)

Return all nodes at a given timestep.

Source code in src/sc_neurocore/explainability/explainability.py
Python
189
190
191
def nodes_at_timestep(self, timestep: int) -> List[DecisionNode]:
    """Return all nodes at a given timestep."""
    return [n for n in self._nodes if n.timestep == timestep]

get_node(neuron_id)

Look up a node by neuron ID.

Source code in src/sc_neurocore/explainability/explainability.py
Python
193
194
195
196
197
198
def get_node(self, neuron_id: str) -> Optional[DecisionNode]:
    """Look up a node by neuron ID."""
    for n in self._nodes:
        if n.neuron_id == neuron_id:
            return n
    return None

spike_path()

Return the chain of spiking nodes from root down.

Source code in src/sc_neurocore/explainability/explainability.py
Python
200
201
202
203
204
205
206
def spike_path(self) -> List[DecisionNode]:
    """Return the chain of spiking nodes from root down."""
    if self.root is None:
        return []
    path = []
    self._collect_spike_path(self.root, path)
    return path

ProvenanceStep dataclass

One step in a full provenance chain.

Source code in src/sc_neurocore/explainability/explainability.py
Python
240
241
242
243
244
245
246
247
248
@dataclass
class ProvenanceStep:
    """One step in a full provenance chain."""

    stage: str
    description: str
    data_hash: str
    timestamp_ns: int
    metadata: Dict[str, Any] = field(default_factory=dict)

ProvenanceTrace

Full chain from input → encoding → computation → spike decision.

Source code in src/sc_neurocore/explainability/explainability.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
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
class ProvenanceTrace:
    """Full chain from input → encoding → computation → spike decision."""

    def __init__(self):
        self._steps: List[ProvenanceStep] = []
        self._complete = False

    def add_step(
        self,
        stage: str,
        description: str,
        data: Optional[np.ndarray] = None,
        metadata: Optional[Dict[str, Any]] = None,
    ) -> ProvenanceStep:
        """Record one provenance step."""
        if data is not None:
            data_hash = hashlib.sha256(data.tobytes()).hexdigest()[:16]
        else:
            data_hash = hashlib.sha256(description.encode()).hexdigest()[:16]

        step = ProvenanceStep(
            stage=stage,
            description=description,
            data_hash=data_hash,
            timestamp_ns=time.perf_counter_ns(),
            metadata=metadata or {},
        )
        self._steps.append(step)
        return step

    def finalize(self) -> None:
        self._complete = True

    @property
    def is_complete(self) -> bool:
        return self._complete

    @property
    def num_steps(self) -> int:
        return len(self._steps)

    @property
    def chain_hash(self) -> str:
        """Hash of the entire provenance chain for tamper detection."""
        h = hashlib.sha256()
        for step in self._steps:
            h.update(step.data_hash.encode())
            h.update(step.stage.encode())
        return h.hexdigest()

    def to_list(self) -> List[Dict[str, Any]]:
        return [
            {
                "stage": s.stage,
                "description": s.description,
                "data_hash": s.data_hash,
                "timestamp_ns": s.timestamp_ns,
                "metadata": s.metadata,
            }
            for s in self._steps
        ]

chain_hash property

Hash of the entire provenance chain for tamper detection.

add_step(stage, description, data=None, metadata=None)

Record one provenance step.

Source code in src/sc_neurocore/explainability/explainability.py
Python
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
def add_step(
    self,
    stage: str,
    description: str,
    data: Optional[np.ndarray] = None,
    metadata: Optional[Dict[str, Any]] = None,
) -> ProvenanceStep:
    """Record one provenance step."""
    if data is not None:
        data_hash = hashlib.sha256(data.tobytes()).hexdigest()[:16]
    else:
        data_hash = hashlib.sha256(description.encode()).hexdigest()[:16]

    step = ProvenanceStep(
        stage=stage,
        description=description,
        data_hash=data_hash,
        timestamp_ns=time.perf_counter_ns(),
        metadata=metadata or {},
    )
    self._steps.append(step)
    return step

RegulatoryMetadata dataclass

IEC 62304 / FDA SaMD traceability fields.

Source code in src/sc_neurocore/explainability/explainability.py
Python
317
318
319
320
321
322
323
324
325
326
327
328
@dataclass
class RegulatoryMetadata:
    """IEC 62304 / FDA SaMD traceability fields."""

    device_class: str = "Class II"
    risk_level: str = "moderate"
    intended_use: str = ""
    software_version: str = ""
    udi: str = ""  # Unique Device Identifier
    sudi_hash: str = ""  # Hash of the software + config
    operator_id: str = ""
    review_status: str = "pending"

Cross-reference to SymbiYosys formal verification.

Source code in src/sc_neurocore/explainability/explainability.py
Python
331
332
333
334
335
336
337
338
339
@dataclass
class FormalPropertyLink:
    """Cross-reference to SymbiYosys formal verification."""

    property_name: str
    property_file: str = ""
    status: str = "unverified"  # proven / cex / unverified
    bounded_depth: int = 0
    engine: str = "sby"

VerifiabilityReport dataclass

Formal audit report with hash verification.

Source code in src/sc_neurocore/explainability/explainability.py
Python
342
343
344
345
346
347
348
349
350
351
352
353
354
@dataclass
class VerifiabilityReport:
    """Formal audit report with hash verification."""

    chain_hash: str
    num_steps: int
    all_hashes_valid: bool
    decision_tree_depth: int
    total_spikes: int
    replay_seed: int
    replay_matches: bool
    regulatory: Optional[RegulatoryMetadata] = None
    formal_properties: List[FormalPropertyLink] = field(default_factory=list)

SensitivityResult dataclass

Result of a 'what-if' threshold perturbation.

Source code in src/sc_neurocore/explainability/explainability.py
Python
360
361
362
363
364
365
366
367
368
369
@dataclass
class SensitivityResult:
    """Result of a 'what-if' threshold perturbation."""

    neuron_id: str
    original_threshold: int
    perturbed_threshold: int
    original_decision: SpikeDecision
    perturbed_decision: SpikeDecision
    flipped: bool

SensitivityAnalyzer

Counterfactual analysis: 'would the decision flip if threshold ±N?'

Source code in src/sc_neurocore/explainability/explainability.py
Python
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
class SensitivityAnalyzer:
    """Counterfactual analysis: 'would the decision flip if threshold ±N?'"""

    @staticmethod
    def analyze(
        node: DecisionNode,
        perturbations: Optional[List[int]] = None,
    ) -> List[SensitivityResult]:
        if perturbations is None:
            perturbations = [-10, -5, -1, 1, 5, 10]
        results = []
        for delta in perturbations:
            new_t = max(0, node.threshold + delta)
            new_dec = SpikeDecision.SPIKE if node.popcount >= new_t else SpikeDecision.NO_SPIKE
            results.append(
                SensitivityResult(
                    neuron_id=node.neuron_id,
                    original_threshold=node.threshold,
                    perturbed_threshold=new_t,
                    original_decision=node.decision,
                    perturbed_decision=new_dec,
                    flipped=(new_dec != node.decision),
                )
            )
        return results

    @staticmethod
    def critical_delta(node: DecisionNode) -> int:
        """Smallest threshold change that flips the decision."""
        m = node.margin
        if m.margin >= 0:
            return m.margin + 1
        return m.margin

critical_delta(node) staticmethod

Smallest threshold change that flips the decision.

Source code in src/sc_neurocore/explainability/explainability.py
Python
398
399
400
401
402
403
404
@staticmethod
def critical_delta(node: DecisionNode) -> int:
    """Smallest threshold change that flips the decision."""
    m = node.margin
    if m.margin >= 0:
        return m.margin + 1
    return m.margin

CausalAttribution dataclass

Attribution of a spike to upstream neurons.

Source code in src/sc_neurocore/explainability/explainability.py
Python
410
411
412
413
414
415
416
417
418
419
420
421
@dataclass
class CausalAttribution:
    """Attribution of a spike to upstream neurons."""

    target_neuron: str
    attributions: Dict[str, float]  # source_neuron -> contribution weight
    total_contribution: float

    @property
    def top_contributors(self) -> List[Tuple[str, float]]:
        """Sorted (descending) list of contributing neurons."""
        return sorted(self.attributions.items(), key=lambda x: x[1], reverse=True)

top_contributors property

Sorted (descending) list of contributing neurons.

CausalAttributor

Computes causal attribution from input neurons to output spike.

Source code in src/sc_neurocore/explainability/explainability.py
Python
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
class CausalAttributor:
    """Computes causal attribution from input neurons to output spike."""

    @staticmethod
    def attribute(
        target: DecisionNode,
        input_bitstreams: Dict[str, np.ndarray],
        weights: Optional[Dict[str, float]] = None,
    ) -> CausalAttribution:
        """Compute per-input-neuron contribution to the target popcount."""
        attribs: Dict[str, float] = {}
        for nid, bs in input_bitstreams.items():
            w = weights.get(nid, 1.0) if weights else 1.0
            contribution = float(np.sum(bs)) * w
            attribs[nid] = contribution
        total = sum(attribs.values())
        return CausalAttribution(
            target_neuron=target.neuron_id,
            attributions=attribs,
            total_contribution=total,
        )

attribute(target, input_bitstreams, weights=None) staticmethod

Compute per-input-neuron contribution to the target popcount.

Source code in src/sc_neurocore/explainability/explainability.py
Python
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
@staticmethod
def attribute(
    target: DecisionNode,
    input_bitstreams: Dict[str, np.ndarray],
    weights: Optional[Dict[str, float]] = None,
) -> CausalAttribution:
    """Compute per-input-neuron contribution to the target popcount."""
    attribs: Dict[str, float] = {}
    for nid, bs in input_bitstreams.items():
        w = weights.get(nid, 1.0) if weights else 1.0
        contribution = float(np.sum(bs)) * w
        attribs[nid] = contribution
    total = sum(attribs.values())
    return CausalAttribution(
        target_neuron=target.neuron_id,
        attributions=attribs,
        total_contribution=total,
    )

DiffEntry dataclass

One field that differs between two explanations.

Source code in src/sc_neurocore/explainability/explainability.py
Python
450
451
452
453
454
455
456
@dataclass
class DiffEntry:
    """One field that differs between two explanations."""

    field: str
    value_a: Any
    value_b: Any

ExplanationDiff

Compares two decision nodes to find divergence points.

Source code in src/sc_neurocore/explainability/explainability.py
Python
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
class ExplanationDiff:
    """Compares two decision nodes to find divergence points."""

    @staticmethod
    def diff(a: DecisionNode, b: DecisionNode) -> List[DiffEntry]:
        diffs = []
        for attr in [
            "neuron_id",
            "popcount",
            "threshold",
            "bitstream_length",
            "probability",
            "scc_context",
            "decision",
            "bitstream_hash",
        ]:
            va = getattr(a, attr)
            vb = getattr(b, attr)
            if va != vb:
                diffs.append(DiffEntry(attr, va, vb))
        return diffs

TemporalWindow

Records decisions across timesteps for temporal attribution.

Source code in src/sc_neurocore/explainability/explainability.py
Python
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
class TemporalWindow:
    """Records decisions across timesteps for temporal attribution."""

    def __init__(self):
        self._windows: Dict[int, List[DecisionNode]] = {}

    def add(self, node: DecisionNode) -> None:
        self._windows.setdefault(node.timestep, []).append(node)

    def spike_rate_at(self, timestep: int) -> float:
        nodes = self._windows.get(timestep, [])
        if not nodes:
            return 0.0
        return sum(1 for n in nodes if n.decision == SpikeDecision.SPIKE) / len(nodes)

    def active_timesteps(self) -> List[int]:
        return sorted(self._windows.keys())

    def peak_timestep(self) -> int:
        """Timestep with the highest spike rate."""
        best_t = 0
        best_rate = -1.0
        for t in self._windows:
            rate = self.spike_rate_at(t)
            if rate > best_rate:
                best_rate = rate
                best_t = t
        return best_t

    @property
    def num_timesteps(self) -> int:
        return len(self._windows)

peak_timestep()

Timestep with the highest spike rate.

Source code in src/sc_neurocore/explainability/explainability.py
Python
503
504
505
506
507
508
509
510
511
512
def peak_timestep(self) -> int:
    """Timestep with the highest spike rate."""
    best_t = 0
    best_rate = -1.0
    for t in self._windows:
        rate = self.spike_rate_at(t)
        if rate > best_rate:
            best_rate = rate
            best_t = t
    return best_t

NaturalLanguageExplainer

Generates human-readable explanation strings.

Source code in src/sc_neurocore/explainability/explainability.py
Python
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
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
class NaturalLanguageExplainer:
    """Generates human-readable explanation strings."""

    @staticmethod
    def explain_node(node: DecisionNode) -> str:
        m = node.margin
        if node.decision == SpikeDecision.SPIKE:
            desc = (
                f"Neuron {node.neuron_id} fired at timestep {node.timestep}. "
                f"Popcount {node.popcount} exceeded threshold {node.threshold} "
                f"by {m.margin} bits (confidence {m.confidence:.1%}). "
                f"Encoded probability was {node.probability:.3f}."
            )
        else:
            desc = (
                f"Neuron {node.neuron_id} did NOT fire at timestep {node.timestep}. "
                f"Popcount {node.popcount} fell short of threshold {node.threshold} "
                f"by {abs(m.margin)} bits. "
                f"Encoded probability was {node.probability:.3f}."
            )
        if node.scc_context > 0:
            desc += f" Correlation context SCC={node.scc_context:.3f} may have biased encoding."
        if node.contributing_neurons:
            desc += f" Driven by inputs: {', '.join(node.contributing_neurons[:5])}."
        return desc

    @staticmethod
    def explain_attribution(attr: CausalAttribution) -> str:
        top = attr.top_contributors[:3]
        parts = [f"{nid} ({w:.1f})" for nid, w in top]
        return (
            f"Spike at {attr.target_neuron} was primarily caused by: "
            f"{', '.join(parts)}. Total input contribution: {attr.total_contribution:.1f}."
        )

    @staticmethod
    def explain_sensitivity(results: List[SensitivityResult]) -> str:
        flips = [r for r in results if r.flipped]
        if not flips:
            return "Decision is robust to all tested perturbations."
        smallest = min(flips, key=lambda r: abs(r.perturbed_threshold - r.original_threshold))
        return (
            f"Decision would flip if threshold changed by "
            f"{smallest.perturbed_threshold - smallest.original_threshold:+d} "
            f"(from {smallest.original_threshold} to {smallest.perturbed_threshold})."
        )

    @staticmethod
    def enhance_with_local_llm(
        text: str,
        *,
        bridge: Any,
        question: str = (
            "Rewrite this deterministic spike explanation for a human operator. "
            "Preserve all numeric facts and keep the wording concise."
        ),
    ) -> str:
        """Enhance a deterministic explanation through the local LLM bridge.

        The caller must supply a configured ``LocalLLMBridge`` instance so this
        module keeps no hard runtime dependency on any local model server.
        """
        response = bridge.chat(f"{question}\n\nBase explanation:\n{text}")
        return response.text

    @staticmethod
    def explain_node_with_local_llm(
        node: DecisionNode,
        *,
        bridge: Any,
        question: str = (
            "Explain this spike decision for a human operator in two short paragraphs. "
            "Do not change or invent numeric values."
        ),
    ) -> str:
        """Generate a local-LLM-enhanced explanation for one decision node."""
        base = NaturalLanguageExplainer.explain_node(node)
        return NaturalLanguageExplainer.enhance_with_local_llm(
            base,
            bridge=bridge,
            question=question,
        )

enhance_with_local_llm(text, *, bridge, question='Rewrite this deterministic spike explanation for a human operator. Preserve all numeric facts and keep the wording concise.') staticmethod

Enhance a deterministic explanation through the local LLM bridge.

The caller must supply a configured LocalLLMBridge instance so this module keeps no hard runtime dependency on any local model server.

Source code in src/sc_neurocore/explainability/explainability.py
Python
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
@staticmethod
def enhance_with_local_llm(
    text: str,
    *,
    bridge: Any,
    question: str = (
        "Rewrite this deterministic spike explanation for a human operator. "
        "Preserve all numeric facts and keep the wording concise."
    ),
) -> str:
    """Enhance a deterministic explanation through the local LLM bridge.

    The caller must supply a configured ``LocalLLMBridge`` instance so this
    module keeps no hard runtime dependency on any local model server.
    """
    response = bridge.chat(f"{question}\n\nBase explanation:\n{text}")
    return response.text

explain_node_with_local_llm(node, *, bridge, question='Explain this spike decision for a human operator in two short paragraphs. Do not change or invent numeric values.') staticmethod

Generate a local-LLM-enhanced explanation for one decision node.

Source code in src/sc_neurocore/explainability/explainability.py
Python
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
@staticmethod
def explain_node_with_local_llm(
    node: DecisionNode,
    *,
    bridge: Any,
    question: str = (
        "Explain this spike decision for a human operator in two short paragraphs. "
        "Do not change or invent numeric values."
    ),
) -> str:
    """Generate a local-LLM-enhanced explanation for one decision node."""
    base = NaturalLanguageExplainer.explain_node(node)
    return NaturalLanguageExplainer.enhance_with_local_llm(
        base,
        bridge=bridge,
        question=question,
    )

MultiLayerTrace

Traces decisions across network layers.

Source code in src/sc_neurocore/explainability/explainability.py
Python
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
class MultiLayerTrace:
    """Traces decisions across network layers."""

    def __init__(self):
        self._layers: Dict[str, List[DecisionNode]] = {}

    def add(self, node: DecisionNode) -> None:
        self._layers.setdefault(node.layer_id, []).append(node)

    @property
    def layer_ids(self) -> List[str]:
        return list(self._layers.keys())

    def spikes_at_layer(self, layer_id: str) -> int:
        return sum(1 for n in self._layers.get(layer_id, []) if n.decision == SpikeDecision.SPIKE)

    def spike_rate_at_layer(self, layer_id: str) -> float:
        nodes = self._layers.get(layer_id, [])
        if not nodes:
            return 0.0
        return sum(1 for n in nodes if n.decision == SpikeDecision.SPIKE) / len(nodes)

    def propagation_path(self) -> List[Dict[str, Any]]:
        """Per-layer spike rate for visualising propagation."""
        return [
            {"layer": lid, "spike_rate": self.spike_rate_at_layer(lid), "count": len(nodes)}
            for lid, nodes in self._layers.items()
        ]

propagation_path()

Per-layer spike rate for visualising propagation.

Source code in src/sc_neurocore/explainability/explainability.py
Python
631
632
633
634
635
636
def propagation_path(self) -> List[Dict[str, Any]]:
    """Per-layer spike rate for visualising propagation."""
    return [
        {"layer": lid, "spike_rate": self.spike_rate_at_layer(lid), "count": len(nodes)}
        for lid, nodes in self._layers.items()
    ]

SymbolicPathStep dataclass

One step in a symbolic decision path.

Source code in src/sc_neurocore/explainability/explainability.py
Python
642
643
644
645
646
647
648
@dataclass
class SymbolicPathStep:
    """One step in a symbolic decision path."""

    neuron_id: str
    decision: SpikeDecision
    reason: str

SymbolicPath

Human-readable symbolic path: input → encoding → decision.

Source code in src/sc_neurocore/explainability/explainability.py
Python
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
class SymbolicPath:
    """Human-readable symbolic path: input → encoding → decision."""

    def __init__(self):
        self.steps: List[SymbolicPathStep] = []

    def add(self, neuron_id: str, decision: SpikeDecision, reason: str) -> None:
        self.steps.append(SymbolicPathStep(neuron_id, decision, reason))

    @property
    def length(self) -> int:
        return len(self.steps)

    def to_list(self) -> List[Dict[str, str]]:
        return [
            {"neuron": s.neuron_id, "decision": s.decision.value, "reason": s.reason}
            for s in self.steps
        ]

ExplainabilityEngine

End-to-end explainability: replay + decision tree + provenance.

Source code in src/sc_neurocore/explainability/explainability.py
Python
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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
class ExplainabilityEngine:
    """End-to-end explainability: replay + decision tree + provenance."""

    def __init__(self, seed: int = 0xACE1):
        self.seed = seed
        self.replay = LFSRReplay(seed)
        self.tree = SpikeDecisionTree()
        self.provenance = ProvenanceTrace()
        self.temporal = TemporalWindow()
        self.multi_layer = MultiLayerTrace()
        self.symbolic = SymbolicPath()
        self._replayed_bitstreams: Dict[str, np.ndarray] = {}

    def explain_spike(
        self,
        neuron_id: str,
        threshold_q16: int,
        bitstream_length: int,
        spike_threshold_count: int,
        scc: float = 0.0,
        timestep: int = 0,
        layer_id: str = "",
        contributing_neurons: Optional[List[str]] = None,
    ) -> DecisionNode:
        """Explain one spike decision via deterministic replay.

        Replays the LFSR from the current seed state, generates the
        exact bitstream, and records the decision in the tree and trace.
        """
        self.provenance.add_step(
            "input",
            f"Neuron {neuron_id}: threshold_q16={threshold_q16}, length={bitstream_length}",
        )

        replay = LFSRReplay(self.seed)
        bitstream = replay.encode(threshold_q16, bitstream_length)
        self._replayed_bitstreams[neuron_id] = bitstream

        self.provenance.add_step(
            "encoding",
            f"LFSR encode seed={self.seed:#06x}, threshold={threshold_q16}",
            data=bitstream,
        )

        node = self.tree.add_decision(
            neuron_id=neuron_id,
            bitstream=bitstream,
            threshold=spike_threshold_count,
            scc=scc,
            timestep=timestep,
            layer_id=layer_id,
            contributing_neurons=contributing_neurons,
            threshold_q16=threshold_q16,
        )

        self.temporal.add(node)
        self.multi_layer.add(node)

        reason = (
            f"popcount({node.popcount}) {'≥' if node.decision == SpikeDecision.SPIKE else '<'} "
            f"threshold({spike_threshold_count})"
        )
        self.symbolic.add(neuron_id, node.decision, reason)

        self.provenance.add_step(
            "decision",
            f"Neuron {neuron_id}: {node.decision.value} (popcount={node.popcount}/{spike_threshold_count})",
            metadata={
                "popcount": node.popcount,
                "threshold": spike_threshold_count,
                "probability": node.probability,
                "margin": node.margin.margin,
                "scc_influence": node.scc_influence,
            },
        )

        return node

    def verify(
        self,
        regulatory: Optional[RegulatoryMetadata] = None,
        formal_properties: Optional[List[FormalPropertyLink]] = None,
    ) -> VerifiabilityReport:
        """Generate a verifiability report with full replay check."""
        self.provenance.finalize()

        all_match = True
        for nid, stored_bs in self._replayed_bitstreams.items():
            fresh = LFSRReplay(self.seed)
            node = self.tree.get_node(nid)
            if node is not None:
                re_bs = fresh.encode(
                    threshold=node.threshold_q16,
                    length=node.bitstream_length,
                )
                if not np.array_equal(
                    stored_bs[: min(len(stored_bs), len(re_bs))],
                    re_bs[: min(len(stored_bs), len(re_bs))],
                ):
                    all_match = False

        return VerifiabilityReport(
            chain_hash=self.provenance.chain_hash,
            num_steps=self.provenance.num_steps,
            all_hashes_valid=all_match,
            decision_tree_depth=self.tree.depth,
            total_spikes=self.tree.num_spikes,
            replay_seed=self.seed,
            replay_matches=all_match,
            regulatory=regulatory,
            formal_properties=formal_properties or [],
        )

    def replay_bitstream(
        self,
        threshold_q16: int,
        length: int,
    ) -> np.ndarray:
        """Replay a bitstream from the engine's seed (for external comparison)."""
        replay = LFSRReplay(self.seed)
        return replay.encode(threshold_q16, length)

    def sensitivity(
        self,
        node: DecisionNode,
        perturbations: Optional[List[int]] = None,
    ) -> List[SensitivityResult]:
        """Run sensitivity analysis on a decision node."""
        return SensitivityAnalyzer.analyze(node, perturbations)

    def attribute(
        self,
        target: DecisionNode,
        input_bitstreams: Dict[str, np.ndarray],
        weights: Optional[Dict[str, float]] = None,
    ) -> CausalAttribution:
        """Compute causal attribution for a decision."""
        return CausalAttributor.attribute(target, input_bitstreams, weights)

    def explain_spike_with_local_llm(
        self,
        neuron_id: str,
        threshold_q16: int,
        bitstream_length: int,
        spike_threshold_count: int,
        *,
        bridge: Any,
        scc: float = 0.0,
        timestep: int = 0,
        layer_id: str = "",
        contributing_neurons: Optional[List[str]] = None,
        question: str = (
            "Explain this spike decision for a human operator in two short paragraphs. "
            "Do not change or invent numeric values."
        ),
    ) -> tuple[DecisionNode, str]:
        """Run the deterministic explainability path, then enhance it locally."""
        node = self.explain_spike(
            neuron_id=neuron_id,
            threshold_q16=threshold_q16,
            bitstream_length=bitstream_length,
            spike_threshold_count=spike_threshold_count,
            scc=scc,
            timestep=timestep,
            layer_id=layer_id,
            contributing_neurons=contributing_neurons,
        )
        text = NaturalLanguageExplainer.explain_node_with_local_llm(
            node,
            bridge=bridge,
            question=question,
        )
        return node, text

explain_spike(neuron_id, threshold_q16, bitstream_length, spike_threshold_count, scc=0.0, timestep=0, layer_id='', contributing_neurons=None)

Explain one spike decision via deterministic replay.

Replays the LFSR from the current seed state, generates the exact bitstream, and records the decision in the tree and trace.

Source code in src/sc_neurocore/explainability/explainability.py
Python
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
def explain_spike(
    self,
    neuron_id: str,
    threshold_q16: int,
    bitstream_length: int,
    spike_threshold_count: int,
    scc: float = 0.0,
    timestep: int = 0,
    layer_id: str = "",
    contributing_neurons: Optional[List[str]] = None,
) -> DecisionNode:
    """Explain one spike decision via deterministic replay.

    Replays the LFSR from the current seed state, generates the
    exact bitstream, and records the decision in the tree and trace.
    """
    self.provenance.add_step(
        "input",
        f"Neuron {neuron_id}: threshold_q16={threshold_q16}, length={bitstream_length}",
    )

    replay = LFSRReplay(self.seed)
    bitstream = replay.encode(threshold_q16, bitstream_length)
    self._replayed_bitstreams[neuron_id] = bitstream

    self.provenance.add_step(
        "encoding",
        f"LFSR encode seed={self.seed:#06x}, threshold={threshold_q16}",
        data=bitstream,
    )

    node = self.tree.add_decision(
        neuron_id=neuron_id,
        bitstream=bitstream,
        threshold=spike_threshold_count,
        scc=scc,
        timestep=timestep,
        layer_id=layer_id,
        contributing_neurons=contributing_neurons,
        threshold_q16=threshold_q16,
    )

    self.temporal.add(node)
    self.multi_layer.add(node)

    reason = (
        f"popcount({node.popcount}) {'≥' if node.decision == SpikeDecision.SPIKE else '<'} "
        f"threshold({spike_threshold_count})"
    )
    self.symbolic.add(neuron_id, node.decision, reason)

    self.provenance.add_step(
        "decision",
        f"Neuron {neuron_id}: {node.decision.value} (popcount={node.popcount}/{spike_threshold_count})",
        metadata={
            "popcount": node.popcount,
            "threshold": spike_threshold_count,
            "probability": node.probability,
            "margin": node.margin.margin,
            "scc_influence": node.scc_influence,
        },
    )

    return node

verify(regulatory=None, formal_properties=None)

Generate a verifiability report with full replay check.

Source code in src/sc_neurocore/explainability/explainability.py
Python
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
def verify(
    self,
    regulatory: Optional[RegulatoryMetadata] = None,
    formal_properties: Optional[List[FormalPropertyLink]] = None,
) -> VerifiabilityReport:
    """Generate a verifiability report with full replay check."""
    self.provenance.finalize()

    all_match = True
    for nid, stored_bs in self._replayed_bitstreams.items():
        fresh = LFSRReplay(self.seed)
        node = self.tree.get_node(nid)
        if node is not None:
            re_bs = fresh.encode(
                threshold=node.threshold_q16,
                length=node.bitstream_length,
            )
            if not np.array_equal(
                stored_bs[: min(len(stored_bs), len(re_bs))],
                re_bs[: min(len(stored_bs), len(re_bs))],
            ):
                all_match = False

    return VerifiabilityReport(
        chain_hash=self.provenance.chain_hash,
        num_steps=self.provenance.num_steps,
        all_hashes_valid=all_match,
        decision_tree_depth=self.tree.depth,
        total_spikes=self.tree.num_spikes,
        replay_seed=self.seed,
        replay_matches=all_match,
        regulatory=regulatory,
        formal_properties=formal_properties or [],
    )

replay_bitstream(threshold_q16, length)

Replay a bitstream from the engine's seed (for external comparison).

Source code in src/sc_neurocore/explainability/explainability.py
Python
787
788
789
790
791
792
793
794
def replay_bitstream(
    self,
    threshold_q16: int,
    length: int,
) -> np.ndarray:
    """Replay a bitstream from the engine's seed (for external comparison)."""
    replay = LFSRReplay(self.seed)
    return replay.encode(threshold_q16, length)

sensitivity(node, perturbations=None)

Run sensitivity analysis on a decision node.

Source code in src/sc_neurocore/explainability/explainability.py
Python
796
797
798
799
800
801
802
def sensitivity(
    self,
    node: DecisionNode,
    perturbations: Optional[List[int]] = None,
) -> List[SensitivityResult]:
    """Run sensitivity analysis on a decision node."""
    return SensitivityAnalyzer.analyze(node, perturbations)

attribute(target, input_bitstreams, weights=None)

Compute causal attribution for a decision.

Source code in src/sc_neurocore/explainability/explainability.py
Python
804
805
806
807
808
809
810
811
def attribute(
    self,
    target: DecisionNode,
    input_bitstreams: Dict[str, np.ndarray],
    weights: Optional[Dict[str, float]] = None,
) -> CausalAttribution:
    """Compute causal attribution for a decision."""
    return CausalAttributor.attribute(target, input_bitstreams, weights)

explain_spike_with_local_llm(neuron_id, threshold_q16, bitstream_length, spike_threshold_count, *, bridge, scc=0.0, timestep=0, layer_id='', contributing_neurons=None, question='Explain this spike decision for a human operator in two short paragraphs. Do not change or invent numeric values.')

Run the deterministic explainability path, then enhance it locally.

Source code in src/sc_neurocore/explainability/explainability.py
Python
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
def explain_spike_with_local_llm(
    self,
    neuron_id: str,
    threshold_q16: int,
    bitstream_length: int,
    spike_threshold_count: int,
    *,
    bridge: Any,
    scc: float = 0.0,
    timestep: int = 0,
    layer_id: str = "",
    contributing_neurons: Optional[List[str]] = None,
    question: str = (
        "Explain this spike decision for a human operator in two short paragraphs. "
        "Do not change or invent numeric values."
    ),
) -> tuple[DecisionNode, str]:
    """Run the deterministic explainability path, then enhance it locally."""
    node = self.explain_spike(
        neuron_id=neuron_id,
        threshold_q16=threshold_q16,
        bitstream_length=bitstream_length,
        spike_threshold_count=spike_threshold_count,
        scc=scc,
        timestep=timestep,
        layer_id=layer_id,
        contributing_neurons=contributing_neurons,
    )
    text = NaturalLanguageExplainer.explain_node_with_local_llm(
        node,
        bridge=bridge,
        question=question,
    )
    return node, text