perforatedai.dendrite_stats

Record dendrite-to-neuron-error correlation statistics during PAI training.

  1"""
  2Record dendrite-to-neuron-error correlation statistics during PAI training.
  3"""
  4
  5import csv
  6from dataclasses import dataclass, asdict
  7from pathlib import Path
  8from typing import Any
  9
 10import torch
 11
 12from perforatedai import globals_perforatedai as GPA
 13
 14__all__ = ["DendriteStatisticsRecord", "DendriteStatisticsRecorder"]
 15
 16
 17@dataclass
 18class DendriteStatisticsRecord:
 19    """
 20    Statistics for one dendrite added to one layer.
 21
 22    Attributes:
 23        add_event_index: Which dendrite-addition event this record belongs to,
 24            counting from zero.
 25        layer_name: The name of the parent neuron module.
 26        epoch_added: The value of num_epochs_run when the dendrite was added.
 27        best_absolute_pearson_correlation: Largest absolute Pearson correlation
 28            across all output nodes and candidates, bounded in [0, 1].
 29        mean_absolute_pearson_correlation: Mean of the same quantity over nodes.
 30        best_absolute_covariance: Largest absolute covariance across all output
 31            nodes and candidates. Unbounded. This is the scoring quantity.
 32        mean_absolute_covariance: Mean of the same quantity over nodes.
 33        mean_absolute_neuron_error_at_add: Mean absolute per-node parent error
 34            measured during the dendrite phase that produced this dendrite.
 35        mean_absolute_neuron_error_after_retraining: The same measurement taken
 36            during the following dendrite phase, after retraining. Stays None if
 37            training ended before another dendrite phase ran.
 38        neuron_error_reduction: The decrease in mean absolute per-node error
 39            between those two measurements. Positive means the error fell. Stays
 40            None whenever the after-retraining measurement is None.
 41        validation_score_before: Best neuron-phase validation score before this
 42            dendrite was added.
 43        validation_score_after: Best neuron-phase validation score after this
 44            dendrite was added and the network was retrained.
 45        validation_score_improvement: The improvement between the two, signed so
 46            that positive always means better, whichever direction is better.
 47        retained: True if this dendrite generation was kept, False if it was
 48            tried and discarded, None if training ended before the decision was
 49            made. Rows with retained False describe a generation that was rolled
 50            back, so their error and score changes do not measure a dendrite's
 51            effect and should be filtered out before analysis.
 52    """
 53
 54    add_event_index: int
 55    layer_name: str
 56    epoch_added: int
 57    best_absolute_pearson_correlation: float
 58    mean_absolute_pearson_correlation: float
 59    best_absolute_covariance: float
 60    mean_absolute_covariance: float
 61    mean_absolute_neuron_error_at_add: float
 62    retained: bool | None = None
 63    mean_absolute_neuron_error_after_retraining: float | None = None
 64    neuron_error_reduction: float | None = None
 65    validation_score_before: float | None = None
 66    validation_score_after: float | None = None
 67    validation_score_improvement: float | None = None
 68
 69
 70def _compute_correlation_and_error_summary_for_one_layer(
 71    neuron_module: Any,
 72) -> dict[str, float] | None:
 73    """Collapse one layer's per-node correlation buffers to scalar summaries.
 74
 75    Each correlation buffer is one-dimensional, of shape (N,), holding one
 76    scalar per output node. The buffers are registered lazily by
 77    DendriteValueTracker.setup_arrays on the first backward pass, so they may
 78    not exist yet. On a fresh run only dendrite_values[0] is set up, because
 79    filter_backward calls setup_arrays on that index specifically; candidates
 80    beyond the first only receive buffers when a state dict is loaded. Any
 81    candidate whose buffers are missing is skipped rather than raising.
 82
 83    Args:
 84        neuron_module: A PAINeuronModule taken from the tracker's
 85            neuron_module_vector.
 86
 87    Returns:
 88        A dictionary of scalar summaries for this layer, or None if no
 89        candidate had its correlation buffers allocated yet.
 90    """
 91    candidate_count: int = GPA.pc.get_global_candidates()
 92    pearson_per_candidate: list[torch.Tensor] = []
 93    covariance_per_candidate: list[torch.Tensor] = []
 94
 95    for candidate_index in range(candidate_count):
 96        values = neuron_module.dendrite_module.dendrite_values[candidate_index]
 97        pearson = getattr(values, "best_pearson_correlation", None)
 98        covariance = getattr(values, "prev_dendrite_candidate_correlation", None)
 99        if pearson is None or covariance is None:
