perforatedai.dendrite_loss_events

  1from __future__ import annotations
  2
  3from typing import Iterator
  4
  5try:
  6    from perforatedbp.cleanup_helper_functions import is_in_dendrite_training_mode
  7except ModuleNotFoundError as e:
  8    # Only pass if perforatedbp package itself is missing
  9    if e.name == "perforatedbp":
 10        pass
 11    else:
 12        # perforatedbp exists but is missing a dependency
 13        raise
 14
 15
 16from typing import TYPE_CHECKING
 17if TYPE_CHECKING:
 18    from torch import nn
 19    from perforatedai import modules_perforatedai as MPA
 20    from perforatedai import tracker_perforatedai as TPA
 21    from perforatedai import globals_perforatedai as GPA
 22    from perforatedbp.dendrite_losses.dendrite_loss_pbp import DendriteLoss
 23
 24def register_epoch_hooks() -> None:
 25    # Imported at call time (not module top level) to avoid a circular import
 26    from perforatedai import globals_perforatedai as GPA
 27    start = GPA.pc.get_epoch_start_callbacks()
 28    stop = GPA.pc.get_epoch_stop_callbacks()
 29    start.clear();
 30    stop.clear()  # so repeats do not accumulate
 31    start.append(notify_epoch_start)
 32    stop.append(notify_epoch_stop)
 33
 34def notify_epoch_start(tracker: TPA.PAINeuronModuleTracker) -> None:
 35    """
 36    TODO this should be a method of some class
 37    Call ``on_epoch_start(tracker)`` on each dendrite module's ``DendriteLoss`` object.
 38
 39    See :func:`_dendrite_losses_in_training_mode` for exactly which objects are notified and
 40    the dendrite-mode gate.  This signature (tracker only) matches what the ``start_epoch``
 41    boundary loop calls, so it can be registered directly in ``GPA.pc``'s
 42    ``epoch_start_callbacks``.
 43    """
 44    for dendrite_loss in _dendrite_losses_in_training_mode(tracker):
 45        dendrite_loss.on_epoch_start(tracker)
 46    for dendrite_loss, value_tracker in _dendrite_losses_and_trackers_in_training_mode(tracker):
 47        dendrite_loss.on_epoch_start_dendrite(value_tracker)
 48
 49
 50def notify_epoch_stop(tracker: TPA.PAINeuronModuleTracker) -> None:
 51    """     TODO this should be a method of some class
 52    Call ``on_epoch_stop(tracker)`` on each dendrite module's ``DendriteLoss`` object.
 53    See :func:`_dendrite_losses_in_training_mode` for exactly which objects are notified and
 54    the dendrite-mode gate.  This signature (tracker only) matches what the ``stop_epoch``
 55    boundary loop calls, so it can be registered directly in ``GPA.pc``'s
 56    ``epoch_stop_callbacks``.
 57    """
 58    for dendrite_loss in _dendrite_losses_in_training_mode(tracker):
 59        dendrite_loss.on_epoch_stop(tracker)
 60    for dendrite_loss, value_tracker in _dendrite_losses_and_trackers_in_training_mode(tracker):
 61        dendrite_loss.on_epoch_stop_dendrite(value_tracker)
 62
 63
 64
 65def _dendrite_losses_in_training_mode(
 66        neuron_module_tracker: TPA.PAINeuronModuleTracker,
 67) -> 'Iterator[DendriteLoss]':
 68    """
 69    Yield each dendrite module's ``DendriteLoss`` object, but only in dendrite mode.
 70
 71    The library constructs one ``DendriteLoss`` object per ``PAIDendriteModule`` (and only
 72    where perforated backpropagation is enabled), reachable as
 73    ``neuron_module.dendrite_module.dendrite_loss`` for each entry in
 74    ``tracker.neuron_module_vector``.  Yields nothing unless the tracker is in dendrite
 75    training mode, so the setup and load-path boundary calls (which occur in neuron mode) are
 76    naturally ignored; a dendrite module lacking a ``dendrite_loss`` attribute is skipped.
 77
 78    Args:
 79        neuron_module_tracker: The ``PAINeuronModuleTracker`` whose ``neuron_module_vector`` owns the
 80            per-layer ``DendriteLoss`` objects.
 81
 82    Yields:
 83        Each dendrite module's ``DendriteLoss`` object, in ``neuron_module_vector`` order.
 84    """
 85    if not is_in_dendrite_training_mode(neuron_module_tracker):
 86        return
 87    for neuron_module in neuron_module_tracker.neuron_module_vector:
 88        dendrite_loss: 'DendriteLoss | None' = getattr(neuron_module.dendrite_module, "dendrite_loss", None)
 89        if dendrite_loss is not None:
 90            yield dendrite_loss
 91
 92
 93def _dendrite_losses_and_trackers_in_training_mode(
 94        tracker: TPA.PAINeuronModuleTracker,
 95) -> 'Iterator[tuple[DendriteLoss, MPA.DendriteValueTracker]]':
 96    """Yield ``(dendrite_loss, dendrite_value_tracker)`` per module, but only in dendrite mode.
 97
 98    Sibling of :func:`_dendrite_losses_in_training_mode` that additionally reaches the per-module
 99    value tracker (``dendrite_module.dendrite_values[0]``, per decision D2=A) so the per-dendrite
100    hooks receive it directly.  It reproduces the same dendrite-mode gate and the same
101    ``dendrite_loss`` skip, and additionally guards ``dendrite_values``: a module reached with a
102    ``dendrite_loss`` set but ``dendrite_values`` absent or empty is skipped before the ``[0]``
103    index, so the fan-out never raises on a partially constructed module.
104
105    Args:
106        tracker: The ``PAINeuronModuleTracker`` whose ``neuron_module_vector`` owns the per-layer
107            ``DendriteLoss`` objects and their value trackers.
108
109    Yields:
110        Each module's ``(dendrite_loss, dendrite_values[0])`` pair, in ``neuron_module_vector`` order.
111    """
112    if not is_in_dendrite_training_mode(tracker):
113        return
114    for neuron_module in tracker.neuron_module_vector:
115        dendrite_module: 'MPA.PAIDendriteModule' = neuron_module.dendrite_module
116        dendrite_loss: 'DendriteLoss | None' = getattr(dendrite_module, "dendrite_loss", None)
117        if dendrite_loss is None:
118            continue
119        dendrite_values: 'nn.ModuleList | None' = getattr(dendrite_module, "dendrite_values", None)
120        if not dendrite_values:  # attribute missing, or the ModuleList is empty
121            continue
122        yield dendrite_loss, dendrite_values[0]
def register_epoch_hooks() -> None:
25def register_epoch_hooks() -> None:
26    # Imported at call time (not module top level) to avoid a circular import
27    from perforatedai import globals_perforatedai as GPA
28    start = GPA.pc.get_epoch_start_callbacks()
29    stop = GPA.pc.get_epoch_stop_callbacks()
30    start.clear();
31    stop.clear()  # so repeats do not accumulate
32    start.append(notify_epoch_start)
33    stop.append(notify_epoch_stop)
def notify_epoch_start( tracker: perforatedai.tracker_perforatedai.PAINeuronModuleTracker) -> None:
35def notify_epoch_start(tracker: TPA.PAINeuronModuleTracker) -> None:
36    """
37    TODO this should be a method of some class
38    Call ``on_epoch_start(tracker)`` on each dendrite module's ``DendriteLoss`` object.
39
40    See :func:`_dendrite_losses_in_training_mode` for exactly which objects are notified and
41    the dendrite-mode gate.  This signature (tracker only) matches what the ``start_epoch``
42    boundary loop calls, so it can be registered directly in ``GPA.pc``'s
43    ``epoch_start_callbacks``.
44    """
45    for dendrite_loss in _dendrite_losses_in_training_mode(tracker):
46        dendrite_loss.on_epoch_start(tracker)
47    for dendrite_loss, value_tracker in _dendrite_losses_and_trackers_in_training_mode(tracker):
48        dendrite_loss.on_epoch_start_dendrite(value_tracker)