100            continue
101        pearson_per_candidate.append(pearson.detach().abs().float().cpu())
102        covariance_per_candidate.append(covariance.detach().abs().float().cpu())
103
104    if not pearson_per_candidate:
105        return None
106
107    # Dimensions: allocated_candidate_count x number_of_output_nodes.
108    stacked_pearson: torch.Tensor = torch.stack(pearson_per_candidate)
109    stacked_covariance: torch.Tensor = torch.stack(covariance_per_candidate)
110
111    # The parent error is a property of the neuron, not of any one candidate,
112    # so candidate zero is representative.
113    parent_error_buffer = getattr(
114        neuron_module.dendrite_module.dendrite_values[0],
115        "normal_pass_average_d",
116        None,
117    )
118    if parent_error_buffer is None:
119        return None
120    parent_error: torch.Tensor = parent_error_buffer.detach().abs().float().cpu()
121
122    return {
123        "best_absolute_pearson_correlation": stacked_pearson.max().item(),
124        "mean_absolute_pearson_correlation": stacked_pearson.mean().item(),
125        "best_absolute_covariance": stacked_covariance.max().item(),
126        "mean_absolute_covariance": stacked_covariance.mean().item(),
127        "mean_absolute_neuron_error": parent_error.mean().item(),
128    }
129
130
131class DendriteStatisticsRecorder:
132    """
133    Collect per-dendrite correlation and error-reduction statistics.
134
135    The recorder must be driven from the training loop because the values it
136    reads are overwritten by the mode switch inside add_validation_score. Call
137    capture_mode_and_layer_statistics_before_add_validation_score immediately
138    before that call, and
139    record_score_and_detect_dendrite_addition_after_add_validation_score
140    immediately after it, every epoch.
141    """
142
143    def __init__(self, output_directory: Path) -> None:
144        """Initialize the recorder.
145
146        Args:
147            output_directory: Directory the CSV file is written into. Created if
148                it does not exist.
149        """
150        self._output_directory: Path = output_directory
151        self._output_directory.mkdir(parents=True, exist_ok=True)
152        self._records: list[DendriteStatisticsRecord] = []
153        self._latest_snapshot: dict[str, dict[str, float]] = {}
154        self._previous_dendrite_count: int = 0
155        self._pending_records: list[DendriteStatisticsRecord] = []
156        self._neuron_phase_scores: list[float] = []
157        self._mode_during_epoch: str | None = None
158        self._snapshot_is_fresh: bool = False
159        self._previous_integrated_count: int = 0
160
161    def capture_mode_and_layer_statistics_before_add_validation_score(self) -> None:
162        """Snapshot every layer's correlation buffers before the mode can switch.
163
164        Records the current mode unconditionally, because
165        record_score_and_detect_dendrite_addition_after_add_validation_score
166        needs to know which phase this epoch belonged to and cannot determine that
167        afterward. Takes the buffer snapshot only during a dendrite-training
168        phase, when the buffers hold meaningful values.
169        """
170        tracker = GPA.pai_tracker
171        if not hasattr(tracker, "member_vars"):
172            # The placeholder value present before model initialization.
173            return
174
175        # Read before add_validation_score gets a chance to switch it.
176        self._mode_during_epoch = tracker.member_vars["mode"]
177
178        if not GPA.pc.get_perforated_backpropagation():
179            return
180        if self._mode_during_epoch != "p":
181            return
182
183        snapshot: dict[str, dict[str, float]] = {}
184        for neuron_module in tracker.neuron_module_vector:
185            summary = _compute_correlation_and_error_summary_for_one_layer(
186                neuron_module
187            )
188            if summary is not None:
189                snapshot[neuron_module.name] = summary
190        if not snapshot:
191            # No layer has allocated its buffers yet; keep the previous snapshot.
192            return
193        self._latest_snapshot = snapshot
194        self._snapshot_is_fresh = True
195
196    def record_score_and_detect_dendrite_addition_after_add_validation_score(
197        self, validation_score: float
198    ) -> None:
199        """Detect a dendrite addition and close out the previous one.
200
201        Args:
202            validation_score: The same value passed to add_validation_score this
203                epoch.
204        """
205        tracker = GPA.pai_tracker
206        if not hasattr(tracker, "member_vars"):
207            return
208
209        self._collect_score_if_neuron_phase(validation_score)
210        self._mark_pending_records_retained_if_newly_integrated(tracker)
211
212        current_dendrite_count: int = tracker.member_vars["num_dendrites_added"]
213        if current_dendrite_count <= self._previous_dendrite_count:
214            return
215
216        # A dendrite was added this epoch. The snapshot taken moments ago serves
217        # two purposes: it is the after-retraining measurement for the previous
218        # dendrite, and the at-add measurement for this one. The close and the
219        # open below both read self._neuron_phase_scores, so the per-phase state
220        # is reset only afterward.
221        self._complete_and_store_records_for_most_recent_dendrite_addition(
222            another_dendrite_phase_followed=True
223        )
224        self._open_pending_records_for_new_dendrite_addition(tracker)
225
226        self._neuron_phase_scores = []
227        self._snapshot_is_fresh = False
228        self._previous_dendrite_count = current_dendrite_count
229
230    def _collect_score_if_neuron_phase(self, validation_score: float) -> None:
231        """Append this epoch's score to the neuron-phase list, if applicable.
232
233        The score is collected only when the epoch that just finished was a
234        neuron phase; a dendrite-phase score is dropped. The mode is read from
235        self._mode_during_epoch, which was captured before add_validation_score
236        ran, because reading tracker.member_vars["mode"] now would return the
237        post-switch value and file a dendrite-phase score under the following
238        neuron phase at every boundary.
239
240        Args:
241            validation_score: The same value passed to add_validation_score this
242                epoch.
243        """
244        if self._mode_during_epoch == "n":
245            self._neuron_phase_scores.append(validation_score)
246
247    def _mark_pending_records_retained_if_newly_integrated(
248        self, tracker: Any
249    ) -> None:
250        """Mark the open records retained on the epoch a generation is kept.
251
252        num_dendrites_integrated is a monotonically increasing library counter
253        of how many dendrite generations have been kept. This method compares it
254        against the last value the recorder observed, held in
255        self._previous_integrated_count. A rise means the generation currently
256        held in self._pending_records was kept, so every pending record is marked
257        retained. The stored value is then advanced to the observed count, which
258        confines the marking to the single epoch on which the count increased:
259        without it the comparison would remain true on every later epoch and
260        re-mark the same records. That advance is the second half of the
261        detection, not separate housekeeping.
262
263        The library makes the decision late: it sets should_increment_integrated
264        at the neuron-to-dendrite switch that begins the next generation, so the
265        signal always arrives while the previous generation's records are still
266        open.
267
268        Args:
269            tracker: The initialized GPA.pai_tracker.
270        """
271        integrated_count: int = tracker.member_vars.get("num_dendrites_integrated", 0)
272        if integrated_count > self._previous_integrated_count:
273            for record in self._pending_records:
274                record.retained = True
275            self._previous_integrated_count = integrated_count
276
277    def _open_pending_records_for_new_dendrite_addition(self, tracker: Any) -> None:
278        """Create the pending records for the dendrite addition just detected.
279
280        One record is opened per layer present in the latest snapshot. Each is
281        tagged with self._previous_dendrite_count as its add_event_index, which
282        is the index of the addition being opened, and seeded with that layer's
283        at-add correlation and error summaries and the best validation score of
284        the neuron phase that just ended. The after-retraining and retention
285        fields are left unset for a later call to complete.
286
287        The caller resets the per-phase state and advances
288        self._previous_dendrite_count after this method returns, because both
289        this method and the preceding close read self._neuron_phase_scores.
290
291        Args:
292            tracker: The initialized GPA.pai_tracker.
293        """
294        add_event_index: int = self._previous_dendrite_count
295        epoch_added: int = tracker.member_vars["num_epochs_run"]
296        for layer_name, summary in self._latest_snapshot.items():
297            self._pending_records.append(
298                DendriteStatisticsRecord(
299                    add_event_index=add_event_index,
300                    layer_name=layer_name,
301                    epoch_added=epoch_added,
302                    best_absolute_pearson_correlation=summary[
303                        "best_absolute_pearson_correlation"
304                    ],
305                    mean_absolute_pearson_correlation=summary[
306                        "mean_absolute_pearson_correlation"
307                    ],
308                    best_absolute_covariance=summary["best_absolute_covariance"],
309                    mean_absolute_covariance=summary["mean_absolute_covariance"],
310                    mean_absolute_neuron_error_at_add=summary[
311                        "mean_absolute_neuron_error"
312                    ],
313                    validation_score_before=(
314                        self._select_best_validation_score_of_most_recent_neuron_phase()
315                    ),
316                )
317            )
318
319    def _select_best_validation_score_of_most_recent_neuron_phase(
320        self,
321    ) -> float | None:
322        """Return the best score from the most recent neuron phase."""
323        if not self._neuron_phase_scores:
324            return None
325        if GPA.pai_tracker.member_vars["maximizing_score"]:
326            return max(self._neuron_phase_scores)
327        return min(self._neuron_phase_scores)
328
329    def _complete_and_store_records_for_most_recent_dendrite_addition(
330        self, another_dendrite_phase_followed: bool
331    ) -> None:
332        """Fill in the after-retraining fields of the previous set of records.
333
334        Args:
335            another_dendrite_phase_followed: True only when a later dendrite
336                phase has produced a fresh neuron-error measurement. When False,
337                the error fields are left as None rather than being filled from
338                the same snapshot that supplied the at-add value, which would
339                fabricate a reduction of exactly zero. This flag also decides
340                whether an undecided generation is marked as discarded, because
341                a following dendrite phase is what makes that fate known.
342        """
343        if not self._pending_records:
344            return
345        if another_dendrite_phase_followed:
346            # Another generation is starting and this one was never marked
347            # integrated, so it was tried and discarded.
348            for record in self._pending_records:
349                if record.retained is None:
350                    record.retained = False
351        score_after: float | None = (
352            self._select_best_validation_score_of_most_recent_neuron_phase()
353        )
354        maximizing: bool = GPA.pai_tracker.member_vars["maximizing_score"]
355
356        for record in self._pending_records:
357            summary = self._latest_snapshot.get(record.layer_name)
358            if (
359                another_dendrite_phase_followed
360                and self._snapshot_is_fresh
361                and summary is not None
362            ):
363                error_after: float = summary["mean_absolute_neuron_error"]
364                record.mean_absolute_neuron_error_after_retraining = error_after
365                record.neuron_error_reduction = (
366                    record.mean_absolute_neuron_error_at_add - error_after
367                )
368            record.validation_score_after = score_after
369            if record.validation_score_before is not None and score_after is not None:
370                difference: float = score_after - record.validation_score_before
371                record.validation_score_improvement = (
372                    difference if maximizing else -difference
373                )
374            self._records.append(record)
375        self._pending_records = []
376
377    def complete_final_records_and_write_csv_file(
378        self, csv_file_name: str = "dendrite_statistics.csv"
379    ) -> Path:
380        """Close any open records and write the CSV file.
381
382        The final dendrite's error fields are left empty, because measuring the
383        error after retraining requires a subsequent dendrite phase that never
384        ran. Its validation-score fields are still filled in.
385
386        Args:
387            csv_file_name: Name of the CSV file to write.
388
389        Returns:
390            The path of the file written.
391        """
392        self._complete_and_store_records_for_most_recent_dendrite_addition(
393            another_dendrite_phase_followed=False
394        )
395        output_path: Path = self._output_directory / csv_file_name
396        field_names: list[str] = list(DendriteStatisticsRecord.__annotations__)
397        with output_path.open("w", newline="", encoding="utf-8") as handle:
398            writer = csv.DictWriter(handle, fieldnames=field_names)
399            writer.writeheader()
400            for record in self._records:
401                writer.writerow(asdict(record))
402        return output_path
@dataclass
class DendriteStatisticsRecord:
18@dataclass
19class DendriteStatisticsRecord:
20    """
21    Statistics for one dendrite added to one layer.
22
23    Attributes:
24        add_event_index: Which dendrite-addition event this record belongs to,
25            counting from zero.
26        layer_name: The name of the parent neuron module.
27        epoch_added: The value of num_epochs_run when the dendrite was added.
28        best_absolute_pearson_correlation: Largest absolute Pearson correlation
29            across all output nodes and candidates, bounded in [0, 1].
30        mean_absolute_pearson_correlation: Mean of the same quantity over nodes.
31        best_absolute_covariance: Largest absolute covariance across all output
32            nodes and candidates. Unbounded. This is the scoring quantity.
33        mean_absolute_covariance: Mean of the same quantity over nodes.
34        mean_absolute_neuron_error_at_add: Mean absolute per-node parent error
35            measured during the dendrite phase that produced this dendrite.
36        mean_absolute_neuron_error_after_retraining: The same measurement taken
37            during the following dendrite phase, after retraining. Stays None if
38            training ended before another dendrite phase ran.
39        neuron_error_reduction: The decrease in mean absolute per-node error
40            between those two measurements. Positive means the error fell. Stays
41            None whenever the after-retraining measurement is None.
42        validation_score_before: Best neuron-phase validation score before this
43            dendrite was added.
44        validation_score_after: Best neuron-phase validation score after this
45            dendrite was added and the network was retrained.
46        validation_score_improvement: The improvement between the two, signed so
47            that positive always means better, whichever direction is better.
48        retained: True if this dendrite generation was kept, False if it was
49            tried and discarded, None if training ended before the decision was
50            made. Rows with retained False describe a generation that was rolled
51            back, so their error and score changes do not measure a dendrite's
52            effect and should be filtered out before analysis.
53    """
54
55    add_event_index: int
56    layer_name: str
57    epoch_added: int
58    best_absolute_pearson_correlation: float
59    mean_absolute_pearson_correlation: float
60    best_absolute_covariance: float
61    mean_absolute_covariance: float
62    mean_absolute_neuron_error_at_add: float
63    retained: bool | None = None
64    mean_absolute_neuron_error_after_retraining: float | None = None
65    neuron_error_reduction: float | None = None
66    validation_score_before: float | None = None
67    validation_score_after: float | None = None
68    validation_score_improvement: float | None = None

Statistics for one dendrite added to one layer.

Attributes: add_event_index: Which dendrite-addition event this record belongs to, counting from zero. layer_name: The name of the parent neuron module. epoch_added: The value of num_epochs_run when the dendrite was added. best_absolute_pearson_correlation: Largest absolute Pearson correlation across all output nodes and candidates, bounded in [0, 1]. mean_absolute_pearson_correlation: Mean of the same quantity over nodes. best_absolute_covariance: Largest absolute covariance across all output nodes and candidates. Unbounded. This is the scoring quantity. mean_absolute_covariance: Mean of the same quantity over nodes. mean_absolute_neuron_error_at_add: Mean absolute per-node parent error measured during the dendrite phase that produced this dendrite. mean_absolute_neuron_error_after_retraining: The same measurement taken during the following dendrite phase, after retraining. Stays None if training ended before another dendrite phase ran. neuron_error_reduction: The decrease in mean absolute per-node error between those two measurements. Positive means the error fell. Stays None whenever the after-retraining measurement is None. validation_score_before: Best neuron-phase validation score before this dendrite was added. validation_score_after: Best neuron-phase validation score after this dendrite was added and the network was retrained. validation_score_improvement: The improvement between the two, signed so that positive always means better, whichever direction is better. retained: True if this dendrite generation was kept, False if it was tried and discarded, None if training ended before the decision was made. Rows with retained False describe a generation that was rolled back, so their error and score changes do not measure a dendrite's effect and should be filtered out before analysis.