TODO this should be a method of some class Call on_epoch_start(tracker) on each dendrite module's DendriteLoss object.

See _dendrite_losses_in_training_mode() for exactly which objects are notified and the dendrite-mode gate. This signature (tracker only) matches what the start_epoch boundary loop calls, so it can be registered directly in GPA.pc's epoch_start_callbacks.

def notify_epoch_stop( tracker: perforatedai.tracker_perforatedai.PAINeuronModuleTracker) -> None:
51def notify_epoch_stop(tracker: TPA.PAINeuronModuleTracker) -> None:
52    """     TODO this should be a method of some class
53    Call ``on_epoch_stop(tracker)`` on each dendrite module's ``DendriteLoss`` object.
54    See :func:`_dendrite_losses_in_training_mode` for exactly which objects are notified and
55    the dendrite-mode gate.  This signature (tracker only) matches what the ``stop_epoch``
56    boundary loop calls, so it can be registered directly in ``GPA.pc``'s
57    ``epoch_stop_callbacks``.
58    """
59    for dendrite_loss in _dendrite_losses_in_training_mode(tracker):
60        dendrite_loss.on_epoch_stop(tracker)
61    for dendrite_loss, value_tracker in _dendrite_losses_and_trackers_in_training_mode(tracker):
62        dendrite_loss.on_epoch_stop_dendrite(value_tracker)

TODO this should be a method of some class Call on_epoch_stop(tracker) on each dendrite module's DendriteLoss object. See _dendrite_losses_in_training_mode() for exactly which objects are notified and the dendrite-mode gate. This signature (tracker only) matches what the stop_epoch boundary loop calls, so it can be registered directly in GPA.pc's epoch_stop_callbacks.