DendriteStatisticsRecord( add_event_index: int, layer_name: str, epoch_added: int, best_absolute_pearson_correlation: float, mean_absolute_pearson_correlation: float, best_absolute_covariance: float, mean_absolute_covariance: float, mean_absolute_neuron_error_at_add: float, retained: bool | None = None, mean_absolute_neuron_error_after_retraining: float | None = None, neuron_error_reduction: float | None = None, validation_score_before: float | None = None, validation_score_after: float | None = None, validation_score_improvement: float | None = None)
add_event_index: int
layer_name: str
epoch_added: int
best_absolute_pearson_correlation: float
mean_absolute_pearson_correlation: float
best_absolute_covariance: float
mean_absolute_covariance: float
mean_absolute_neuron_error_at_add: float
retained: bool | None = None
mean_absolute_neuron_error_after_retraining: float | None = None
neuron_error_reduction: float | None = None
validation_score_before: float | None = None
validation_score_after: float | None = None
validation_score_improvement: float | None = None
class DendriteStatisticsRecorder:
132class DendriteStatisticsRecorder:
133    """
134    Collect per-dendrite correlation and error-reduction statistics.
135
136    The recorder must be driven from the training loop because the values it
137    reads are overwritten by the mode switch inside add_validation_score. Call
138    capture_mode_and_layer_statistics_before_add_validation_score immediately
139    before that call, and
140    record_score_and_detect_dendrite_addition_after_add_validation_score
141    immediately after it, every epoch.
142    """
143
144    def __init__(self, output_directory: Path) -> None:
145        """Initialize the recorder.
146
147        Args:
148            output_directory: Directory the CSV file is written into. Created if
149                it does not exist.
150        """
151        self._output_directory: Path = output_directory
152        self._output_directory.mkdir(parents=True, exist_ok=True)
153        self._records: list[DendriteStatisticsRecord] = []
154        self._latest_snapshot: dict[str, dict[str, float]] = {}
155        self._previous_dendrite_count: int = 0
156        self._pending_records: list[DendriteStatisticsRecord] = []
157        self._neuron_phase_scores: list[float] = []
158        self._mode_during_epoch: str | None = None
159        self._snapshot_is_fresh: bool = False
160        self._previous_integrated_count: int = 0
161
162    def capture_mode_and_layer_statistics_before_add_validation_score(self) -> None:
163        """Snapshot every layer's correlation buffers before the mode can switch.
164
165        Records the current mode unconditionally, because
166        record_score_and_detect_dendrite_addition_after_add_validation_score
167        needs to know which phase this epoch belonged to and cannot determine that
168        afterward. Takes the buffer snapshot only during a dendrite-training
169        phase, when the buffers hold meaningful values.
170        """
171        tracker = GPA.pai_tracker
172        if not hasattr(tracker, "member_vars"):
173            # The placeholder value present before model initialization.
174            return
175
176        # Read before add_validation_score gets a chance to switch it.
177        self._mode_during_epoch = tracker.member_vars["mode"]
178
179        if not GPA.pc.get_perforated_backpropagation():
180            return
181        if self._mode_during_epoch != "p":
182            return
183
184        snapshot: dict[str, dict[str, float]] = {}
185        for neuron_module in tracker.neuron_module_vector:
186            summary = _compute_correlation_and_error_summary_for_one_layer(
187                neuron_module
188            )
189            if summary is not None:
190                snapshot[neuron_module.name] = summary
191        if not snapshot:
192            # No layer has allocated its buffers yet; keep the previous snapshot.
193            return
194        self._latest_snapshot = snapshot
195        self._snapshot_is_fresh = True
196
197    def record_score_and_detect_dendrite_addition_after_add_validation_score(
198        self, validation_score: float
199    ) -> None:
200        """Detect a dendrite addition and close out the previous one.
201
202        Args:
203            validation_score: The same value passed to add_validation_score this
204                epoch.
205        """
206        tracker = GPA.pai_tracker
207        if not hasattr(tracker, "member_vars"):
208            return
209
210        self._collect_score_if_neuron_phase(validation_score)
211        self._mark_pending_records_retained_if_newly_integrated(tracker)
212
213        current_dendrite_count: int = tracker.member_vars["num_dendrites_added"]
214        if current_dendrite_count <= self._previous_dendrite_count:
215            return
216
217        # A dendrite was added this epoch. The snapshot taken moments ago serves
218        # two purposes: it is the after-retraining measurement for the previous
219        # dendrite, and the at-add measurement for this one. The close and the
220        # open below both read self._neuron_phase_scores, so the per-phase state
221        # is reset only afterward.
222        self._complete_and_store_records_for_most_recent_dendrite_addition(
223            another_dendrite_phase_followed=True
224        )
225        self._open_pending_records_for_new_dendrite_addition(tracker)
226
227        self._neuron_phase_scores = []
228        self._snapshot_is_fresh = False
229        self._previous_dendrite_count = current_dendrite_count
230
231    def _collect_score_if_neuron_phase(self, validation_score: float) -> None:
232        """Append this epoch's score to the neuron-phase list, if applicable.
233
234        The score is collected only when the epoch that just finished was a
235        neuron phase; a dendrite-phase score is dropped. The mode is read from
236        self._mode_during_epoch, which was captured before add_validation_score
237        ran, because reading tracker.member_vars["mode"] now would return the
238        post-switch value and file a dendrite-phase score under the following
239        neuron phase at every boundary.
240
241        Args:
242            validation_score: The same value passed to add_validation_score this
243                epoch.
244        """
245        if self._mode_during_epoch == "n":
246            self._neuron_phase_scores.append(validation_score)
247
248    def _mark_pending_records_retained_if_newly_integrated(
249        self, tracker: Any
250    ) -> None:
251        """Mark the open records retained on the epoch a generation is kept.
252
253        num_dendrites_integrated is a monotonically increasing library counter
254        of how many dendrite generations have been kept. This method compares it
255        against the last value the recorder observed, held in
256        self._previous_integrated_count. A rise means the generation currently
257        held in self._pending_records was kept, so every pending record is marked
258        retained. The stored value is then advanced to the observed count, which
259        confines the marking to the single epoch on which the count increased:
260        without it the comparison would remain true on every later epoch and
261        re-mark the same records. That advance is the second half of the
262        detection, not separate housekeeping.
263
264        The library makes the decision late: it sets should_increment_integrated
265        at the neuron-to-dendrite switch that begins the next generation, so the
266        signal always arrives while the previous generation's records are still
267        open.
268
269        Args:
270            tracker: The initialized GPA.pai_tracker.
271        """
272        integrated_count: int = tracker.member_vars.get("num_dendrites_integrated", 0)
273        if integrated_count > self._previous_integrated_count:
274            for record in self._pending_records:
275                record.retained = True
276            self._previous_integrated_count = integrated_count
277
278    def _open_pending_records_for_new_dendrite_addition(self, tracker: Any) -> None:
279        """Create the pending records for the dendrite addition just detected.
280
281        One record is opened per layer present in the latest snapshot. Each is
282        tagged with self._previous_dendrite_count as its add_event_index, which
283        is the index of the addition being opened, and seeded with that layer's
284        at-add correlation and error summaries and the best validation score of
285        the neuron phase that just ended. The after-retraining and retention
286        fields are left unset for a later call to complete.
287
288        The caller resets the per-phase state and advances
289        self._previous_dendrite_count after this method returns, because both
290        this method and the preceding close read self._neuron_phase_scores.
291
292        Args:
293            tracker: The initialized GPA.pai_tracker.
294        """
295        add_event_index: int = self._previous_dendrite_count
296        epoch_added: int = tracker.member_vars["num_epochs_run"]
297        for layer_name, summary in self._latest_snapshot.items():
298            self._pending_records.append(
299                DendriteStatisticsRecord(
300                    add_event_index=add_event_index,
301                    layer_name=layer_name,
302                    epoch_added=epoch_added,
303                    best_absolute_pearson_correlation=summary[
304                        "best_absolute_pearson_correlation"
305                    ],
306                    mean_absolute_pearson_correlation=summary[
307                        "mean_absolute_pearson_correlation"
308                    ],
309                    best_absolute_covariance=summary["best_absolute_covariance"],
310                    mean_absolute_covariance=summary["mean_absolute_covariance"],
311                    mean_absolute_neuron_error_at_add=summary[
312                        "mean_absolute_neuron_error"
313                    ],
314                    validation_score_before=(
315                        self._select_best_validation_score_of_most_recent_neuron_phase()
316                    ),
317                )
318            )
319
320    def _select_best_validation_score_of_most_recent_neuron_phase(
321        self,
322    ) -> float | None:
323        """Return the best score from the most recent neuron phase."""
324        if not self._neuron_phase_scores:
325            return None
326        if GPA.pai_tracker.member_vars["maximizing_score"]:
327            return max(self._neuron_phase_scores)
328        return min(self._neuron_phase_scores)
329
330    def _complete_and_store_records_for_most_recent_dendrite_addition(
331        self, another_dendrite_phase_followed: bool
332    ) -> None:
333        """Fill in the after-retraining fields of the previous set of records.
334
335        Args:
336            another_dendrite_phase_followed: True only when a later dendrite
337                phase has produced a fresh neuron-error measurement. When False,
338                the error fields are left as None rather than being filled from
339                the same snapshot that supplied the at-add value, which would
340                fabricate a reduction of exactly zero. This flag also decides
341                whether an undecided generation is marked as discarded, because
342                a following dendrite phase is what makes that fate known.
343        """
344        if not self._pending_records:
345            return
346        if another_dendrite_phase_followed:
347            # Another generation is starting and this one was never marked
348            # integrated, so it was tried and discarded.
349            for record in self._pending_records:
350                if record.retained is None:
351                    record.retained = False
352        score_after: float | None = (
353            self._select_best_validation_score_of_most_recent_neuron_phase()
354        )
355        maximizing: bool = GPA.pai_tracker.member_vars["maximizing_score"]
356
357        for record in self._pending_records:
358            summary = self._latest_snapshot.get(record.layer_name)
359            if (
360                another_dendrite_phase_followed
361                and self._snapshot_is_fresh
362                and summary is not None
363            ):
364                error_after: float = summary["mean_absolute_neuron_error"]
365                record.mean_absolute_neuron_error_after_retraining = error_after
366                record.neuron_error_reduction = (
367                    record.mean_absolute_neuron_error_at_add - error_after
368                )
369            record.validation_score_after = score_after
370            if record.validation_score_before is not None and score_after is not None:
371                difference: float = score_after - record.validation_score_before
372                record.validation_score_improvement = (
373                    difference if maximizing else -difference
374                )
375            self._records.append(record)
376        self._pending_records = []
377
378    def complete_final_records_and_write_csv_file(
379        self, csv_file_name: str = "dendrite_statistics.csv"
380    ) -> Path:
381        """Close any open records and write the CSV file.
382
383        The final dendrite's error fields are left empty, because measuring the
384        error after retraining requires a subsequent dendrite phase that never
385        ran. Its validation-score fields are still filled in.
386
387        Args:
388            csv_file_name: Name of the CSV file to write.
389
390        Returns:
391            The path of the file written.
392        """
393        self._complete_and_store_records_for_most_recent_dendrite_addition(
394            another_dendrite_phase_followed=False
395        )
396        output_path: Path = self._output_directory / csv_file_name
397        field_names: list[str] = list(DendriteStatisticsRecord.__annotations__)
398        with output_path.open("w", newline="", encoding="utf-8") as handle:
399            writer = csv.DictWriter(handle, fieldnames=field_names)
400            writer.writeheader()
401            for record in self._records:
402                writer.writerow(asdict(record))
403        return output_path

Collect per-dendrite correlation and error-reduction statistics.

The recorder must be driven from the training loop because the values it reads are overwritten by the mode switch inside add_validation_score. Call capture_mode_and_layer_statistics_before_add_validation_score immediately before that call, and record_score_and_detect_dendrite_addition_after_add_validation_score immediately after it, every epoch.

DendriteStatisticsRecorder(output_directory: pathlib.Path)
144    def __init__(self, output_directory: Path) -> None:
145        """Initialize the recorder.
146
147        Args:
148            output_directory: Directory the CSV file is written into. Created if
149                it does not exist.
150        """
151        self._output_directory: Path = output_directory
152        self._output_directory.mkdir(parents=True, exist_ok=True)
153        self._records: list[DendriteStatisticsRecord] = []
154        self._latest_snapshot: dict[str, dict[str, float]] = {}
155        self._previous_dendrite_count: int = 0
156        self._pending_records: list[DendriteStatisticsRecord] = []
157        self._neuron_phase_scores: list[float] = []
158        self._mode_during_epoch: str | None = None
159        self._snapshot_is_fresh: bool = False
160        self._previous_integrated_count: int = 0

Initialize the recorder.

Args: output_directory: Directory the CSV file is written into. Created if it does not exist.

def capture_mode_and_layer_statistics_before_add_validation_score(self) -> None:
162    def capture_mode_and_layer_statistics_before_add_validation_score(self) -> None:
163        """Snapshot every layer's correlation buffers before the mode can switch.
164
165        Records the current mode unconditionally, because
166        record_score_and_detect_dendrite_addition_after_add_validation_score
167        needs to know which phase this epoch belonged to and cannot determine that
168        afterward. Takes the buffer snapshot only during a dendrite-training
169        phase, when the buffers hold meaningful values.
170        """
171        tracker = GPA.pai_tracker
172        if not hasattr(tracker, "member_vars"):
173            # The placeholder value present before model initialization.
174            return
175
176        # Read before add_validation_score gets a chance to switch it.
177        self._mode_during_epoch = tracker.member_vars["mode"]
178
179        if not GPA.pc.get_perforated_backpropagation():
180            return
181        if self._mode_during_epoch != "p":
182            return
183
184        snapshot: dict[str, dict[str, float]] = {}
185        for neuron_module in tracker.neuron_module_vector:
186            summary = _compute_correlation_and_error_summary_for_one_layer(
187                neuron_module
188            )
189            if summary is not None:
190                snapshot[neuron_module.name] = summary
191        if not snapshot:
192            # No layer has allocated its buffers yet; keep the previous snapshot.
193            return
194        self._latest_snapshot = snapshot
195        self._snapshot_is_fresh = True

Snapshot every layer's correlation buffers before the mode can switch.

Records the current mode unconditionally, because record_score_and_detect_dendrite_addition_after_add_validation_score needs to know which phase this epoch belonged to and cannot determine that afterward. Takes the buffer snapshot only during a dendrite-training phase, when the buffers hold meaningful values.

def record_score_and_detect_dendrite_addition_after_add_validation_score(self, validation_score: float) -> None:
197    def record_score_and_detect_dendrite_addition_after_add_validation_score(
198        self, validation_score: float
199    ) -> None:
200        """Detect a dendrite addition and close out the previous one.
201
202        Args:
203            validation_score: The same value passed to add_validation_score this
204                epoch.
205        """
206        tracker = GPA.pai_tracker
207        if not hasattr(tracker, "member_vars"):
208            return
209
210        self._collect_score_if_neuron_phase(validation_score)
211        self._mark_pending_records_retained_if_newly_integrated(tracker)
212
213        current_dendrite_count: int = tracker.member_vars["num_dendrites_added"]
214        if current_dendrite_count <= self._previous_dendrite_count:
215            return
216
217        # A dendrite was added this epoch. The snapshot taken moments ago serves
218        # two purposes: it is the after-retraining measurement for the previous
219        # dendrite, and the at-add measurement for this one. The close and the
220        # open below both read self._neuron_phase_scores, so the per-phase state
221        # is reset only afterward.
222        self._complete_and_store_records_for_most_recent_dendrite_addition(
223            another_dendrite_phase_followed=True
224        )
225        self._open_pending_records_for_new_dendrite_addition(tracker)
226
227        self._neuron_phase_scores = []
228        self._snapshot_is_fresh = False
229        self._previous_dendrite_count = current_dendrite_count

Detect a dendrite addition and close out the previous one.

Args: validation_score: The same value passed to add_validation_score this epoch.

def complete_final_records_and_write_csv_file(self, csv_file_name: str = 'dendrite_statistics.csv') -> pathlib.Path:
378    def complete_final_records_and_write_csv_file(
379        self, csv_file_name: str = "dendrite_statistics.csv"
380    ) -> Path:
381        """Close any open records and write the CSV file.
382
383        The final dendrite's error fields are left empty, because measuring the
384        error after retraining requires a subsequent dendrite phase that never
385        ran. Its validation-score fields are still filled in.
386
387        Args:
388            csv_file_name: Name of the CSV file to write.
389
390        Returns:
391            The path of the file written.
392        """
393        self._complete_and_store_records_for_most_recent_dendrite_addition(
394            another_dendrite_phase_followed=False
395        )
396        output_path: Path = self._output_directory / csv_file_name
397        field_names: list[str] = list(DendriteStatisticsRecord.__annotations__)
398        with output_path.open("w", newline="", encoding="utf-8") as handle:
399            writer = csv.DictWriter(handle, fieldnames=field_names)
400            writer.writeheader()
401            for record in self._records:
402                writer.writerow(asdict(record))
403        return output_path

Close any open records and write the CSV file.

The final dendrite's error fields are left empty, because measuring the error after retraining requires a subsequent dendrite phase that never ran. Its validation-score fields are still filled in.

Args: csv_file_name: Name of the CSV file to write.

Returns: The path of the file written.