perforatedai.globals_perforatedai

PAI configuration file.

This module provides configuration classes and utilities for Perforated AI (PAI), including device settings, dendrite management, module conversion options, and training parameters.

   1# Copyright (c) 2025 Perforated AI
   2"""PAI configuration file.
   3
   4This module provides configuration classes and utilities for Perforated AI (PAI),
   5including device settings, dendrite management, module conversion options,
   6and training parameters.
   7"""
   8
   9import math
  10import sys
  11
  12import torch
  13import torch.nn as nn
  14
  15# Re-exported so every module that already imports globals_perforatedai as GPA can
  16# reference GPA.NODE_AXIS / GPA.REDUCE_AXIS / GPA.NOT_REDUCE_OR_NODE_AXIS without a new
  17# import. dendrite_axis_codes is a leaf module (imports nothing), so this cannot cycle.
  18from perforatedai.dendrite_axis_codes import (
  19    NODE_AXIS,
  20    NOT_REDUCE_OR_NODE_AXIS,
  21    REDUCE_AXIS,
  22)
  23
  24
  25def _validate_module_id(module_id):
  26    """Validate that a module ID string uses dot notation.
  27
  28    Module IDs must start with '.' and must not contain '[' or ']'.
  29    For example, 'model.layers[1].module' should be written as '.layers.1.module'.
  30    """
  31    if not isinstance(module_id, str) or not module_id.startswith("."):
  32        raise ValueError(
  33            f"Module ID '{module_id}' must start with '.' - model.module should be '.module'"
  34        )
  35    if "[" in module_id or "]" in module_id:
  36        raise ValueError(
  37            f"Module ID '{module_id}' must not contain '[' or ']'. "
  38            "Use dot notation instead, e.g. '.layers.1.module'"
  39        )
  40
  41
  42# Unordered id/name lists that both Python calls and the config CLI edit. For
  43# these, a Python set_/append_ call is merged with the JSON rather than
  44# replacing it. Class lists feed the name lists via their short class names.
  45SELECTION_LIST_VARS = (
  46    "module_ids_to_perforate",
  47    "module_ids_to_track",
  48    "module_names_to_perforate",
  49    "module_names_to_track",
  50    "parameter_ids_to_track",
  51    "block_rules",
  52    "modules_to_fuse",
  53)
  54_CLASS_LIST_FEEDS = {
  55    "modules_to_perforate": "module_names_to_perforate",
  56    "modules_to_track": "module_names_to_track",
  57}
  58_SELECTION_CONFLICT_PAIRS = (
  59    ("module_ids_to_perforate", "module_ids_to_track"),
  60    ("module_names_to_perforate", "module_names_to_track"),
  61)
  62
  63
  64BLOCK_RULE_MODES = ("perforated", "tracked")
  65
  66
  67def _normalize_block_rules(value):
  68    """Return block rules as validated {block, path, mode[, structure]} dicts.
  69
  70    A later rule for the same block and path replaces an earlier one.
  71    The optional 'structure' key is a sorted list of relative submodule paths
  72    that identifies which instances the rule applies to; rules without it apply
  73    to all instances that have the path (backward-compatible behaviour).
  74    """
  75    rules = {}
  76    for rule in value:
  77        allowed = {"block", "path", "mode", "structure"}
  78        required = {"block", "path", "mode"}
  79        if not isinstance(rule, dict) or not required.issubset(set(rule)) or not set(rule).issubset(allowed):
  80            raise ValueError(
  81                "block_rules entries must be {'block', 'path', 'mode'} dicts "
  82                "(optionally with 'structure'), got %r" % (rule,)
  83            )
  84        block, path, mode = rule["block"], rule["path"], rule["mode"]
  85        if not isinstance(block, str) or block == "":
  86            raise ValueError("block rule needs a block class name, got %r" % (block,))
  87        if not isinstance(path, str) or not path.startswith(".") or len(path) < 2:
  88            raise ValueError(
  89                "block rule path must be a relative path like '.conv2', got %r"
  90                % (path,)
  91            )
  92        if "[" in path or "]" in path:
  93            raise ValueError(
  94                "Block rule path '%s' must not contain '[' or ']'. "
  95                "Use dot notation instead, e.g. '.layers.1.module'" % path
  96            )
  97        if mode not in BLOCK_RULE_MODES:
  98            raise ValueError(
  99                "block rule mode must be one of %s, got %r" % (BLOCK_RULE_MODES, mode)
 100            )
 101        normalised = {"block": block, "path": path, "mode": mode}
 102        if "structure" in rule:
 103            structure = rule["structure"]
 104            if not isinstance(structure, list) or not all(isinstance(s, str) for s in structure):
 105                raise ValueError(
 106                    "block rule 'structure' must be a list of strings, got %r" % (structure,)
 107                )
 108            normalised["structure"] = structure
 109        # Dedup key: include structure so different-structure instances can each
 110        # have their own rule for the same path within the same block class.
 111        dedup_key = (block, path, tuple(normalised.get("structure", [])))
 112        rules[dedup_key] = normalised
 113    return list(rules.values())
 114def _normalize_fuse_pairs(value):
 115    """Return fused pairs as a list of [head_id, norm_id] lists, validated."""
 116    pairs = []
 117    for pair in value:
 118        if not isinstance(pair, (list, tuple)) or len(pair) != 2:
 119            raise ValueError(
 120                "modules_to_fuse entries must be (head_id, norm_id) pairs, got %r"
 121                % (pair,)
 122            )
 123        for module_id in pair:
 124            _validate_module_id(module_id)
 125        pairs.append([pair[0], pair[1]])
 126    return pairs
 127
 128
 129def _record_python_supplied(obj, var_name, value, replace):
 130    """Remember items a user script supplied for a selection list.
 131
 132    Kept in memory only (never saved to JSON). Calls made by the config CLI
 133    itself are ignored so the CLI cannot lock its own edits.
 134    """
 135    if var_name not in SELECTION_LIST_VARS and var_name not in _CLASS_LIST_FEEDS:
 136        return
 137    if obj.__dict__.get("_loading_config_values", False) or obj.__dict__.get(
 138        "_tui_editing", False
 139    ):
 140        return
 141    supplied = obj.__dict__.setdefault("_python_supplied", {})
 142    items = list(value)
 143    if replace:
 144        supplied[var_name] = items
 145    elif var_name == "block_rules":
 146        new_keys = {(r["block"], r["path"]) for r in items}
 147        kept = [
 148            r
 149            for r in supplied.get(var_name, [])
 150            if (r["block"], r["path"]) not in new_keys
 151        ]
 152        supplied[var_name] = kept + items
 153    else:
 154        supplied[var_name] = supplied.get(var_name, []) + items
 155
 156
 157def add_pai_config_var_functions(obj, var_name, initial_value, list_type=False):
 158    """Dynamically add a property with getter and setter to an object.
 159
 160    This function adds a private variable along with getter and setter methods
 161    to a given object instance. Used for integrating initial and Perforated
 162    Backpropagation variables into the PAIConfig class.
 163
 164    Parameters
 165    ----------
 166    obj : object
 167        The object to which the property will be added.
 168    var_name : str
 169        Name of the variable/property to create.
 170    initial_value : any
 171        Initial value for the property.
 172
 173    Returns
 174    -------
 175    None
 176
 177    Notes
 178    -----
 179    Creates three attributes on obj:
 180        - _{var_name}: private storage
 181        - get_{var_name}: getter method
 182        - set_{var_name}: setter method
 183    """
 184    private_name = f"_{var_name}"
 185
 186    # Add the private variable to the instance
 187    setattr(obj, private_name, initial_value)
 188
 189    # Define getter and setter and appender
 190
 191    def getter_val(self):
 192        """Get the current value of the property.
 193
 194        If the property a individual value but is set to be a list,
 195        return the element corresponding to the
 196        current number of dendrites added. Otherwise, return the value directly.
 197
 198        Returns
 199        -------
 200        Any
 201            Current value of the property.
 202
 203        Notes:
 204        -----
 205        Many variables have optimal settings that must change as dendrites are added
 206        this enables those values to be dynamically set very easily.
 207
 208        Parameters
 209        ----------
 210        None
 211
 212        """
 213        global pai_tracker
 214        if type(getattr(self, private_name)) is list:
 215            return getattr(self, private_name)[
 216                min(
 217                    len(getattr(self, private_name)) - 1,
 218                    pai_tracker.member_vars["num_dendrites_added"],
 219                )
 220            ]
 221        return getattr(self, private_name)
 222
 223    def getter_list(self):
 224        """Get the underlying list value for this dynamic config property.
 225
 226        Returns
 227        -------
 228        list
 229            Raw list stored for this property.
 230
 231        Parameters
 232        ----------
 233        None
 234
 235        """
 236        return getattr(self, private_name)
 237
 238    def setter(self, value):
 239        """Set the value of the property.
 240
 241        Parameters
 242        ----------
 243        value : Any
 244            New value to assign to the dynamic configuration field.
 245
 246        Returns
 247        -------
 248        None
 249            Updates the property and may trigger configuration auto-save.
 250        """
 251        if (
 252            self.__dict__.get("_module_name") is not None
 253            or self.__dict__.get("_module_type") is not None
 254        ):
 255            raise RuntimeError(
 256                "Setting custom module config values should only be done "
 257                "from JSON config files or the GUI"
 258            )
 259        if var_name in (
 260            "module_ids_to_track",
 261            "module_ids_to_perforate",
 262            "parameter_ids_to_track",
 263        ):
 264            for module_id in value:
 265                _validate_module_id(module_id)
 266        if var_name == "block_rules":
 267            value = _normalize_block_rules(value)
 268        if var_name == "modules_to_fuse":
 269            value = _normalize_fuse_pairs(value)
 270        if var_name == "perforated_backpropagation" and value:
 271            try:
 272                import perforatedbp  # noqa: F401
 273            except ImportError:
 274                raise ValueError(
 275                    "perforated_backpropagation=True requires the 'perforatedbp' package, "
 276                    "which is not installed. Install it separately or leave "
 277                    "perforated_backpropagation=False (the default)."
 278                )
 279        setattr(self, private_name, value)
 280        if isinstance(value, (list, tuple)):
 281            _record_python_supplied(self, var_name, value, replace=True)
 282        if not self.__dict__.get("_loading_config_values", False):
 283            self.__dict__.setdefault("_manually_set_keys", set()).add(var_name)
 284            if var_name == "config_file":
 285                self.sync_config_sources()
 286
 287    def appender(self, value):
 288        """Append a value to the property if it is a list.
 289
 290        Parameters
 291        ----------
 292        value : Any
 293            Value or values to append to the underlying list property.
 294
 295        Returns
 296        -------
 297        None
 298            Appends items in-place and prints the resulting list value.
 299        """
 300        if isinstance(getattr(self, private_name), list):
 301            if var_name in (
 302                "module_ids_to_track",
 303                "module_ids_to_perforate",
 304                "parameter_ids_to_track",
 305            ):
 306                for module_id in value:
 307                    _validate_module_id(module_id)
 308            if var_name == "block_rules":
 309                new_rules = _normalize_block_rules(value)
 310                new_keys = {(r["block"], r["path"]) for r in new_rules}
 311                kept = [
 312                    rule
 313                    for rule in getattr(self, private_name)
 314                    if (rule["block"], rule["path"]) not in new_keys
 315                ]
 316                setattr(self, private_name, kept + new_rules)
 317                _record_python_supplied(self, var_name, new_rules, replace=False)
 318            else:
 319                setattr(self, private_name, getattr(self, private_name) + value)
 320                _record_python_supplied(self, var_name, value, replace=False)
 321            if var_name == "modules_to_fuse":
 322                value = _normalize_fuse_pairs(value)
 323            setattr(self, private_name, getattr(self, private_name) + value)
 324            _record_python_supplied(self, var_name, value, replace=False)
 325            if not self.__dict__.get("_loading_config_values", False):
 326                self.__dict__.setdefault("_manually_set_keys", set()).add(var_name)
 327            print(
 328                'New list value of "{}": {}'.format(
 329                    private_name, getattr(self, private_name)
 330                )
 331            )
 332        else:
 333            raise TypeError(f"Cannot append to non-list attribute '{var_name}'")
 334
 335    # Attach methods to the instance
 336    if list_type:
 337        setattr(obj, f"get_{var_name}", getter_list.__get__(obj))
 338    else:
 339        setattr(obj, f"get_{var_name}", getter_val.__get__(obj))
 340    setattr(obj, f"set_{var_name}", setter.__get__(obj))
 341    setattr(obj, f"append_{var_name}", appender.__get__(obj))
 342
 343
 344# ---------------------------------------------------------------------------
 345# JSON serialization helpers  (used by PAIConfig.save_config / load_config)
 346# ---------------------------------------------------------------------------
 347
 348
 349def _resolve_dotted_name(dotted_name):
 350    """Import and return an object identified by a dotted module path.
 351
 352    E.g. 'torch.nn.modules.conv.Conv2d'  → nn.Conv2d class
 353         'torch.sigmoid'                 → torch.sigmoid function
 354
 355    Returns None if the name cannot be resolved.
 356    """
 357    import importlib
 358
 359    # Common shorthand names accepted in user-facing config files.
 360    if dotted_name == "sigmoid":
 361        return torch.sigmoid
 362    if dotted_name == "relu":
 363        return torch.relu
 364    if dotted_name == "tanh":
 365        return torch.tanh
 366
 367    parts = dotted_name.rsplit(".", 1)
 368    if len(parts) == 2:
 369        try:
 370            mod = importlib.import_module(parts[0])
 371            return getattr(mod, parts[1], None)
 372        except Exception:
 373            pass
 374    # Fall back: try the whole string as a single attribute of builtins
 375    import builtins
 376
 377    return getattr(builtins, dotted_name, None)
 378
 379
 380_TORCH_ACTIVATION_SHORTHAND = ("sigmoid", "relu", "tanh")
 381
 382
 383def callable_config_repr(val):
 384    """Canonical string form of a callable config value (e.g. pai_forward_function).
 385
 386    Shared by config serialisation and the interactive configuration display so
 387    the two never disagree on how a callable is named.
 388    """
 389    name = getattr(val, "__name__", None) or getattr(val, "__qualname__", None)
 390    mod = getattr(val, "__module__", None)
 391    if name and mod:
 392        if name in _TORCH_ACTIVATION_SHORTHAND:
 393            return f"torch.{name}"
 394        return f"{mod}.{name}"
 395    if name:
 396        return str(name)
 397    return repr(val)
 398
 399
 400def _serialize_pai_value(val):
 401    """Recursively convert a PAIConfig value to a JSON-serialisable form."""
 402    if isinstance(val, bool):
 403        return val
 404    if isinstance(val, (int, float, str)):
 405        return val
 406    if isinstance(val, torch.device):
 407        return str(val)
 408    if isinstance(val, torch.dtype):
 409        return str(val)
 410    if isinstance(val, list):
 411        return [_serialize_pai_value(v) for v in val]
 412    if isinstance(val, dict):
 413        return {str(k): _serialize_pai_value(v) for k, v in val.items()}
 414    if isinstance(val, type):
 415        mod = getattr(val, "__module__", "") or ""
 416        return f"{mod}.{val.__name__}" if mod else val.__name__
 417    if callable(val):
 418        return callable_config_repr(val)
 419    return str(val)
 420
 421
 422def _deserialize_pai_value(json_val, type_hint):
 423    """Convert a JSON value to its Python type using an explicit type hint."""
 424    if json_val is None:
 425        return None
 426    if type_hint is torch.device:
 427        return torch.device(str(json_val))
 428    if type_hint is torch.dtype:
 429        v = getattr(torch, str(json_val).split(".", 1)[-1], None)
 430        return v if isinstance(v, torch.dtype) else json_val
 431    if type_hint is callable:
 432        v = _resolve_dotted_name(json_val) if isinstance(json_val, str) else None
 433        return v if (v and callable(v)) else json_val
 434    if type_hint == [type]:  # list whose elements are class objects
 435        return [
 436            (_resolve_dotted_name(v) if isinstance(v, str) else v)
 437            for v in (json_val or [])
 438        ]
 439    return json_val  # bool, int, float, str, list — JSON value is already correct
 440
 441
 442class PAIConfig:
 443    """Configuration class for PAI settings.
 444
 445    This class manages all configuration parameters for the Perforated AI system,
 446    including device settings, dendrite behavior, module conversion rules,
 447    training parameters, and debugging options.
 448
 449    Attributes
 450    ----------
 451    use_cuda : bool
 452        Whether CUDA is available and should be used.
 453    device : torch.device
 454        The device to use for computation (CPU, CUDA, etc.).
 455    save_name : str
 456        Name used for saving models (should not be set manually).
 457    debugging_output_dimensions : int
 458        Debug level for input dimension checking.
 459    confirm_correct_sizes : bool
 460        Whether to verify tensor sizes during execution.
 461    unwrapped_modules_confirmed : bool
 462        Confirmation flag for using unwrapped modules.
 463    weight_decay_accepted : bool
 464        Confirmation flag for accepting weight decay.
 465    checked_skipped_modules : bool
 466        Whether skipped modules have been verified.
 467    verbose : bool
 468        Enable verbose logging output.
 469    extra_verbose : bool
 470        Enable extra verbose logging output.
 471    silent : bool
 472        Suppress all PAI print statements.
 473    save_old_graph_scores : bool
 474        Whether to save historical graph scores.
 475    testing_dendrite_capacity : bool
 476        Enable dendrite capacity testing mode.
 477    using_safe_tensors : bool
 478        Use safe tensors file format for saving.
 479    global_candidates : int
 480        Number of global candidate dendrites.
 481    drawing_pai : bool
 482        Enable PAI visualization graphs.
 483    test_saves : bool
 484        Save intermediary test models.
 485    pai_saves : bool
 486        Save PAI-specific format models.
 487    output_dimensions : list
 488        Format specification for input tensor dimensions.
 489    improvement_threshold : float
 490        Relative improvement threshold for validation scores.
 491    improvement_threshold_raw : float
 492        Absolute improvement threshold for validation scores.
 493    candidate_weight_initialization_multiplier : float
 494        Multiplier for random dendrite weight initialization.
 495    DOING_SWITCH_EVERY_TIME : int
 496        Constant for switch mode: add dendrites every epoch.
 497    DOING_HISTORY : int
 498        Constant for switch mode: add dendrites based on validation history.
 499    n_epochs_to_switch : int
 500        Number of epochs without improvement before switching.
 501    history_lookback : int
 502        Number of epochs to average for validation history.
 503    initial_history_after_switches : int
 504        Epochs to wait after adding dendrites before beggining checks.
 505    DOING_FIXED_SWITCH : int
 506        Constant for switch mode: add dendrites at fixed intervals.
 507    n_fixed_switch_num : int
 508        Number of epochs between fixed switches (neuron mode).
 509    first_fixed_switch_num : int
 510        Number of epochs before first switch (for pretraining).
 511    DOING_NO_SWITCH : int
 512        Constant for switch mode: never add dendrites.
 513    switch_mode : int
 514        Current switch mode setting.
 515    reset_best_score_on_switch : bool
 516        Whether to reset best score when adding dendrites.
 517    learn_dendrites_live : bool
 518        Enable live dendrite learning (advanced feature).
 519    no_extra_n_modes : bool
 520        Disable extra neuron modes (advanced feature).
 521    d_type : torch.dtype
 522        Data type for dendrite weights.
 523    retain_all_dendrites : bool
 524        Keep dendrites even if they don't improve performance.
 525    find_best_lr : bool
 526        Automatically sweep learning rates when adding dendrites.
 527    dont_give_up_unless_learning_rate_lowered : bool
 528        Ensure search lowers learning rate at least once.
 529    lr_binary_search_max_depth : int
 530        Maximum binary search depth for LR sweep (default 4).
 531    dendrite_lr_multiplier : float
 532        Learning rate multiplier for dendrite weights and their output weights.
 533    max_dendrite_tries : int
 534        Maximum attempts to add dendrites with random initializations.
 535    max_dendrites : int
 536        Maximum total number of dendrites to add.
 537    PARAM_VALS_BY_TOTAL_EPOCH : int
 538        Constant: scheduler params tracked by total epochs.
 539    PARAM_VALS_BY_UPDATE_EPOCH : int
 540        Constant: scheduler params reset at each switch.
 541    PARAM_VALS_BY_NEURON_EPOCH_START : int
 542        Constant: scheduler params reset for neuron starts only.
 543    param_vals_setting : int
 544        Current parameter tracking mode.
 545    pai_forward_function : callable
 546        Activation function used for dendrites.
 547    modules_to_perforate : list
 548        Module types to convert to PAI modules for perforation.
 549    module_names_to_perforate : list
 550        Module names to convert to PAI modules for perforation.
 551    module_ids_to_perforate : list
 552        Specific module IDs to convert to PAI modules for perforation.
 553    block_rules : list
 554        {"block", "path", "mode"} entries applied inside every instance of a
 555        block class (a module type with children that occurs more than once).
 556    modules_to_fuse : list
 557        Pairs of [head_id, norm_id] module ids to fuse into one block.
 558    modules_to_track : list
 559        Module types to track but not convert.
 560    module_names_to_track : list
 561        Module names to track but not convert.
 562    module_ids_to_track : list
 563        Specific module IDs to track but not convert.
 564    modules_to_replace : list
 565        Module types to replace before conversion.
 566    replacement_modules : list
 567        Replacement modules for modules_to_replace.
 568    modules_with_processing : list
 569        Module types requiring custom processing.
 570    modules_processing_classes : list
 571        Processing classes for modules_with_processing.
 572    module_names_with_processing : list
 573        Module names requiring custom processing.
 574    module_by_name_processing_classes : list
 575        Processing classes for module_names_with_processing.
 576    module_names_to_not_save : list
 577        Module names to exclude from saving.
 578    perforated_backpropagation : bool
 579        Whether Perforated Backpropagation is enabled.
 580    """
 581
 582    # Explicit type map for every config variable — used by load_config to coerce JSON values.
 583    # [type] means "list whose elements are class/type objects" (need dotted-name resolution).
 584    _TYPES: dict = {
 585        **{
 586            k: bool
 587            for k in (
 588                "use_cuda",
 589                "confirm_correct_sizes",
 590                "unwrapped_modules_confirmed",
 591                "weight_decay_accepted",
 592                "checked_skipped_modules",
 593                "configuration_confirmed",
 594                "verbose",
 595                "extra_verbose",
 596                "silent",
 597                "save_old_graph_scores",
 598                "testing_dendrite_capacity",
 599                "strict_loading",
 600                "using_safe_tensors",
 601                "drawing_pai",
 602                "drawing_extra_graphs",
 603                "test_saves",
 604                "pai_saves",
 605                "reset_best_score_on_switch",
 606                "learn_dendrites_live",
 607                "no_extra_n_modes",
 608                "retain_all_dendrites",
 609                "find_best_lr",
 610                "dont_give_up_unless_learning_rate_lowered",
 611                "maximizing_score",
 612                "candidate_weight_init_by_main",
 613                "perforated_backpropagation",
 614                "weight_tying_experimental",
 615                "dashboard_events_enabled",
 616                "dashboard_debug",
 617            )
 618        },
 619        **{
 620            k: int
 621            for k in (
 622                "debugging_output_dimensions",
 623                "global_candidates",
 624                "n_epochs_to_switch",
 625                "history_lookback",
 626                "initial_history_after_switches",
 627                "n_fixed_switch_num",
 628                "first_fixed_switch_num",
 629                "switch_mode",
 630                "max_dendrite_tries",
 631                "max_dendrites",
 632                "param_vals_setting",
 633            )
 634        },
 635        **{
 636            k: float
 637            for k in (
 638                "improvement_threshold_raw",
 639                "candidate_weight_initialization_multiplier",
 640                "dendrite_lr_multiplier",
 641            )
 642        },
 643        **{
 644            k: str
 645            for k in (
 646                "save_name",
 647                "library_validation_score",
 648                "dashboard_url",
 649            )
 650        },
 651        "device": torch.device,
 652        "d_type": torch.dtype,
 653        "pai_forward_function": callable,
 654        **{
 655            k: list
 656            for k in (
 657                "output_dimensions",
 658                "improvement_threshold",
 659                "module_names_to_perforate",
 660                "module_ids_to_perforate",
 661                "module_names_to_track",
 662                "module_ids_to_track",
 663                "parameter_ids_to_track",
 664                "block_rules",
 665                "modules_to_fuse",
 666                "module_names_with_processing",
 667                "module_names_to_not_save",
 668                "library_extra_scores",
 669                "library_extra_scores_without_graphing",
 670            )
 671        },
 672        **{
 673            k: [type]
 674            for k in (
 675                "modules_to_perforate",
 676                "modules_to_track",
 677                "modules_to_replace",
 678                "replacement_modules",
 679                "modules_with_processing",
 680                "modules_processing_classes",
 681                "module_by_name_processing_classes",
 682            )
 683        },
 684    }
 685
 686    # Subset of _TYPES: variables that can be overridden on a per-module basis
 687    # via the Studio.  These are set outside the ``if not module_name:`` block
 688    # in :py:meth:`__init__`, so they are meaningful when constructing a
 689    # module-specific PAIConfig instance.
 690    _CUSTOMIZABLE: dict = {
 691        #"verbose": bool,
 692        #"extra_verbose": bool,
 693        #"silent": bool,
 694        #"global_candidates": int,
 695        "output_dimensions": list,
 696        #"candidate_weight_initialization_multiplier": float,
 697        #"candidate_weight_init_by_main": bool,
 698        #"retain_all_dendrites": bool,
 699        #"max_dendrites": int,
 700        #"pai_forward_function": callable,
 701    }
 702
 703    def __getstate__(self):
 704        """Tell pickle what to save when this object is serialized (e.g. torch.save).
 705
 706        The get_*/set_*/append_* methods attached to each PAIConfig instance are
 707        locally-defined closures and cannot be pickled.  Only the underlying data
 708        values (stored as _<name> in __dict__) need to be saved; __setstate__
 709        will recreate the methods by calling __init__ on load.
 710        """
 711        import types
 712
 713        # Walk every attribute on this instance and keep only the plain data values.
 714        # Bound methods (the get_*/set_*/append_* closures) are skipped because
 715        # they cannot be serialized by pickle.
 716        pickle_safe_state = {}
 717        for attr_name, attr_value in self.__dict__.items():
 718            if not isinstance(attr_value, types.MethodType):
 719                pickle_safe_state[attr_name] = attr_value
 720
 721        return pickle_safe_state
 722
 723    def __setstate__(self, saved_state):
 724        """Restore this object from a pickled state (e.g. torch.load).
 725
 726        Calls __init__ to rebuild all the get_*/set_*/append_* methods, then
 727        overlays the saved data values on top so all settings are preserved.
 728        """
 729        # Grab the identity fields needed to reconstruct the right flavor of config
 730        # (global config vs. per-module config).
 731        saved_module_name = saved_state.get("_module_name")
 732        saved_module_type = saved_state.get("_module_type")
 733
 734        # Re-run __init__ so all the get_*/set_*/append_* methods exist again.
 735        # This also sets default values for every variable, which we overwrite below.
 736        self.__init__(module_name=saved_module_name, module_type=saved_module_type)
 737
 738        # Overwrite the defaults with the actual saved values.
 739        # Only restore private data attributes (prefixed with _); skip the identity
 740        # fields we already handled above, and skip _config_file for now so that
 741        # the setter calls above do not trigger auto-save during the restore.
 742        skip_on_first_pass = {"_module_name", "_module_type", "_config_file"}
 743        for attr_name, attr_value in saved_state.items():
 744            if attr_name.startswith("_") and attr_name not in skip_on_first_pass:
 745                self.__dict__[attr_name] = attr_value
 746
 747        # Restore the config file path last.  Auto-save is driven by _config_file
 748        # being set, so we only put it back after all values are already in place.
 749        if saved_state.get("_config_file"):
 750            self.__dict__["_config_file"] = saved_state["_config_file"]
 751
 752    def __getattr__(self, name):
 753        """Handle missing attributes gracefully, especially for PB variables.
 754
 755        Parameters
 756        ----------
 757        name : str
 758            The name of the attribute being accessed.
 759
 760        Returns
 761        -------
 762        None or raises AttributeError
 763            Returns None for missing set_ methods, raises AttributeError otherwise.
 764        """
 765        if name.startswith("set_"):
 766            print(f"Variable '{name[4:]}' does not exist.  Ignoring set attempt.")
 767            return lambda x: None
 768        if name.startswith("append_"):
 769            print(
 770                f"List Variable '{name[7:]}' does not exist.  Ignoring append attempt."
 771            )
 772            return lambda x: None
 773        if name.startswith("get_") and self.__dict__.get("_module_name") is not None:
 774            # Module-specific config: check for a per-module override stored directly in
 775            # __dict__ (written by load_config when custom JSON data was found for this
 776            # module).  This covers CUSTOMIZABLE vars that are not initialised for
 777            # per-module configs (e.g. output_dimensions, which lives inside the
 778            # ``if not module_name:`` block).
 779            private_key = f"_{name[4:]}"
 780            if private_key in self.__dict__:
 781                stored = self.__dict__[private_key]
 782                return lambda: stored
 783            # Fall back to the global pc instance for vars not set on this instance.
 784            global_getter = getattr(pc, name, None)
 785            if global_getter is not None:
 786                return global_getter
 787        raise AttributeError(
 788            f"'{self.__class__.__name__}' object has no attribute '{name}'"
 789        )
 790
 791    def __init__(self, module_name=None, module_type=None):
 792        """Initialize PAIConfig with default settings.
 793
 794        module_name=None means this is the main global config.
 795        If module_name is set this is a per-module config that loads
 796        custom settings from module_settings[module_name] (by id) or
 797        module_settings[module_type] (by type) in the JSON file.
 798        """
 799        # Must be first: prevents __getattr__ from firing for _config_file
 800        # during construction (before add_pai_config_var_functions sets it).
 801        # Also disables auto-save in setters until the end of __init__.
 802        self.__dict__["_config_file"] = None
 803        self.__dict__["_manually_set_keys"] = set()
 804        self.__dict__["_loading_config_values"] = False
 805        # None = global config; any string = per-module config
 806        self.__dict__["_module_name"] = module_name
 807        # Short class name of the wrapped module (e.g. 'Conv2d'), used as
 808        # a fallback lookup key when the specific name has no saved settings.
 809        self.__dict__["_module_type"] = module_type
 810
 811        if not module_name:
 812            ### Global Constants
 813            # Device configuration
 814            self.use_cuda = torch.cuda.is_available()
 815            add_pai_config_var_functions(self, "use_cuda", self.use_cuda)
 816            self.device = torch.device("cuda" if self.use_cuda else "cpu")
 817            add_pai_config_var_functions(self, "device", self.device)
 818
 819            self.save_name = ""
 820            add_pai_config_var_functions(self, "save_name", self.save_name)
 821
 822            self.config_file = None
 823            add_pai_config_var_functions(self, "config_file", self.config_file)
 824
 825            # Debug settings
 826            self.debugging_output_dimensions = 0
 827            add_pai_config_var_functions(
 828                self, "debugging_output_dimensions", self.debugging_output_dimensions
 829            )
 830            # Debugging input tensor sizes.
 831            # This will slow things down very slightly and is not necessary but can help
 832            # catch when dimensions were not filled in correctly.
 833            self.confirm_correct_sizes = False
 834            add_pai_config_var_functions(
 835                self, "confirm_correct_sizes", self.confirm_correct_sizes
 836            )
 837
 838            # Confirmation flags for non-recommended options
 839            self.unwrapped_modules_confirmed = False
 840            add_pai_config_var_functions(
 841                self, "unwrapped_modules_confirmed", self.unwrapped_modules_confirmed
 842            )
 843            # We used to be worried this caused problems, but it is now accepted.
 844            # Leaving code in case future changes require revisiting this decision.
 845            self.weight_decay_accepted = True
 846            add_pai_config_var_functions(
 847                self, "weight_decay_accepted", self.weight_decay_accepted
 848            )
 849            self.checked_skipped_modules = False
 850            add_pai_config_var_functions(
 851                self, "checked_skipped_modules", self.checked_skipped_modules
 852            )
 853            self.configuration_confirmed = False
 854            add_pai_config_var_functions(
 855                self, "configuration_confirmed", self.configuration_confirmed
 856            )
 857            # Analysis settings
 858            self.save_old_graph_scores = True
 859            add_pai_config_var_functions(
 860                self, "save_old_graph_scores", self.save_old_graph_scores
 861            )
 862            # Testing settings
 863            self.testing_dendrite_capacity = True
 864            add_pai_config_var_functions(
 865                self, "testing_dendrite_capacity", self.testing_dendrite_capacity
 866            )
 867
 868            # File format settings
 869            self.using_safe_tensors = True
 870            add_pai_config_var_functions(
 871                self, "using_safe_tensors", self.using_safe_tensors
 872            )
 873
 874            # Checkpoint loading settings
 875            # Whether to use strict=True when loading state_dict
 876            # Set to False if loading old checkpoints that are missing new fields
 877            self.strict_loading = True
 878            add_pai_config_var_functions(
 879                self, "strict_loading", self.strict_loading
 880            )
 881
 882            # Graph and visualization settings
 883            # A graph setting which can be set to false if you want to do your own
 884            # training visualizations
 885            self.drawing_pai = True
 886            add_pai_config_var_functions(self, "drawing_pai", self.drawing_pai)
 887
 888            # Drawing extra graphs beyond the standard ones.
 889            self.drawing_extra_graphs = True
 890            add_pai_config_var_functions(
 891                self, "drawing_extra_graphs", self.drawing_extra_graphs
 892            )
 893
 894            # Saving test intermediary models, good for experimentation, bad for memory
 895            self.test_saves = True
 896            add_pai_config_var_functions(self, "test_saves", self.test_saves)
 897            # To be filled in later. pai_saves will remove some extra scaffolding for
 898            # slight memory and speed improvements
 899            self.pai_saves = False
 900            add_pai_config_var_functions(self, "pai_saves", self.pai_saves)
 901            # Improvement thresholds
 902            # Percentage improvement increase needed to call a new best validation score
 903            self.improvement_threshold = [0.001, 0.0001, 0.0]
 904            add_pai_config_var_functions(
 905                self, "improvement_threshold", self.improvement_threshold
 906            )
 907
 908            # Raw increase needed
 909            self.improvement_threshold_raw = 1e-5
 910            add_pai_config_var_functions(
 911                self, "improvement_threshold_raw", self.improvement_threshold_raw
 912            )
 913            # SWITCH MODE SETTINGS
 914
 915            # Add dendrites every time to debug implementation
 916            self.DOING_SWITCH_EVERY_TIME = 0
 917
 918            # Switch when validation hasn't improved over x epochs
 919            self.DOING_HISTORY = 1
 920            # Epochs to try before deciding to load previous best and add dendrites
 921            # Be sure this is higher than scheduler patience
 922            self.n_epochs_to_switch = 10
 923            add_pai_config_var_functions(
 924                self, "n_epochs_to_switch", self.n_epochs_to_switch
 925            )
 926            # Number to average validation scores over
 927            self.history_lookback = 1
 928            add_pai_config_var_functions(
 929                self, "history_lookback", self.history_lookback
 930            )
 931            # Amount of epochs to run after adding a new set of dendrites before checking
 932            # to add more
 933            self.initial_history_after_switches = 0
 934            add_pai_config_var_functions(
 935                self,
 936                "initial_history_after_switches",
 937                self.initial_history_after_switches,
 938            )
 939
 940            # Switch after a fixed number of epochs
 941            self.DOING_FIXED_SWITCH = 2
 942            # Number of epochs to complete before switching (neuron mode)
 943            self.n_fixed_switch_num = 250
 944            add_pai_config_var_functions(
 945                self, "n_fixed_switch_num", self.n_fixed_switch_num
 946            )
 947            # An additional flag if you want your first switch to occur later than all the
 948            # rest for initial pretraining.  This is a new minimum, if its lower than
 949            # the above it will be ignored.
 950            self.first_fixed_switch_num = -1
 951            add_pai_config_var_functions(
 952                self, "first_fixed_switch_num", self.first_fixed_switch_num
 953            )
 954
 955            # A setting to not add dendrites and just do regular training
 956            # Warning, this will also never trigger training_complete
 957            self.DOING_NO_SWITCH = 3
 958
 959            # Default switch mode
 960            self.switch_mode = self.DOING_HISTORY
 961            add_pai_config_var_functions(self, "switch_mode", self.switch_mode)
 962
 963            # Reset settings
 964            # Resets score on switch
 965            # This can be useful if you need many epochs to catch up to the best score
 966            # from the previous version after adding dendrites
 967            self.reset_best_score_on_switch = True
 968            add_pai_config_var_functions(
 969                self, "reset_best_score_on_switch", self.reset_best_score_on_switch
 970            )
 971
 972            # Advanced settings
 973            # Not used in open source implementation, leave as default
 974            self.learn_dendrites_live = False
 975            add_pai_config_var_functions(
 976                self, "learn_dendrites_live", self.learn_dendrites_live
 977            )
 978            self.no_extra_n_modes = True
 979            add_pai_config_var_functions(
 980                self, "no_extra_n_modes", self.no_extra_n_modes
 981            )
 982
 983            # Data type for new modules and dendrite to dendrite / dendrite to neuron
 984            # weights
 985            self.d_type = torch.float
 986            add_pai_config_var_functions(self, "d_type", self.d_type)
 987
 988            # Learning rate management
 989            # A setting to automatically sweep over previously used learning rates when
 990            # adding new dendrites
 991            # Sometimes it's best to go back to initial LR, but often its best to start
 992            # at a lower LR
 993            self.find_best_lr = True
 994            add_pai_config_var_functions(self, "find_best_lr", self.find_best_lr)
 995            # Enforces the above even if the previous epoch didn't lower the learning rate
 996            self.dont_give_up_unless_learning_rate_lowered = True
 997            add_pai_config_var_functions(
 998                self,
 999                "dont_give_up_unless_learning_rate_lowered",
1000                self.dont_give_up_unless_learning_rate_lowered,
1001            )
1002            # Maximum depth for binary search LR sweep. Limits total tests to O(log N).
1003            self.lr_binary_search_max_depth = 4
1004            add_pai_config_var_functions(
1005                self,
1006                "lr_binary_search_max_depth",
1007                self.lr_binary_search_max_depth,
1008            )
1009            # Dendrites and their output weights train at the optimizer's learning rate
1010            # times this. Their output weights start at 0, so with a small learning
1011            # rate, such as when fine-tuning, new dendrites barely change the network.
1012            # Applied by setup_optimizer, or by passing the optimizer's params
1013            # through UPA.get_parameter_groups when using set_optimizer_instance.
1014            self.dendrite_lr_multiplier = 1.0
1015            add_pai_config_var_functions(
1016                self, "dendrite_lr_multiplier", self.dendrite_lr_multiplier
1017            )
1018            # Whether a higher validation score is better (True) or lower is better (False).
1019            self.maximizing_score = True
1020            add_pai_config_var_functions(
1021                self, "maximizing_score", self.maximizing_score
1022            )
1023
1024            # Dendrite attempt settings
1025            # Set to 1 if you want to quit as soon as one dendrite fails
1026            # Higher values will try new random dendrite weights this many times before
1027            # accepting that more dendrites don't improve
1028            self.max_dendrite_tries = 2
1029            add_pai_config_var_functions(
1030                self, "max_dendrite_tries", self.max_dendrite_tries
1031            )
1032
1033            # Scheduler parameter settings
1034            # Have learning rate params be by total epoch
1035            self.PARAM_VALS_BY_TOTAL_EPOCH = 0
1036            # Reset the params at every switch
1037            self.PARAM_VALS_BY_UPDATE_EPOCH = 1
1038            # Reset params for dendrite starts but not for normal restarts
1039            # Not used for open source version
1040            self.PARAM_VALS_BY_NEURON_EPOCH_START = 2
1041            # Default setting
1042            self.param_vals_setting = self.PARAM_VALS_BY_UPDATE_EPOCH
1043            add_pai_config_var_functions(
1044                self, "param_vals_setting", self.param_vals_setting
1045            )
1046            # Lists for module types and names to add dendrites to
1047            # For these lists no specifier means type, name is module name
1048            # and ids is the individual modules id, eg. model.conv2
1049            self.modules_to_perforate = []
1050            add_pai_config_var_functions(
1051                self, "modules_to_perforate", self.modules_to_perforate, list_type=True
1052            )
1053            self.module_names_to_perforate = [
1054                "PAISequential",
1055                "Conv1d",
1056                "Conv2d",
1057                "Conv3d",
1058                "Linear",
1059            ]
1060            add_pai_config_var_functions(
1061                self,
1062                "module_names_to_perforate",
1063                self.module_names_to_perforate,
1064                list_type=True,
1065            )
1066            self.module_ids_to_perforate = []
1067            add_pai_config_var_functions(
1068                self,
1069                "module_ids_to_perforate",
1070                self.module_ids_to_perforate,
1071                list_type=True,
1072            )
1073
1074            # All modules should either be perforated or tracked to ensure all modules
1075            # are accounted for
1076            self.modules_to_track = []
1077            add_pai_config_var_functions(
1078                self, "modules_to_track", self.modules_to_track, list_type=True
1079            )
1080            self.module_names_to_track = []
1081            add_pai_config_var_functions(
1082                self,
1083                "module_names_to_track",
1084                self.module_names_to_track,
1085                list_type=True,
1086            )
1087            # IDs are for if you want to pass only a single module by its assigned ID rather than the module type by name
1088            self.module_ids_to_track = []
1089            add_pai_config_var_functions(
1090                self, "module_ids_to_track", self.module_ids_to_track, list_type=True
1091            )
1092
1093            # Block rules: {"block": class name, "path": relative path, "mode"}
1094            # entries applied inside every instance of that block class, e.g.
1095            # {"block": "BasicBlock", "path": ".conv2", "mode": "perforated"}.
1096            # A mode set directly by id wins; a block rule wins over a type rule.
1097            self.block_rules = []
1098            add_pai_config_var_functions(
1099                self, "block_rules", self.block_rules, list_type=True
1100            )
1101            # Pairs of [head_id, norm_id] to fuse so the norm is trained with the
1102            # head it follows; applied by fuse_modules before conversion
1103            self.modules_to_fuse = []
1104            add_pai_config_var_functions(
1105                self, "modules_to_fuse", self.modules_to_fuse, list_type=True
1106            )
1107
1108            # Parameter IDs to track as neuron parameters without recursive behavior
1109            # (e.g., [".my_custom_parameter"]).
1110            self.parameter_ids_to_track = []
1111            add_pai_config_var_functions(
1112                self,
1113                "parameter_ids_to_track",
1114                self.parameter_ids_to_track,
1115                list_type=True,
1116            )
1117
1118            # Replacement modules happen before the conversion,
1119            # so replaced modules will then also be run through the conversion steps
1120            # These are for modules that need to be replaced before addition of dendrites
1121            # See the resnet example in models_perforatedai
1122            self.modules_to_replace = []
1123            add_pai_config_var_functions(
1124                self, "modules_to_replace", self.modules_to_replace, list_type=True
1125            )
1126            # Modules to replace the above modules with
1127            self.replacement_modules = []
1128            add_pai_config_var_functions(
1129                self, "replacement_modules", self.replacement_modules, list_type=True
1130            )
1131
1132            # Dendrites default to modules which are one tensor input and one tensor
1133            # output in forward()
1134            # Other modules require to be labeled as modules with processing and assigned
1135            # processing classes
1136            # This can be done by module type or module name see customization.md in API
1137            # for example
1138            self.modules_with_processing = []
1139            add_pai_config_var_functions(
1140                self,
1141                "modules_with_processing",
1142                self.modules_with_processing,
1143                list_type=True,
1144            )
1145            self.modules_processing_classes = []
1146            add_pai_config_var_functions(
1147                self,
1148                "modules_processing_classes",
1149                self.modules_processing_classes,
1150                list_type=True,
1151            )
1152            self.module_names_with_processing = []
1153            add_pai_config_var_functions(
1154                self,
1155                "module_names_with_processing",
1156                self.module_names_with_processing,
1157                list_type=True,
1158            )
1159            self.module_by_name_processing_classes = []
1160            add_pai_config_var_functions(
1161                self,
1162                "module_by_name_processing_classes",
1163                self.module_by_name_processing_classes,
1164                list_type=True,
1165            )
1166
1167            # Similarly here as above. Some huggingface models have multiple pointers to
1168            # the same modules which cause problems
1169            # If you want to only save one of the multiple pointers you can set which ones
1170            # not to save here
1171            self.module_names_to_not_save = [".base_model"]
1172            add_pai_config_var_functions(
1173                self,
1174                "module_names_to_not_save",
1175                self.module_names_to_not_save,
1176                list_type=True,
1177            )
1178
1179            # Perforated Backpropagation settings
1180            self.perforated_backpropagation = False
1181            add_pai_config_var_functions(
1182                self, "perforated_backpropagation", self.perforated_backpropagation
1183            )
1184
1185            # This is specifically a workaround for weight tying
1186            # Not to be used for a duplicate pointer that isn't actually run twice
1187            self.weight_tying_experimental = False
1188            add_pai_config_var_functions(
1189                self, "weight_tying_experimental", self.weight_tying_experimental
1190            )
1191
1192            # Dashboard event streaming settings
1193            self.dashboard_events_enabled = False
1194            add_pai_config_var_functions(
1195                self, "dashboard_events_enabled", self.dashboard_events_enabled
1196            )
1197            self.dashboard_url = "http://localhost:3002"
1198            add_pai_config_var_functions(
1199                self, "dashboard_url", self.dashboard_url
1200            )
1201            self.dashboard_debug = False
1202            add_pai_config_var_functions(
1203                self, "dashboard_debug", self.dashboard_debug
1204            )
1205
1206            # These are settings where libraries must be doing the scoring adding to
1207            # message from your main script what metric to use
1208            self.library_validation_score = ""
1209            add_pai_config_var_functions(
1210                self, "library_validation_score", self.library_validation_score
1211            )
1212            self.library_extra_scores = []
1213            add_pai_config_var_functions(
1214                self,
1215                "library_extra_scores",
1216                self.library_extra_scores,
1217                list_type=True,
1218            )
1219            self.library_extra_scores_without_graphing = []
1220            add_pai_config_var_functions(
1221                self,
1222                "library_extra_scores_without_graphing",
1223                self.library_extra_scores_without_graphing,
1224                list_type=True,
1225            )
1226
1227            # Input dimensions needs to be set every time. It is set to what format of
1228            # planes you are expecting.
1229            # Neuron index should be set to 0, variable indexes should be set to -1.
1230            # For example, if your format is [batchsize, nodes, x, y]
1231            # output_dimensions is [-1, 0, -1, -1].
1232            # if your format is, [batchsize, time index, nodes] output_dimensions is
1233            # [-1, -1, 0]
1234            # TODO consider changing from a single set here to a set for each type of module
1235            # TODO should not set this value directly, should be a setter like set_this_output_dimensions in PAINeuronModule
1236            self.output_dimensions = [REDUCE_AXIS, NODE_AXIS, NOT_REDUCE_OR_NODE_AXIS, NOT_REDUCE_OR_NODE_AXIS]
1237            add_pai_config_var_functions(
1238                self, "output_dimensions", self.output_dimensions, list_type=True
1239            )
1240        # Verbosity settings
1241        self.verbose = False
1242        add_pai_config_var_functions(self, "verbose", self.verbose)
1243        self.extra_verbose = False
1244        add_pai_config_var_functions(self, "extra_verbose", self.extra_verbose)
1245        # Suppress all PAI prints
1246        self.silent = False
1247        add_pai_config_var_functions(self, "silent", self.silent)
1248
1249        # Epoch-boundary callback lists.  Each holds callables invoked with the tracker as
1250        # their sole argument at the corresponding boundary (see start_epoch / stop_epoch).
1251        # Declared inline (no redundant plain attribute) so only the private
1252        # _epoch_*_callbacks storage exists; save_config skips those two names so the lists
1253        # never round-trip through JSON.
1254        add_pai_config_var_functions(self, "epoch_start_callbacks", [], list_type=True)
1255        add_pai_config_var_functions(self, "epoch_stop_callbacks", [], list_type=True)
1256
1257        # In place for future implementation options of adding multiple candidate
1258        # dendrites together
1259        self.global_candidates = 1
1260        add_pai_config_var_functions(self, "global_candidates", self.global_candidates)
1261
1262        # Weight initialization settings
1263        # Multiplier when randomizing dendrite weights
1264        self.candidate_weight_initialization_multiplier = 0.01
1265        add_pai_config_var_functions(
1266            self,
1267            "candidate_weight_initialization_multiplier",
1268            self.candidate_weight_initialization_multiplier,
1269        )
1270        # Multiplier when randomizing dendrite weights
1271        self.candidate_weight_init_by_main = False
1272        add_pai_config_var_functions(
1273            self,
1274            "candidate_weight_init_by_main",
1275            self.candidate_weight_init_by_main,
1276        )
1277
1278        # Dendrite retention settings
1279        # A setting to keep dendrites even if they do not improve scores
1280        self.retain_all_dendrites = False
1281        add_pai_config_var_functions(
1282            self, "retain_all_dendrites", self.retain_all_dendrites
1283        )
1284
1285        # Max dendrites to add even if they do continue improving scores
1286        self.max_dendrites = 100
1287        add_pai_config_var_functions(self, "max_dendrites", self.max_dendrites)
1288
1289        # Activation function settings
1290        # The activation function to use for dendrites
1291        self.pai_forward_function = torch.sigmoid
1292        add_pai_config_var_functions(
1293            self, "pai_forward_function", self.pai_forward_function
1294        )
1295
1296        # Apply per-module overrides after defaults are defined so loaded values
1297        # win over initializer defaults.
1298        if module_name is not None:
1299            import os
1300
1301            global_pc = globals().get("pc")
1302            source_paths = []
1303            if global_pc is not None:
1304                config_file = getattr(global_pc, "__dict__", {}).get("_config_file")
1305                run_config = global_pc.get_run_config_path()
1306                if config_file:
1307                    source_paths.append(config_file)
1308                if run_config:
1309                    source_paths.append(run_config)
1310
1311            for source_path in source_paths:
1312                if source_path and os.path.exists(source_path):
1313                    self.load_config(
1314                        source_path,
1315                        module_name=module_name,
1316                        module_type=module_type,
1317                    )
1318                    break
1319
1320        # ------------------------------------------------------------------
1321        # Config file will be set when save_name is assigned (in perforate_model)
1322        # ------------------------------------------------------------------
1323        # _config_file stays None until save_name is set to a non-empty value
1324
1325    # ------------------------------------------------------------------
1326
1327    def save_config(self, filename, include_confirmed=True):
1328        """Save the current PAIConfig state to a JSON file.
1329
1330        Parameters
1331        ----------
1332        filename : str
1333            Destination file path (created or overwritten).
1334        include_confirmed : bool
1335            When False, ``configuration_confirmed`` is left out of the file.
1336            Run configs use this so a one-off confirmation is not replayed on
1337            later runs.
1338
1339        Notes
1340        -----
1341        Values that are not natively JSON-serialisable (torch.device,
1342        torch.dtype, nn.Module subclasses, callables) are stored as their
1343        dotted-string representations so they can be round-tripped by
1344        :py:meth:`load_config`.
1345
1346        Returns
1347        -------
1348        None
1349            This function does not return a value.
1350        """
1351        import json
1352
1353        config_dict = {}
1354
1355        # Private-storage vars added by add_pai_config_var_functions
1356        # e.g. self._module_ids_to_perforate → key 'module_ids_to_perforate'
1357        for key, val in sorted(self.__dict__.items()):
1358            if not (key.startswith("_") and not key.startswith("__")):
1359                continue
1360            # Skip internal bookkeeping keys that must not round-trip through JSON
1361            if key in (
1362                "_config_file",
1363                "_module_name",
1364                "_module_type",
1365                "_epoch_start_callbacks",
1366                "_epoch_stop_callbacks",
1367                "_manually_set_keys",
1368                "_loading_config_values",
1369                "_auto_persist_config",
1370                "_python_supplied",
1371                "_tui_editing",
1372            ):
1373                continue
1374            clean_key = key[1:]
1375            if clean_key == "configuration_confirmed" and not include_confirmed:
1376                continue
1377            # Keep callable config fields (e.g. pai_forward_function) but skip
1378            # any other private callable values that are not typed as callable.
1379            if callable(val) and PAIConfig._TYPES.get(clean_key) is not callable:
1380                continue
1381            try:
1382                config_dict[clean_key] = _serialize_pai_value(val)
1383            except Exception:
1384                config_dict[clean_key] = str(val)
1385
1386        # Plain constants (DOING_*, PARAM_VALS_BY_*, etc.)
1387        for key, val in self.__dict__.items():
1388            if key.startswith("_") or callable(val):
1389                continue
1390            if key not in config_dict:
1391                # Keep config_file runtime-only: do not persist pointer paths in
1392                # saved JSON snapshots.
1393                if key == "config_file":
1394                    continue
1395                if key == "configuration_confirmed" and not include_confirmed:
1396                    continue
1397                try:
1398                    config_dict[key] = _serialize_pai_value(val)
1399                except Exception:
1400                    config_dict[key] = str(val)
1401
1402        # Merge short class names from modules_to_perforate into module_names_to_perforate
1403        # so the UI (and JS) only needs to check one array.
1404        type_short_names = [
1405            cls.__name__
1406            for cls in self.__dict__.get("_modules_to_perforate", [])
1407            if isinstance(cls, type)
1408        ]
1409        existing = config_dict.get("module_names_to_perforate", [])
1410        config_dict["module_names_to_perforate"] = existing + [
1411            n for n in type_short_names if n not in existing
1412        ]
1413
1414        # Preserve any per-module settings written by the Studio frontend.
1415        _existing_ms: dict = {}
1416        try:
1417            with open(filename, "r") as _f:
1418                _existing_ms = json.load(_f).get("module_settings", {})
1419        except Exception:
1420            pass
1421        config_dict["module_settings"] = _existing_ms
1422
1423        # Publish customizable field type names so the Studio frontend can
1424        # render appropriate editors without needing to import the library.
1425        config_dict["_customizable_fields"] = {
1426            k: (v.__name__ if hasattr(v, "__name__") else str(v))
1427            for k, v in PAIConfig._CUSTOMIZABLE.items()
1428        }
1429
1430        # Ensure the directory exists before saving
1431        import os
1432        import tempfile
1433
1434        directory = os.path.dirname(filename)
1435        if directory:
1436            os.makedirs(directory, exist_ok=True)
1437
1438        # Atomic write: never leave the file truncated (DDP ranks may read concurrently).
1439        fd, tmp_path = tempfile.mkstemp(dir=directory or ".", suffix=".tmp")
1440        try:
1441            with os.fdopen(fd, "w") as f:
1442                json.dump(config_dict, f, indent=2)
1443            # mkstemp creates the file owner-only; match what a plain open() would give
1444            umask = os.umask(0)
1445            os.umask(umask)
1446            os.chmod(tmp_path, 0o666 & ~umask)
1447            os.replace(tmp_path, filename)
1448        except Exception:
1449            try:
1450                os.unlink(tmp_path)
1451            except OSError:
1452                pass
1453            raise
1454        print(f"[PAI Config] Saved {len(config_dict)} variables \u2192 {filename}")
1455
1456    def load_config(self, filename, module_name=None, module_type=None, skip_keys=None):
1457        """Load PAIConfig state from a JSON file produced by :py:meth:`save_config`.
1458
1459        If *module_name* is ``None`` (default) every serialisable variable in
1460        the file is restored on this instance.
1461
1462        If *module_name* is given the lookup priority is:
1463          1. ``module_settings[module_name]`` (exact name / id match)
1464          2. ``module_settings[module_type]``  (type-level fallback)
1465          3. No-op — the defaults already set by ``__init__`` are kept.
1466
1467        Parameters
1468        ----------
1469        filename : str
1470            Path to the JSON file to read.
1471        module_name : str, optional
1472            Display name (id) of the module whose custom settings should be loaded.
1473        module_type : str, optional
1474            Short class name of the module type, used as a fallback key.
1475
1476        skip_keys : set, optional
1477            Variable names to ignore while loading (manual overrides).
1478
1479        Returns
1480        -------
1481        None
1482            This function does not return a value.
1483        """
1484        import json
1485
1486        with open(filename, "r") as f:
1487            config_dict = json.load(f)
1488
1489        if module_name is not None:
1490            # ── Per-module load ──────────────────────────────────────────────
1491            module_settings = config_dict.get("module_settings", {})
1492            # Priority: exact name → type fallback → no-op
1493            if module_name in module_settings:
1494                custom = module_settings[module_name]
1495                resolved_key = module_name
1496            elif module_type and module_type in module_settings:
1497                custom = module_settings[module_type]
1498                resolved_key = module_type
1499            else:
1500                # No custom settings for this module or type — keep defaults.
1501                return
1502            loaded = 0
1503            skipped = 0
1504            for key, json_val in custom.items():
1505                if key not in PAIConfig._CUSTOMIZABLE:
1506                    continue
1507                type_hint = PAIConfig._TYPES.get(key)
1508                private_key = f"_{key}"
1509                # Write directly to __dict__ so we bypass any setter guards and also
1510                # correctly handle vars that are not pre-initialised on per-module
1511                # configs (e.g. output_dimensions, which only lives inside the
1512                # ``if not module_name:`` block of __init__).
1513                try:
1514                    self.__dict__[private_key] = (
1515                        _deserialize_pai_value(json_val, type_hint)
1516                        if type_hint is not None
1517                        else json_val
1518                    )
1519                    loaded += 1
1520                except Exception as exc:
1521                    print(
1522                        f"[PAI Config] Warning: could not load '{key}' for '{resolved_key}': {exc}"
1523                    )
1524                    skipped += 1
1525            print(
1526                f"[PAI Config] Loaded {loaded} custom vars for '{resolved_key}' from {filename}"
1527                + (f" ({skipped} skipped)" if skipped else "")
1528            )
1529            return
1530
1531        # ── Global load: every variable in the JSON ──────────────────────────
1532        skip_keys = set(skip_keys or [])
1533        loaded = 0
1534        skipped = 0
1535        self.__dict__["_loading_config_values"] = True
1536        try:
1537            for key, json_val in config_dict.items():
1538                # Skip internal bookkeeping and Studio-only metadata keys.
1539                # 'module_name' and 'module_type' must never overwrite the
1540                # instance's _module_name/_module_type (they are internal only).
1541                if key in (
1542                    "config_file",
1543                    "module_settings",
1544                    "module_name",
1545                    "module_type",
1546                ) or key.startswith("_"):
1547                    continue
1548                if key in skip_keys:
1549                    continue
1550                type_hint = PAIConfig._TYPES.get(key)
1551                private_key = f"_{key}"
1552                if hasattr(self, private_key):
1553                    try:
1554                        setattr(
1555                            self,
1556                            private_key,
1557                            (
1558                                _deserialize_pai_value(json_val, type_hint)
1559                                if type_hint is not None
1560                                else json_val
1561                            ),
1562                        )
1563                        loaded += 1
1564                    except Exception as exc:
1565                        print(f"[PAI Config] Warning: could not load '{key}': {exc}")
1566                        skipped += 1
1567                elif hasattr(self, key) and not callable(getattr(self, key, None)):
1568                    try:
1569                        setattr(self, key, json_val)
1570                        loaded += 1
1571                    except Exception:
1572                        skipped += 1
1573            try:
1574                self._block_rules = _normalize_block_rules(self._block_rules)
1575            except ValueError as exc:
1576                print(f"[PAI Config] Warning: ignoring invalid block_rules: {exc}")
1577                self._block_rules = []
1578        finally:
1579            self.__dict__["_loading_config_values"] = False
1580
1581        print(
1582            f"[PAI Config] Loaded {loaded} variables from {filename}"
1583            + (f" ({skipped} skipped)" if skipped else "")
1584        )
1585
1586    def get_run_config_path(self):
1587        """Get the run-specific config path derived from save_name.
1588
1589        Returns
1590        -------
1591        str or None
1592            Path to the run config file, or None when save_name is unset.
1593        """
1594        import os
1595
1596        save_name = self.__dict__.get("_save_name")
1597        if not save_name:
1598            return None
1599        return os.path.join(os.getcwd(), save_name, f"{save_name}_config.json")
1600
1601    def sync_config_sources(self):
1602        """Load config values from configured local JSON sources.
1603
1604        Load order (later sources override earlier ones):
1605        1. run config derived from save_name (if present)
1606        2. config_file pointer (if set)
1607
1608        An explicitly supplied config_file is therefore the highest-priority
1609        file source: it wins over a stale run config left in the save_name
1610        folder by a previous run. With no config_file set, the run config is
1611        the only file source.
1612
1613        Keys set manually in this process are never overwritten.
1614        """
1615        import os
1616
1617        if self.__dict__.get("_module_name") is not None:
1618            return
1619
1620        # Selection lists a script has set are merged with the JSON instead of
1621        # being skipped, so CLI additions survive; see _merge_python_supplied.
1622        merge_keys = [
1623            k for k in SELECTION_LIST_VARS if self.get_python_supplied(k) is not None
1624        ]
1625        skip_keys = set(self.__dict__.get("_manually_set_keys", set())) - set(
1626            merge_keys
1627        )
1628        config_file = self.__dict__.get("_config_file")
1629        run_config = self.get_run_config_path()
1630
1631        if run_config and os.path.exists(run_config):
1632            self.load_config(run_config, skip_keys=skip_keys)
1633        if config_file and os.path.exists(config_file):
1634            self.load_config(config_file, skip_keys=skip_keys)
1635        self._merge_python_supplied(merge_keys)
1636
1637    def get_python_supplied(self, var_name):
1638        """Items a user script supplied for a selection list, or None.
1639
1640        Class lists (``modules_to_perforate`` / ``modules_to_track``) count
1641        toward the matching ``module_names_*`` list via their short names.
1642        Returns None when the script never set or appended to the list.
1643        """
1644        supplied = self.__dict__.get("_python_supplied", {})
1645        items = None
1646        if var_name in supplied:
1647            items = list(supplied[var_name])
1648        for class_var, names_var in _CLASS_LIST_FEEDS.items():
1649            if names_var == var_name and class_var in supplied:
1650                names = [
1651                    c.__name__ for c in supplied[class_var] if isinstance(c, type)
1652                ]
1653                items = (items or []) + [n for n in names if n not in (items or [])]
1654        return items
1655
1656    def _merge_python_supplied(self, merge_keys):
1657        """Union script-supplied items with JSON values; script wins conflicts."""
1658        for key in merge_keys:
1659            supplied = self.get_python_supplied(key)
1660            current = list(self.__dict__.get(f"_{key}", []))
1661            if key == "block_rules":
1662                # A script rule replaces a JSON rule for the same block and path.
1663                supplied_keys = {(r["block"], r["path"]) for r in supplied}
1664                current = [
1665                    r for r in current if (r["block"], r["path"]) not in supplied_keys
1666                ]
1667            merged = supplied + [v for v in current if v not in supplied]
1668            setattr(self, f"_{key}", merged)
1669        sup_fuse = self.get_python_supplied("modules_to_fuse") or []
1670        if sup_fuse:
1671            sup_ids = {module_id for pair in sup_fuse for module_id in pair}
1672            self._modules_to_fuse = [
1673                pair
1674                for pair in self._modules_to_fuse
1675                if pair in sup_fuse or not (set(pair) & sup_ids)
1676            ]
1677        for perforate_var, track_var in _SELECTION_CONFLICT_PAIRS:
1678            sup_p = self.get_python_supplied(perforate_var) or []
1679            sup_t = self.get_python_supplied(track_var) or []
1680            if not sup_p and not sup_t:
1681                continue
1682            cur_p = list(self.__dict__.get(f"_{perforate_var}", []))
1683            cur_t = list(self.__dict__.get(f"_{track_var}", []))
1684            setattr(
1685                self,
1686                f"_{perforate_var}",
1687                [v for v in cur_p if v in sup_p or v not in sup_t],
1688            )
1689            setattr(
1690                self,
1691                f"_{track_var}",
1692                [v for v in cur_t if v in sup_t or v not in sup_p],
1693            )
1694
1695    def persist_config_outputs(self, overwrite_config_file=False):
1696        """Persist current config state to local JSON outputs.
1697
1698        Parameters
1699        ----------
1700        overwrite_config_file : bool
1701            When True, also writes the configured config_file pointer target.
1702        """
1703        if self.__dict__.get("_module_name") is not None:
1704            return
1705
1706        run_config = self.get_run_config_path()
1707        if run_config:
1708            self.save_config(run_config, include_confirmed=False)
1709
1710        if overwrite_config_file:
1711            config_file = self.__dict__.get("_config_file")
1712            if config_file:
1713                self.save_config(config_file)
1714
1715
1716class PAISequential(nn.Sequential):
1717    """Sequential module wrapper for PAI.
1718
1719    This wrapper takes an array of layers and creates a sequential container
1720    that is compatible with PAI's dendrite addition system. It should be used
1721    for normalization layers and can be used for final output layers.
1722
1723    Parameters
1724    ----------
1725    layer_array : list
1726        List of PyTorch nn.Module objects to be executed sequentially.
1727
1728    Examples
1729    --------
1730    >>> layers = [nn.Linear(2 * hidden_dim, seq_width),
1731    ...           nn.LayerNorm(seq_width)]
1732    >>> sequential_block = PAISequential(layers)
1733
1734    Notes
1735    -----
1736    This should be used for:
1737        - All normalization layers (LayerNorm, BatchNorm, etc.)
1738    This can be used for:
1739        - Final output layer and softmax combinations
1740    """
1741
1742    def __init__(self, layer_array):
1743        """Initialize PAISequential with a list of layers.
1744
1745        Parameters
1746        ----------
1747        layer_array : list
1748            List of PyTorch modules to execute in sequence.
1749        """
1750        super(PAISequential, self).__init__()
1751        self.model = nn.Sequential(*layer_array)
1752
1753    def forward(self, *args, **kwargs):
1754        """Forward pass through the sequential layers.
1755
1756        Parameters
1757        ----------
1758        *args
1759            Positional arguments passed to the first layer.
1760        **kwargs
1761            Keyword arguments passed to the layers.
1762
1763        Returns
1764        -------
1765        torch.Tensor
1766            Output from the final layer in the sequence.
1767        """
1768        return self.model(*args, **kwargs)
1769
1770
1771class FusedNormIdentity(nn.Module):
1772    """Stand-in left where a norm used to be after it is fused into its head.
1773
1774    The norm now runs inside the head's PAISequential, so this module just
1775    returns its input and the user's forward() can stay exactly as written.
1776    On the first training forward it checks that its input is the head's
1777    output; if the user's forward does anything between the head and the norm,
1778    fusing would silently change the result, so it raises instead.
1779
1780    Parameters
1781    ----------
1782    head_id : str
1783        Module id of the head, used in the error message.
1784    norm_id : str
1785        Module id of the original norm, used in the error message.
1786    """
1787
1788    def __init__(self, head_id, norm_id):
1789        super(FusedNormIdentity, self).__init__()
1790        self.head_id = head_id
1791        self.norm_id = norm_id
1792        # Plain dict so the head output is not registered as a submodule.
1793        self._check = {"head_output": None, "done": False}
1794
1795    def record_head_output(self, output):
1796        """Remember the head's output so forward can compare against it."""
1797        if not self._check["done"]:
1798            self._check["head_output"] = output
1799
1800    def forward(self, x):
1801        if not self._check["done"]:
1802            if x is not self._check["head_output"]:
1803                raise RuntimeError(
1804                    "Cannot fuse %s with %s: the input to %s is not the output "
1805                    "of %s. Something in forward() runs between them, so fusing "
1806                    "would change the result. Remove this pair from the fused "
1807                    "modules."
1808                    % (
1809                        self.head_id,
1810                        self.norm_id,
1811                        self.norm_id,
1812                        self.head_id,
1813                    )
1814                )
1815            self._check["done"] = True
1816            self._check["head_output"] = None
1817        return x
1818
1819
1820### Global objects and variables
1821
1822### Global Modules
1823pc = PAIConfig()
1824"""Global PAIConfig instance.
1825
1826This is the primary configuration object used throughout the PAI system.
1827Modify settings through this instance to control PAI behavior.
1828"""
1829
1830"""Pointer to the PAI Tracker.
1831
1832This will be populated with the PAI Tracker instance which handles
1833the addition of dendrites during training. Initially an empty list.
1834"""
1835pai_tracker = []
1836
1837pai_scaler = None
1838
1839# This will be set to true if perforated backpropagation is available
1840# Do not just set this to True without the library and a license, it will cause errors
1841try:
1842    import perforatedbp.globals_pbp as perforatedbp_globals
1843
1844    print("Building dendrites with Perforated Backpropagation")
1845
1846    # Set these as defaults without marking them as manually set so that a
1847    # config JSON with perforated_backpropagation=false can still override them.
1848    pc.__dict__["_loading_config_values"] = True
1849    pc.set_perforated_backpropagation(True)
1850    # This is default to True for open source version
1851    # But defaults to False for perforated backpropagation
1852    pc.set_no_extra_n_modes(False)
1853    pc.__dict__["_loading_config_values"] = False
1854
1855    # Loop through the vars module's attributes and add them dynamically
1856    for var_name in dir(perforatedbp_globals):
1857        if not var_name.startswith("_"):
1858            add_pai_config_var_functions(
1859                pc, var_name, getattr(perforatedbp_globals, var_name)
1860            )
1861
1862    # Merge PBP type hints into PAIConfig._TYPES so load_config can correctly
1863    # round-trip all perforatedbp variables from JSON.
1864    if hasattr(perforatedbp_globals, "_TYPES"):
1865        PAIConfig._TYPES.update(perforatedbp_globals._TYPES)
1866
1867except ImportError:
1868    print("Building dendrites without Perforated Backpropagation")
SELECTION_LIST_VARS = ('module_ids_to_perforate', 'module_ids_to_track', 'module_names_to_perforate', 'module_names_to_track', 'parameter_ids_to_track', 'block_rules', 'modules_to_fuse')
BLOCK_RULE_MODES = ('perforated', 'tracked')
def add_pai_config_var_functions(obj, var_name, initial_value, list_type=False):
158def add_pai_config_var_functions(obj, var_name, initial_value, list_type=False):
159    """Dynamically add a property with getter and setter to an object.
160
161    This function adds a private variable along with getter and setter methods
162    to a given object instance. Used for integrating initial and Perforated
163    Backpropagation variables into the PAIConfig class.
164
165    Parameters
166    ----------
167    obj : object
168        The object to which the property will be added.
169    var_name : str
170        Name of the variable/property to create.
171    initial_value : any
172        Initial value for the property.
173
174    Returns
175    -------
176    None
177
178    Notes
179    -----
180    Creates three attributes on obj:
181        - _{var_name}: private storage
182        - get_{var_name}: getter method
183        - set_{var_name}: setter method
184    """
185    private_name = f"_{var_name}"
186
187    # Add the private variable to the instance
188    setattr(obj, private_name, initial_value)
189
190    # Define getter and setter and appender
191
192    def getter_val(self):
193        """Get the current value of the property.
194
195        If the property a individual value but is set to be a list,
196        return the element corresponding to the
197        current number of dendrites added. Otherwise, return the value directly.
198
199        Returns
200        -------
201        Any
202            Current value of the property.
203
204        Notes:
205        -----
206        Many variables have optimal settings that must change as dendrites are added
207        this enables those values to be dynamically set very easily.
208
209        Parameters
210        ----------
211        None
212
213        """
214        global pai_tracker
215        if type(getattr(self, private_name)) is list:
216            return getattr(self, private_name)[
217                min(
218                    len(getattr(self, private_name)) - 1,
219                    pai_tracker.member_vars["num_dendrites_added"],
220                )
221            ]
222        return getattr(self, private_name)
223
224    def getter_list(self):
225        """Get the underlying list value for this dynamic config property.
226
227        Returns
228        -------
229        list
230            Raw list stored for this property.
231
232        Parameters
233        ----------
234        None
235
236        """
237        return getattr(self, private_name)
238
239    def setter(self, value):
240        """Set the value of the property.
241
242        Parameters
243        ----------
244        value : Any
245            New value to assign to the dynamic configuration field.
246
247        Returns
248        -------
249        None
250            Updates the property and may trigger configuration auto-save.
251        """
252        if (
253            self.__dict__.get("_module_name") is not None
254            or self.__dict__.get("_module_type") is not None
255        ):
256            raise RuntimeError(
257                "Setting custom module config values should only be done "
258                "from JSON config files or the GUI"
259            )
260        if var_name in (
261            "module_ids_to_track",
262            "module_ids_to_perforate",
263            "parameter_ids_to_track",
264        ):
265            for module_id in value:
266                _validate_module_id(module_id)
267        if var_name == "block_rules":
268            value = _normalize_block_rules(value)
269        if var_name == "modules_to_fuse":
270            value = _normalize_fuse_pairs(value)
271        if var_name == "perforated_backpropagation" and value:
272            try:
273                import perforatedbp  # noqa: F401
274            except ImportError:
275                raise ValueError(
276                    "perforated_backpropagation=True requires the 'perforatedbp' package, "
277                    "which is not installed. Install it separately or leave "
278                    "perforated_backpropagation=False (the default)."
279                )
280        setattr(self, private_name, value)
281        if isinstance(value, (list, tuple)):
282            _record_python_supplied(self, var_name, value, replace=True)
283        if not self.__dict__.get("_loading_config_values", False):
284            self.__dict__.setdefault("_manually_set_keys", set()).add(var_name)
285            if var_name == "config_file":
286                self.sync_config_sources()
287
288    def appender(self, value):
289        """Append a value to the property if it is a list.
290
291        Parameters
292        ----------
293        value : Any
294            Value or values to append to the underlying list property.
295
296        Returns
297        -------
298        None
299            Appends items in-place and prints the resulting list value.
300        """
301        if isinstance(getattr(self, private_name), list):
302            if var_name in (
303                "module_ids_to_track",
304                "module_ids_to_perforate",
305                "parameter_ids_to_track",
306            ):
307                for module_id in value:
308                    _validate_module_id(module_id)
309            if var_name == "block_rules":
310                new_rules = _normalize_block_rules(value)
311                new_keys = {(r["block"], r["path"]) for r in new_rules}
312                kept = [
313                    rule
314                    for rule in getattr(self, private_name)
315                    if (rule["block"], rule["path"]) not in new_keys
316                ]
317                setattr(self, private_name, kept + new_rules)
318                _record_python_supplied(self, var_name, new_rules, replace=False)
319            else:
320                setattr(self, private_name, getattr(self, private_name) + value)
321                _record_python_supplied(self, var_name, value, replace=False)
322            if var_name == "modules_to_fuse":
323                value = _normalize_fuse_pairs(value)
324            setattr(self, private_name, getattr(self, private_name) + value)
325            _record_python_supplied(self, var_name, value, replace=False)
326            if not self.__dict__.get("_loading_config_values", False):
327                self.__dict__.setdefault("_manually_set_keys", set()).add(var_name)
328            print(
329                'New list value of "{}": {}'.format(
330                    private_name, getattr(self, private_name)
331                )
332            )
333        else:
334            raise TypeError(f"Cannot append to non-list attribute '{var_name}'")
335
336    # Attach methods to the instance
337    if list_type:
338        setattr(obj, f"get_{var_name}", getter_list.__get__(obj))
339    else:
340        setattr(obj, f"get_{var_name}", getter_val.__get__(obj))
341    setattr(obj, f"set_{var_name}", setter.__get__(obj))
342    setattr(obj, f"append_{var_name}", appender.__get__(obj))

Dynamically add a property with getter and setter to an object.

This function adds a private variable along with getter and setter methods to a given object instance. Used for integrating initial and Perforated Backpropagation variables into the PAIConfig class.

Parameters
  • obj (object): The object to which the property will be added.
  • var_name (str): Name of the variable/property to create.
  • initial_value (any): Initial value for the property.
Returns
  • None
Notes

Creates three attributes on obj: - _{var_name}: private storage - get_{var_name}: getter method - set_{var_name}: setter method

def callable_config_repr(val):
384def callable_config_repr(val):
385    """Canonical string form of a callable config value (e.g. pai_forward_function).
386
387    Shared by config serialisation and the interactive configuration display so
388    the two never disagree on how a callable is named.
389    """
390    name = getattr(val, "__name__", None) or getattr(val, "__qualname__", None)
391    mod = getattr(val, "__module__", None)
392    if name and mod:
393        if name in _TORCH_ACTIVATION_SHORTHAND:
394            return f"torch.{name}"
395        return f"{mod}.{name}"
396    if name:
397        return str(name)
398    return repr(val)

Canonical string form of a callable config value (e.g. pai_forward_function).

Shared by config serialisation and the interactive configuration display so the two never disagree on how a callable is named.

class PAIConfig:
 443class PAIConfig:
 444    """Configuration class for PAI settings.
 445
 446    This class manages all configuration parameters for the Perforated AI system,
 447    including device settings, dendrite behavior, module conversion rules,
 448    training parameters, and debugging options.
 449
 450    Attributes
 451    ----------
 452    use_cuda : bool
 453        Whether CUDA is available and should be used.
 454    device : torch.device
 455        The device to use for computation (CPU, CUDA, etc.).
 456    save_name : str
 457        Name used for saving models (should not be set manually).
 458    debugging_output_dimensions : int
 459        Debug level for input dimension checking.
 460    confirm_correct_sizes : bool
 461        Whether to verify tensor sizes during execution.
 462    unwrapped_modules_confirmed : bool
 463        Confirmation flag for using unwrapped modules.
 464    weight_decay_accepted : bool
 465        Confirmation flag for accepting weight decay.
 466    checked_skipped_modules : bool
 467        Whether skipped modules have been verified.
 468    verbose : bool
 469        Enable verbose logging output.
 470    extra_verbose : bool
 471        Enable extra verbose logging output.
 472    silent : bool
 473        Suppress all PAI print statements.
 474    save_old_graph_scores : bool
 475        Whether to save historical graph scores.
 476    testing_dendrite_capacity : bool
 477        Enable dendrite capacity testing mode.
 478    using_safe_tensors : bool
 479        Use safe tensors file format for saving.
 480    global_candidates : int
 481        Number of global candidate dendrites.
 482    drawing_pai : bool
 483        Enable PAI visualization graphs.
 484    test_saves : bool
 485        Save intermediary test models.
 486    pai_saves : bool
 487        Save PAI-specific format models.
 488    output_dimensions : list
 489        Format specification for input tensor dimensions.
 490    improvement_threshold : float
 491        Relative improvement threshold for validation scores.
 492    improvement_threshold_raw : float
 493        Absolute improvement threshold for validation scores.
 494    candidate_weight_initialization_multiplier : float
 495        Multiplier for random dendrite weight initialization.
 496    DOING_SWITCH_EVERY_TIME : int
 497        Constant for switch mode: add dendrites every epoch.
 498    DOING_HISTORY : int
 499        Constant for switch mode: add dendrites based on validation history.
 500    n_epochs_to_switch : int
 501        Number of epochs without improvement before switching.
 502    history_lookback : int
 503        Number of epochs to average for validation history.
 504    initial_history_after_switches : int
 505        Epochs to wait after adding dendrites before beggining checks.
 506    DOING_FIXED_SWITCH : int
 507        Constant for switch mode: add dendrites at fixed intervals.
 508    n_fixed_switch_num : int
 509        Number of epochs between fixed switches (neuron mode).
 510    first_fixed_switch_num : int
 511        Number of epochs before first switch (for pretraining).
 512    DOING_NO_SWITCH : int
 513        Constant for switch mode: never add dendrites.
 514    switch_mode : int
 515        Current switch mode setting.
 516    reset_best_score_on_switch : bool
 517        Whether to reset best score when adding dendrites.
 518    learn_dendrites_live : bool
 519        Enable live dendrite learning (advanced feature).
 520    no_extra_n_modes : bool
 521        Disable extra neuron modes (advanced feature).
 522    d_type : torch.dtype
 523        Data type for dendrite weights.
 524    retain_all_dendrites : bool
 525        Keep dendrites even if they don't improve performance.
 526    find_best_lr : bool
 527        Automatically sweep learning rates when adding dendrites.
 528    dont_give_up_unless_learning_rate_lowered : bool
 529        Ensure search lowers learning rate at least once.
 530    lr_binary_search_max_depth : int
 531        Maximum binary search depth for LR sweep (default 4).
 532    dendrite_lr_multiplier : float
 533        Learning rate multiplier for dendrite weights and their output weights.
 534    max_dendrite_tries : int
 535        Maximum attempts to add dendrites with random initializations.
 536    max_dendrites : int
 537        Maximum total number of dendrites to add.
 538    PARAM_VALS_BY_TOTAL_EPOCH : int
 539        Constant: scheduler params tracked by total epochs.
 540    PARAM_VALS_BY_UPDATE_EPOCH : int
 541        Constant: scheduler params reset at each switch.
 542    PARAM_VALS_BY_NEURON_EPOCH_START : int
 543        Constant: scheduler params reset for neuron starts only.
 544    param_vals_setting : int
 545        Current parameter tracking mode.
 546    pai_forward_function : callable
 547        Activation function used for dendrites.
 548    modules_to_perforate : list
 549        Module types to convert to PAI modules for perforation.
 550    module_names_to_perforate : list
 551        Module names to convert to PAI modules for perforation.
 552    module_ids_to_perforate : list
 553        Specific module IDs to convert to PAI modules for perforation.
 554    block_rules : list
 555        {"block", "path", "mode"} entries applied inside every instance of a
 556        block class (a module type with children that occurs more than once).
 557    modules_to_fuse : list
 558        Pairs of [head_id, norm_id] module ids to fuse into one block.
 559    modules_to_track : list
 560        Module types to track but not convert.
 561    module_names_to_track : list
 562        Module names to track but not convert.
 563    module_ids_to_track : list
 564        Specific module IDs to track but not convert.
 565    modules_to_replace : list
 566        Module types to replace before conversion.
 567    replacement_modules : list
 568        Replacement modules for modules_to_replace.
 569    modules_with_processing : list
 570        Module types requiring custom processing.
 571    modules_processing_classes : list
 572        Processing classes for modules_with_processing.
 573    module_names_with_processing : list
 574        Module names requiring custom processing.
 575    module_by_name_processing_classes : list
 576        Processing classes for module_names_with_processing.
 577    module_names_to_not_save : list
 578        Module names to exclude from saving.
 579    perforated_backpropagation : bool
 580        Whether Perforated Backpropagation is enabled.
 581    """
 582
 583    # Explicit type map for every config variable — used by load_config to coerce JSON values.
 584    # [type] means "list whose elements are class/type objects" (need dotted-name resolution).
 585    _TYPES: dict = {
 586        **{
 587            k: bool
 588            for k in (
 589                "use_cuda",
 590                "confirm_correct_sizes",
 591                "unwrapped_modules_confirmed",
 592                "weight_decay_accepted",
 593                "checked_skipped_modules",
 594                "configuration_confirmed",
 595                "verbose",
 596                "extra_verbose",
 597                "silent",
 598                "save_old_graph_scores",
 599                "testing_dendrite_capacity",
 600                "strict_loading",
 601                "using_safe_tensors",
 602                "drawing_pai",
 603                "drawing_extra_graphs",
 604                "test_saves",
 605                "pai_saves",
 606                "reset_best_score_on_switch",
 607                "learn_dendrites_live",
 608                "no_extra_n_modes",
 609                "retain_all_dendrites",
 610                "find_best_lr",
 611                "dont_give_up_unless_learning_rate_lowered",
 612                "maximizing_score",
 613                "candidate_weight_init_by_main",
 614                "perforated_backpropagation",
 615                "weight_tying_experimental",
 616                "dashboard_events_enabled",
 617                "dashboard_debug",
 618            )
 619        },
 620        **{
 621            k: int
 622            for k in (
 623                "debugging_output_dimensions",
 624                "global_candidates",
 625                "n_epochs_to_switch",
 626                "history_lookback",
 627                "initial_history_after_switches",
 628                "n_fixed_switch_num",
 629                "first_fixed_switch_num",
 630                "switch_mode",
 631                "max_dendrite_tries",
 632                "max_dendrites",
 633                "param_vals_setting",
 634            )
 635        },
 636        **{
 637            k: float
 638            for k in (
 639                "improvement_threshold_raw",
 640                "candidate_weight_initialization_multiplier",
 641                "dendrite_lr_multiplier",
 642            )
 643        },
 644        **{
 645            k: str
 646            for k in (
 647                "save_name",
 648                "library_validation_score",
 649                "dashboard_url",
 650            )
 651        },
 652        "device": torch.device,
 653        "d_type": torch.dtype,
 654        "pai_forward_function": callable,
 655        **{
 656            k: list
 657            for k in (
 658                "output_dimensions",
 659                "improvement_threshold",
 660                "module_names_to_perforate",
 661                "module_ids_to_perforate",
 662                "module_names_to_track",
 663                "module_ids_to_track",
 664                "parameter_ids_to_track",
 665                "block_rules",
 666                "modules_to_fuse",
 667                "module_names_with_processing",
 668                "module_names_to_not_save",
 669                "library_extra_scores",
 670                "library_extra_scores_without_graphing",
 671            )
 672        },
 673        **{
 674            k: [type]
 675            for k in (
 676                "modules_to_perforate",
 677                "modules_to_track",
 678                "modules_to_replace",
 679                "replacement_modules",
 680                "modules_with_processing",
 681                "modules_processing_classes",
 682                "module_by_name_processing_classes",
 683            )
 684        },
 685    }
 686
 687    # Subset of _TYPES: variables that can be overridden on a per-module basis
 688    # via the Studio.  These are set outside the ``if not module_name:`` block
 689    # in :py:meth:`__init__`, so they are meaningful when constructing a
 690    # module-specific PAIConfig instance.
 691    _CUSTOMIZABLE: dict = {
 692        #"verbose": bool,
 693        #"extra_verbose": bool,
 694        #"silent": bool,
 695        #"global_candidates": int,
 696        "output_dimensions": list,
 697        #"candidate_weight_initialization_multiplier": float,
 698        #"candidate_weight_init_by_main": bool,
 699        #"retain_all_dendrites": bool,
 700        #"max_dendrites": int,
 701        #"pai_forward_function": callable,
 702    }
 703
 704    def __getstate__(self):
 705        """Tell pickle what to save when this object is serialized (e.g. torch.save).
 706
 707        The get_*/set_*/append_* methods attached to each PAIConfig instance are
 708        locally-defined closures and cannot be pickled.  Only the underlying data
 709        values (stored as _<name> in __dict__) need to be saved; __setstate__
 710        will recreate the methods by calling __init__ on load.
 711        """
 712        import types
 713
 714        # Walk every attribute on this instance and keep only the plain data values.
 715        # Bound methods (the get_*/set_*/append_* closures) are skipped because
 716        # they cannot be serialized by pickle.
 717        pickle_safe_state = {}
 718        for attr_name, attr_value in self.__dict__.items():
 719            if not isinstance(attr_value, types.MethodType):
 720                pickle_safe_state[attr_name] = attr_value
 721
 722        return pickle_safe_state
 723
 724    def __setstate__(self, saved_state):
 725        """Restore this object from a pickled state (e.g. torch.load).
 726
 727        Calls __init__ to rebuild all the get_*/set_*/append_* methods, then
 728        overlays the saved data values on top so all settings are preserved.
 729        """
 730        # Grab the identity fields needed to reconstruct the right flavor of config
 731        # (global config vs. per-module config).
 732        saved_module_name = saved_state.get("_module_name")
 733        saved_module_type = saved_state.get("_module_type")
 734
 735        # Re-run __init__ so all the get_*/set_*/append_* methods exist again.
 736        # This also sets default values for every variable, which we overwrite below.
 737        self.__init__(module_name=saved_module_name, module_type=saved_module_type)
 738
 739        # Overwrite the defaults with the actual saved values.
 740        # Only restore private data attributes (prefixed with _); skip the identity
 741        # fields we already handled above, and skip _config_file for now so that
 742        # the setter calls above do not trigger auto-save during the restore.
 743        skip_on_first_pass = {"_module_name", "_module_type", "_config_file"}
 744        for attr_name, attr_value in saved_state.items():
 745            if attr_name.startswith("_") and attr_name not in skip_on_first_pass:
 746                self.__dict__[attr_name] = attr_value
 747
 748        # Restore the config file path last.  Auto-save is driven by _config_file
 749        # being set, so we only put it back after all values are already in place.
 750        if saved_state.get("_config_file"):
 751            self.__dict__["_config_file"] = saved_state["_config_file"]
 752
 753    def __getattr__(self, name):
 754        """Handle missing attributes gracefully, especially for PB variables.
 755
 756        Parameters
 757        ----------
 758        name : str
 759            The name of the attribute being accessed.
 760
 761        Returns
 762        -------
 763        None or raises AttributeError
 764            Returns None for missing set_ methods, raises AttributeError otherwise.
 765        """
 766        if name.startswith("set_"):
 767            print(f"Variable '{name[4:]}' does not exist.  Ignoring set attempt.")
 768            return lambda x: None
 769        if name.startswith("append_"):
 770            print(
 771                f"List Variable '{name[7:]}' does not exist.  Ignoring append attempt."
 772            )
 773            return lambda x: None
 774        if name.startswith("get_") and self.__dict__.get("_module_name") is not None:
 775            # Module-specific config: check for a per-module override stored directly in
 776            # __dict__ (written by load_config when custom JSON data was found for this
 777            # module).  This covers CUSTOMIZABLE vars that are not initialised for
 778            # per-module configs (e.g. output_dimensions, which lives inside the
 779            # ``if not module_name:`` block).
 780            private_key = f"_{name[4:]}"
 781            if private_key in self.__dict__:
 782                stored = self.__dict__[private_key]
 783                return lambda: stored
 784            # Fall back to the global pc instance for vars not set on this instance.
 785            global_getter = getattr(pc, name, None)
 786            if global_getter is not None:
 787                return global_getter
 788        raise AttributeError(
 789            f"'{self.__class__.__name__}' object has no attribute '{name}'"
 790        )
 791
 792    def __init__(self, module_name=None, module_type=None):
 793        """Initialize PAIConfig with default settings.
 794
 795        module_name=None means this is the main global config.
 796        If module_name is set this is a per-module config that loads
 797        custom settings from module_settings[module_name] (by id) or
 798        module_settings[module_type] (by type) in the JSON file.
 799        """
 800        # Must be first: prevents __getattr__ from firing for _config_file
 801        # during construction (before add_pai_config_var_functions sets it).
 802        # Also disables auto-save in setters until the end of __init__.
 803        self.__dict__["_config_file"] = None
 804        self.__dict__["_manually_set_keys"] = set()
 805        self.__dict__["_loading_config_values"] = False
 806        # None = global config; any string = per-module config
 807        self.__dict__["_module_name"] = module_name
 808        # Short class name of the wrapped module (e.g. 'Conv2d'), used as
 809        # a fallback lookup key when the specific name has no saved settings.
 810        self.__dict__["_module_type"] = module_type
 811
 812        if not module_name:
 813            ### Global Constants
 814            # Device configuration
 815            self.use_cuda = torch.cuda.is_available()
 816            add_pai_config_var_functions(self, "use_cuda", self.use_cuda)
 817            self.device = torch.device("cuda" if self.use_cuda else "cpu")
 818            add_pai_config_var_functions(self, "device", self.device)
 819
 820            self.save_name = ""
 821            add_pai_config_var_functions(self, "save_name", self.save_name)
 822
 823            self.config_file = None
 824            add_pai_config_var_functions(self, "config_file", self.config_file)
 825
 826            # Debug settings
 827            self.debugging_output_dimensions = 0
 828            add_pai_config_var_functions(
 829                self, "debugging_output_dimensions", self.debugging_output_dimensions
 830            )
 831            # Debugging input tensor sizes.
 832            # This will slow things down very slightly and is not necessary but can help
 833            # catch when dimensions were not filled in correctly.
 834            self.confirm_correct_sizes = False
 835            add_pai_config_var_functions(
 836                self, "confirm_correct_sizes", self.confirm_correct_sizes
 837            )
 838
 839            # Confirmation flags for non-recommended options
 840            self.unwrapped_modules_confirmed = False
 841            add_pai_config_var_functions(
 842                self, "unwrapped_modules_confirmed", self.unwrapped_modules_confirmed
 843            )
 844            # We used to be worried this caused problems, but it is now accepted.
 845            # Leaving code in case future changes require revisiting this decision.
 846            self.weight_decay_accepted = True
 847            add_pai_config_var_functions(
 848                self, "weight_decay_accepted", self.weight_decay_accepted
 849            )
 850            self.checked_skipped_modules = False
 851            add_pai_config_var_functions(
 852                self, "checked_skipped_modules", self.checked_skipped_modules
 853            )
 854            self.configuration_confirmed = False
 855            add_pai_config_var_functions(
 856                self, "configuration_confirmed", self.configuration_confirmed
 857            )
 858            # Analysis settings
 859            self.save_old_graph_scores = True
 860            add_pai_config_var_functions(
 861                self, "save_old_graph_scores", self.save_old_graph_scores
 862            )
 863            # Testing settings
 864            self.testing_dendrite_capacity = True
 865            add_pai_config_var_functions(
 866                self, "testing_dendrite_capacity", self.testing_dendrite_capacity
 867            )
 868
 869            # File format settings
 870            self.using_safe_tensors = True
 871            add_pai_config_var_functions(
 872                self, "using_safe_tensors", self.using_safe_tensors
 873            )
 874
 875            # Checkpoint loading settings
 876            # Whether to use strict=True when loading state_dict
 877            # Set to False if loading old checkpoints that are missing new fields
 878            self.strict_loading = True
 879            add_pai_config_var_functions(
 880                self, "strict_loading", self.strict_loading
 881            )
 882
 883            # Graph and visualization settings
 884            # A graph setting which can be set to false if you want to do your own
 885            # training visualizations
 886            self.drawing_pai = True
 887            add_pai_config_var_functions(self, "drawing_pai", self.drawing_pai)
 888
 889            # Drawing extra graphs beyond the standard ones.
 890            self.drawing_extra_graphs = True
 891            add_pai_config_var_functions(
 892                self, "drawing_extra_graphs", self.drawing_extra_graphs
 893            )
 894
 895            # Saving test intermediary models, good for experimentation, bad for memory
 896            self.test_saves = True
 897            add_pai_config_var_functions(self, "test_saves", self.test_saves)
 898            # To be filled in later. pai_saves will remove some extra scaffolding for
 899            # slight memory and speed improvements
 900            self.pai_saves = False
 901            add_pai_config_var_functions(self, "pai_saves", self.pai_saves)
 902            # Improvement thresholds
 903            # Percentage improvement increase needed to call a new best validation score
 904            self.improvement_threshold = [0.001, 0.0001, 0.0]
 905            add_pai_config_var_functions(
 906                self, "improvement_threshold", self.improvement_threshold
 907            )
 908
 909            # Raw increase needed
 910            self.improvement_threshold_raw = 1e-5
 911            add_pai_config_var_functions(
 912                self, "improvement_threshold_raw", self.improvement_threshold_raw
 913            )
 914            # SWITCH MODE SETTINGS
 915
 916            # Add dendrites every time to debug implementation
 917            self.DOING_SWITCH_EVERY_TIME = 0
 918
 919            # Switch when validation hasn't improved over x epochs
 920            self.DOING_HISTORY = 1
 921            # Epochs to try before deciding to load previous best and add dendrites
 922            # Be sure this is higher than scheduler patience
 923            self.n_epochs_to_switch = 10
 924            add_pai_config_var_functions(
 925                self, "n_epochs_to_switch", self.n_epochs_to_switch
 926            )
 927            # Number to average validation scores over
 928            self.history_lookback = 1
 929            add_pai_config_var_functions(
 930                self, "history_lookback", self.history_lookback
 931            )
 932            # Amount of epochs to run after adding a new set of dendrites before checking
 933            # to add more
 934            self.initial_history_after_switches = 0
 935            add_pai_config_var_functions(
 936                self,
 937                "initial_history_after_switches",
 938                self.initial_history_after_switches,
 939            )
 940
 941            # Switch after a fixed number of epochs
 942            self.DOING_FIXED_SWITCH = 2
 943            # Number of epochs to complete before switching (neuron mode)
 944            self.n_fixed_switch_num = 250
 945            add_pai_config_var_functions(
 946                self, "n_fixed_switch_num", self.n_fixed_switch_num
 947            )
 948            # An additional flag if you want your first switch to occur later than all the
 949            # rest for initial pretraining.  This is a new minimum, if its lower than
 950            # the above it will be ignored.
 951            self.first_fixed_switch_num = -1
 952            add_pai_config_var_functions(
 953                self, "first_fixed_switch_num", self.first_fixed_switch_num
 954            )
 955
 956            # A setting to not add dendrites and just do regular training
 957            # Warning, this will also never trigger training_complete
 958            self.DOING_NO_SWITCH = 3
 959
 960            # Default switch mode
 961            self.switch_mode = self.DOING_HISTORY
 962            add_pai_config_var_functions(self, "switch_mode", self.switch_mode)
 963
 964            # Reset settings
 965            # Resets score on switch
 966            # This can be useful if you need many epochs to catch up to the best score
 967            # from the previous version after adding dendrites
 968            self.reset_best_score_on_switch = True
 969            add_pai_config_var_functions(
 970                self, "reset_best_score_on_switch", self.reset_best_score_on_switch
 971            )
 972
 973            # Advanced settings
 974            # Not used in open source implementation, leave as default
 975            self.learn_dendrites_live = False
 976            add_pai_config_var_functions(
 977                self, "learn_dendrites_live", self.learn_dendrites_live
 978            )
 979            self.no_extra_n_modes = True
 980            add_pai_config_var_functions(
 981                self, "no_extra_n_modes", self.no_extra_n_modes
 982            )
 983
 984            # Data type for new modules and dendrite to dendrite / dendrite to neuron
 985            # weights
 986            self.d_type = torch.float
 987            add_pai_config_var_functions(self, "d_type", self.d_type)
 988
 989            # Learning rate management
 990            # A setting to automatically sweep over previously used learning rates when
 991            # adding new dendrites
 992            # Sometimes it's best to go back to initial LR, but often its best to start
 993            # at a lower LR
 994            self.find_best_lr = True
 995            add_pai_config_var_functions(self, "find_best_lr", self.find_best_lr)
 996            # Enforces the above even if the previous epoch didn't lower the learning rate
 997            self.dont_give_up_unless_learning_rate_lowered = True
 998            add_pai_config_var_functions(
 999                self,
1000                "dont_give_up_unless_learning_rate_lowered",
1001                self.dont_give_up_unless_learning_rate_lowered,
1002            )
1003            # Maximum depth for binary search LR sweep. Limits total tests to O(log N).
1004            self.lr_binary_search_max_depth = 4
1005            add_pai_config_var_functions(
1006                self,
1007                "lr_binary_search_max_depth",
1008                self.lr_binary_search_max_depth,
1009            )
1010            # Dendrites and their output weights train at the optimizer's learning rate
1011            # times this. Their output weights start at 0, so with a small learning
1012            # rate, such as when fine-tuning, new dendrites barely change the network.
1013            # Applied by setup_optimizer, or by passing the optimizer's params
1014            # through UPA.get_parameter_groups when using set_optimizer_instance.
1015            self.dendrite_lr_multiplier = 1.0
1016            add_pai_config_var_functions(
1017                self, "dendrite_lr_multiplier", self.dendrite_lr_multiplier
1018            )
1019            # Whether a higher validation score is better (True) or lower is better (False).
1020            self.maximizing_score = True
1021            add_pai_config_var_functions(
1022                self, "maximizing_score", self.maximizing_score
1023            )
1024
1025            # Dendrite attempt settings
1026            # Set to 1 if you want to quit as soon as one dendrite fails
1027            # Higher values will try new random dendrite weights this many times before
1028            # accepting that more dendrites don't improve
1029            self.max_dendrite_tries = 2
1030            add_pai_config_var_functions(
1031                self, "max_dendrite_tries", self.max_dendrite_tries
1032            )
1033
1034            # Scheduler parameter settings
1035            # Have learning rate params be by total epoch
1036            self.PARAM_VALS_BY_TOTAL_EPOCH = 0
1037            # Reset the params at every switch
1038            self.PARAM_VALS_BY_UPDATE_EPOCH = 1
1039            # Reset params for dendrite starts but not for normal restarts
1040            # Not used for open source version
1041            self.PARAM_VALS_BY_NEURON_EPOCH_START = 2
1042            # Default setting
1043            self.param_vals_setting = self.PARAM_VALS_BY_UPDATE_EPOCH
1044            add_pai_config_var_functions(
1045                self, "param_vals_setting", self.param_vals_setting
1046            )
1047            # Lists for module types and names to add dendrites to
1048            # For these lists no specifier means type, name is module name
1049            # and ids is the individual modules id, eg. model.conv2
1050            self.modules_to_perforate = []
1051            add_pai_config_var_functions(
1052                self, "modules_to_perforate", self.modules_to_perforate, list_type=True
1053            )
1054            self.module_names_to_perforate = [
1055                "PAISequential",
1056                "Conv1d",
1057                "Conv2d",
1058                "Conv3d",
1059                "Linear",
1060            ]
1061            add_pai_config_var_functions(
1062                self,
1063                "module_names_to_perforate",
1064                self.module_names_to_perforate,
1065                list_type=True,
1066            )
1067            self.module_ids_to_perforate = []
1068            add_pai_config_var_functions(
1069                self,
1070                "module_ids_to_perforate",
1071                self.module_ids_to_perforate,
1072                list_type=True,
1073            )
1074
1075            # All modules should either be perforated or tracked to ensure all modules
1076            # are accounted for
1077            self.modules_to_track = []
1078            add_pai_config_var_functions(
1079                self, "modules_to_track", self.modules_to_track, list_type=True
1080            )
1081            self.module_names_to_track = []
1082            add_pai_config_var_functions(
1083                self,
1084                "module_names_to_track",
1085                self.module_names_to_track,
1086                list_type=True,
1087            )
1088            # IDs are for if you want to pass only a single module by its assigned ID rather than the module type by name
1089            self.module_ids_to_track = []
1090            add_pai_config_var_functions(
1091                self, "module_ids_to_track", self.module_ids_to_track, list_type=True
1092            )
1093
1094            # Block rules: {"block": class name, "path": relative path, "mode"}
1095            # entries applied inside every instance of that block class, e.g.
1096            # {"block": "BasicBlock", "path": ".conv2", "mode": "perforated"}.
1097            # A mode set directly by id wins; a block rule wins over a type rule.
1098            self.block_rules = []
1099            add_pai_config_var_functions(
1100                self, "block_rules", self.block_rules, list_type=True
1101            )
1102            # Pairs of [head_id, norm_id] to fuse so the norm is trained with the
1103            # head it follows; applied by fuse_modules before conversion
1104            self.modules_to_fuse = []
1105            add_pai_config_var_functions(
1106                self, "modules_to_fuse", self.modules_to_fuse, list_type=True
1107            )
1108
1109            # Parameter IDs to track as neuron parameters without recursive behavior
1110            # (e.g., [".my_custom_parameter"]).
1111            self.parameter_ids_to_track = []
1112            add_pai_config_var_functions(
1113                self,
1114                "parameter_ids_to_track",
1115                self.parameter_ids_to_track,
1116                list_type=True,
1117            )
1118
1119            # Replacement modules happen before the conversion,
1120            # so replaced modules will then also be run through the conversion steps
1121            # These are for modules that need to be replaced before addition of dendrites
1122            # See the resnet example in models_perforatedai
1123            self.modules_to_replace = []
1124            add_pai_config_var_functions(
1125                self, "modules_to_replace", self.modules_to_replace, list_type=True
1126            )
1127            # Modules to replace the above modules with
1128            self.replacement_modules = []
1129            add_pai_config_var_functions(
1130                self, "replacement_modules", self.replacement_modules, list_type=True
1131            )
1132
1133            # Dendrites default to modules which are one tensor input and one tensor
1134            # output in forward()
1135            # Other modules require to be labeled as modules with processing and assigned
1136            # processing classes
1137            # This can be done by module type or module name see customization.md in API
1138            # for example
1139            self.modules_with_processing = []
1140            add_pai_config_var_functions(
1141                self,
1142                "modules_with_processing",
1143                self.modules_with_processing,
1144                list_type=True,
1145            )
1146            self.modules_processing_classes = []
1147            add_pai_config_var_functions(
1148                self,
1149                "modules_processing_classes",
1150                self.modules_processing_classes,
1151                list_type=True,
1152            )
1153            self.module_names_with_processing = []
1154            add_pai_config_var_functions(
1155                self,
1156                "module_names_with_processing",
1157                self.module_names_with_processing,
1158                list_type=True,
1159            )
1160            self.module_by_name_processing_classes = []
1161            add_pai_config_var_functions(
1162                self,
1163                "module_by_name_processing_classes",
1164                self.module_by_name_processing_classes,
1165                list_type=True,
1166            )
1167
1168            # Similarly here as above. Some huggingface models have multiple pointers to
1169            # the same modules which cause problems
1170            # If you want to only save one of the multiple pointers you can set which ones
1171            # not to save here
1172            self.module_names_to_not_save = [".base_model"]
1173            add_pai_config_var_functions(
1174                self,
1175                "module_names_to_not_save",
1176                self.module_names_to_not_save,
1177                list_type=True,
1178            )
1179
1180            # Perforated Backpropagation settings
1181            self.perforated_backpropagation = False
1182            add_pai_config_var_functions(
1183                self, "perforated_backpropagation", self.perforated_backpropagation
1184            )
1185
1186            # This is specifically a workaround for weight tying
1187            # Not to be used for a duplicate pointer that isn't actually run twice
1188            self.weight_tying_experimental = False
1189            add_pai_config_var_functions(
1190                self, "weight_tying_experimental", self.weight_tying_experimental
1191            )
1192
1193            # Dashboard event streaming settings
1194            self.dashboard_events_enabled = False
1195            add_pai_config_var_functions(
1196                self, "dashboard_events_enabled", self.dashboard_events_enabled
1197            )
1198            self.dashboard_url = "http://localhost:3002"
1199            add_pai_config_var_functions(
1200                self, "dashboard_url", self.dashboard_url
1201            )
1202            self.dashboard_debug = False
1203            add_pai_config_var_functions(
1204                self, "dashboard_debug", self.dashboard_debug
1205            )
1206
1207            # These are settings where libraries must be doing the scoring adding to
1208            # message from your main script what metric to use
1209            self.library_validation_score = ""
1210            add_pai_config_var_functions(
1211                self, "library_validation_score", self.library_validation_score
1212            )
1213            self.library_extra_scores = []
1214            add_pai_config_var_functions(
1215                self,
1216                "library_extra_scores",
1217                self.library_extra_scores,
1218                list_type=True,
1219            )
1220            self.library_extra_scores_without_graphing = []
1221            add_pai_config_var_functions(
1222                self,
1223                "library_extra_scores_without_graphing",
1224                self.library_extra_scores_without_graphing,
1225                list_type=True,
1226            )
1227
1228            # Input dimensions needs to be set every time. It is set to what format of
1229            # planes you are expecting.
1230            # Neuron index should be set to 0, variable indexes should be set to -1.
1231            # For example, if your format is [batchsize, nodes, x, y]
1232            # output_dimensions is [-1, 0, -1, -1].
1233            # if your format is, [batchsize, time index, nodes] output_dimensions is
1234            # [-1, -1, 0]
1235            # TODO consider changing from a single set here to a set for each type of module
1236            # TODO should not set this value directly, should be a setter like set_this_output_dimensions in PAINeuronModule
1237            self.output_dimensions = [REDUCE_AXIS, NODE_AXIS, NOT_REDUCE_OR_NODE_AXIS, NOT_REDUCE_OR_NODE_AXIS]
1238            add_pai_config_var_functions(
1239                self, "output_dimensions", self.output_dimensions, list_type=True
1240            )
1241        # Verbosity settings
1242        self.verbose = False
1243        add_pai_config_var_functions(self, "verbose", self.verbose)
1244        self.extra_verbose = False
1245        add_pai_config_var_functions(self, "extra_verbose", self.extra_verbose)
1246        # Suppress all PAI prints
1247        self.silent = False
1248        add_pai_config_var_functions(self, "silent", self.silent)
1249
1250        # Epoch-boundary callback lists.  Each holds callables invoked with the tracker as
1251        # their sole argument at the corresponding boundary (see start_epoch / stop_epoch).
1252        # Declared inline (no redundant plain attribute) so only the private
1253        # _epoch_*_callbacks storage exists; save_config skips those two names so the lists
1254        # never round-trip through JSON.
1255        add_pai_config_var_functions(self, "epoch_start_callbacks", [], list_type=True)
1256        add_pai_config_var_functions(self, "epoch_stop_callbacks", [], list_type=True)
1257
1258        # In place for future implementation options of adding multiple candidate
1259        # dendrites together
1260        self.global_candidates = 1
1261        add_pai_config_var_functions(self, "global_candidates", self.global_candidates)
1262
1263        # Weight initialization settings
1264        # Multiplier when randomizing dendrite weights
1265        self.candidate_weight_initialization_multiplier = 0.01
1266        add_pai_config_var_functions(
1267            self,
1268            "candidate_weight_initialization_multiplier",
1269            self.candidate_weight_initialization_multiplier,
1270        )
1271        # Multiplier when randomizing dendrite weights
1272        self.candidate_weight_init_by_main = False
1273        add_pai_config_var_functions(
1274            self,
1275            "candidate_weight_init_by_main",
1276            self.candidate_weight_init_by_main,
1277        )
1278
1279        # Dendrite retention settings
1280        # A setting to keep dendrites even if they do not improve scores
1281        self.retain_all_dendrites = False
1282        add_pai_config_var_functions(
1283            self, "retain_all_dendrites", self.retain_all_dendrites
1284        )
1285
1286        # Max dendrites to add even if they do continue improving scores
1287        self.max_dendrites = 100
1288        add_pai_config_var_functions(self, "max_dendrites", self.max_dendrites)
1289
1290        # Activation function settings
1291        # The activation function to use for dendrites
1292        self.pai_forward_function = torch.sigmoid
1293        add_pai_config_var_functions(
1294            self, "pai_forward_function", self.pai_forward_function
1295        )
1296
1297        # Apply per-module overrides after defaults are defined so loaded values
1298        # win over initializer defaults.
1299        if module_name is not None:
1300            import os
1301
1302            global_pc = globals().get("pc")
1303            source_paths = []
1304            if global_pc is not None:
1305                config_file = getattr(global_pc, "__dict__", {}).get("_config_file")
1306                run_config = global_pc.get_run_config_path()
1307                if config_file:
1308                    source_paths.append(config_file)
1309                if run_config:
1310                    source_paths.append(run_config)
1311
1312            for source_path in source_paths:
1313                if source_path and os.path.exists(source_path):
1314                    self.load_config(
1315                        source_path,
1316                        module_name=module_name,
1317                        module_type=module_type,
1318                    )
1319                    break
1320
1321        # ------------------------------------------------------------------
1322        # Config file will be set when save_name is assigned (in perforate_model)
1323        # ------------------------------------------------------------------
1324        # _config_file stays None until save_name is set to a non-empty value
1325
1326    # ------------------------------------------------------------------
1327
1328    def save_config(self, filename, include_confirmed=True):
1329        """Save the current PAIConfig state to a JSON file.
1330
1331        Parameters
1332        ----------
1333        filename : str
1334            Destination file path (created or overwritten).
1335        include_confirmed : bool
1336            When False, ``configuration_confirmed`` is left out of the file.
1337            Run configs use this so a one-off confirmation is not replayed on
1338            later runs.
1339
1340        Notes
1341        -----
1342        Values that are not natively JSON-serialisable (torch.device,
1343        torch.dtype, nn.Module subclasses, callables) are stored as their
1344        dotted-string representations so they can be round-tripped by
1345        :py:meth:`load_config`.
1346
1347        Returns
1348        -------
1349        None
1350            This function does not return a value.
1351        """
1352        import json
1353
1354        config_dict = {}
1355
1356        # Private-storage vars added by add_pai_config_var_functions
1357        # e.g. self._module_ids_to_perforate → key 'module_ids_to_perforate'
1358        for key, val in sorted(self.__dict__.items()):
1359            if not (key.startswith("_") and not key.startswith("__")):
1360                continue
1361            # Skip internal bookkeeping keys that must not round-trip through JSON
1362            if key in (
1363                "_config_file",
1364                "_module_name",
1365                "_module_type",
1366                "_epoch_start_callbacks",
1367                "_epoch_stop_callbacks",
1368                "_manually_set_keys",
1369                "_loading_config_values",
1370                "_auto_persist_config",
1371                "_python_supplied",
1372                "_tui_editing",
1373            ):
1374                continue
1375            clean_key = key[1:]
1376            if clean_key == "configuration_confirmed" and not include_confirmed:
1377                continue
1378            # Keep callable config fields (e.g. pai_forward_function) but skip
1379            # any other private callable values that are not typed as callable.
1380            if callable(val) and PAIConfig._TYPES.get(clean_key) is not callable:
1381                continue
1382            try:
1383                config_dict[clean_key] = _serialize_pai_value(val)
1384            except Exception:
1385                config_dict[clean_key] = str(val)
1386
1387        # Plain constants (DOING_*, PARAM_VALS_BY_*, etc.)
1388        for key, val in self.__dict__.items():
1389            if key.startswith("_") or callable(val):
1390                continue
1391            if key not in config_dict:
1392                # Keep config_file runtime-only: do not persist pointer paths in
1393                # saved JSON snapshots.
1394                if key == "config_file":
1395                    continue
1396                if key == "configuration_confirmed" and not include_confirmed:
1397                    continue
1398                try:
1399                    config_dict[key] = _serialize_pai_value(val)
1400                except Exception:
1401                    config_dict[key] = str(val)
1402
1403        # Merge short class names from modules_to_perforate into module_names_to_perforate
1404        # so the UI (and JS) only needs to check one array.
1405        type_short_names = [
1406            cls.__name__
1407            for cls in self.__dict__.get("_modules_to_perforate", [])
1408            if isinstance(cls, type)
1409        ]
1410        existing = config_dict.get("module_names_to_perforate", [])
1411        config_dict["module_names_to_perforate"] = existing + [
1412            n for n in type_short_names if n not in existing
1413        ]
1414
1415        # Preserve any per-module settings written by the Studio frontend.
1416        _existing_ms: dict = {}
1417        try:
1418            with open(filename, "r") as _f:
1419                _existing_ms = json.load(_f).get("module_settings", {})
1420        except Exception:
1421            pass
1422        config_dict["module_settings"] = _existing_ms
1423
1424        # Publish customizable field type names so the Studio frontend can
1425        # render appropriate editors without needing to import the library.
1426        config_dict["_customizable_fields"] = {
1427            k: (v.__name__ if hasattr(v, "__name__") else str(v))
1428            for k, v in PAIConfig._CUSTOMIZABLE.items()
1429        }
1430
1431        # Ensure the directory exists before saving
1432        import os
1433        import tempfile
1434
1435        directory = os.path.dirname(filename)
1436        if directory:
1437            os.makedirs(directory, exist_ok=True)
1438
1439        # Atomic write: never leave the file truncated (DDP ranks may read concurrently).
1440        fd, tmp_path = tempfile.mkstemp(dir=directory or ".", suffix=".tmp")
1441        try:
1442            with os.fdopen(fd, "w") as f:
1443                json.dump(config_dict, f, indent=2)
1444            # mkstemp creates the file owner-only; match what a plain open() would give
1445            umask = os.umask(0)
1446            os.umask(umask)
1447            os.chmod(tmp_path, 0o666 & ~umask)
1448            os.replace(tmp_path, filename)
1449        except Exception:
1450            try:
1451                os.unlink(tmp_path)
1452            except OSError:
1453                pass
1454            raise
1455        print(f"[PAI Config] Saved {len(config_dict)} variables \u2192 {filename}")
1456
1457    def load_config(self, filename, module_name=None, module_type=None, skip_keys=None):
1458        """Load PAIConfig state from a JSON file produced by :py:meth:`save_config`.
1459
1460        If *module_name* is ``None`` (default) every serialisable variable in
1461        the file is restored on this instance.
1462
1463        If *module_name* is given the lookup priority is:
1464          1. ``module_settings[module_name]`` (exact name / id match)
1465          2. ``module_settings[module_type]``  (type-level fallback)
1466          3. No-op — the defaults already set by ``__init__`` are kept.
1467
1468        Parameters
1469        ----------
1470        filename : str
1471            Path to the JSON file to read.
1472        module_name : str, optional
1473            Display name (id) of the module whose custom settings should be loaded.
1474        module_type : str, optional
1475            Short class name of the module type, used as a fallback key.
1476
1477        skip_keys : set, optional
1478            Variable names to ignore while loading (manual overrides).
1479
1480        Returns
1481        -------
1482        None
1483            This function does not return a value.
1484        """
1485        import json
1486
1487        with open(filename, "r") as f:
1488            config_dict = json.load(f)
1489
1490        if module_name is not None:
1491            # ── Per-module load ──────────────────────────────────────────────
1492            module_settings = config_dict.get("module_settings", {})
1493            # Priority: exact name → type fallback → no-op
1494            if module_name in module_settings:
1495                custom = module_settings[module_name]
1496                resolved_key = module_name
1497            elif module_type and module_type in module_settings:
1498                custom = module_settings[module_type]
1499                resolved_key = module_type
1500            else:
1501                # No custom settings for this module or type — keep defaults.
1502                return
1503            loaded = 0
1504            skipped = 0
1505            for key, json_val in custom.items():
1506                if key not in PAIConfig._CUSTOMIZABLE:
1507                    continue
1508                type_hint = PAIConfig._TYPES.get(key)
1509                private_key = f"_{key}"
1510                # Write directly to __dict__ so we bypass any setter guards and also
1511                # correctly handle vars that are not pre-initialised on per-module
1512                # configs (e.g. output_dimensions, which only lives inside the
1513                # ``if not module_name:`` block of __init__).
1514                try:
1515                    self.__dict__[private_key] = (
1516                        _deserialize_pai_value(json_val, type_hint)
1517                        if type_hint is not None
1518                        else json_val
1519                    )
1520                    loaded += 1
1521                except Exception as exc:
1522                    print(
1523                        f"[PAI Config] Warning: could not load '{key}' for '{resolved_key}': {exc}"
1524                    )
1525                    skipped += 1
1526            print(
1527                f"[PAI Config] Loaded {loaded} custom vars for '{resolved_key}' from {filename}"
1528                + (f" ({skipped} skipped)" if skipped else "")
1529            )
1530            return
1531
1532        # ── Global load: every variable in the JSON ──────────────────────────
1533        skip_keys = set(skip_keys or [])
1534        loaded = 0
1535        skipped = 0
1536        self.__dict__["_loading_config_values"] = True
1537        try:
1538            for key, json_val in config_dict.items():
1539                # Skip internal bookkeeping and Studio-only metadata keys.
1540                # 'module_name' and 'module_type' must never overwrite the
1541                # instance's _module_name/_module_type (they are internal only).
1542                if key in (
1543                    "config_file",
1544                    "module_settings",
1545                    "module_name",
1546                    "module_type",
1547                ) or key.startswith("_"):
1548                    continue
1549                if key in skip_keys:
1550                    continue
1551                type_hint = PAIConfig._TYPES.get(key)
1552                private_key = f"_{key}"
1553                if hasattr(self, private_key):
1554                    try:
1555                        setattr(
1556                            self,
1557                            private_key,
1558                            (
1559                                _deserialize_pai_value(json_val, type_hint)
1560                                if type_hint is not None
1561                                else json_val
1562                            ),
1563                        )
1564                        loaded += 1
1565                    except Exception as exc:
1566                        print(f"[PAI Config] Warning: could not load '{key}': {exc}")
1567                        skipped += 1
1568                elif hasattr(self, key) and not callable(getattr(self, key, None)):
1569                    try:
1570                        setattr(self, key, json_val)
1571                        loaded += 1
1572                    except Exception:
1573                        skipped += 1
1574            try:
1575                self._block_rules = _normalize_block_rules(self._block_rules)
1576            except ValueError as exc:
1577                print(f"[PAI Config] Warning: ignoring invalid block_rules: {exc}")
1578                self._block_rules = []
1579        finally:
1580            self.__dict__["_loading_config_values"] = False
1581
1582        print(
1583            f"[PAI Config] Loaded {loaded} variables from {filename}"
1584            + (f" ({skipped} skipped)" if skipped else "")
1585        )
1586
1587    def get_run_config_path(self):
1588        """Get the run-specific config path derived from save_name.
1589
1590        Returns
1591        -------
1592        str or None
1593            Path to the run config file, or None when save_name is unset.
1594        """
1595        import os
1596
1597        save_name = self.__dict__.get("_save_name")
1598        if not save_name:
1599            return None
1600        return os.path.join(os.getcwd(), save_name, f"{save_name}_config.json")
1601
1602    def sync_config_sources(self):
1603        """Load config values from configured local JSON sources.
1604
1605        Load order (later sources override earlier ones):
1606        1. run config derived from save_name (if present)
1607        2. config_file pointer (if set)
1608
1609        An explicitly supplied config_file is therefore the highest-priority
1610        file source: it wins over a stale run config left in the save_name
1611        folder by a previous run. With no config_file set, the run config is
1612        the only file source.
1613
1614        Keys set manually in this process are never overwritten.
1615        """
1616        import os
1617
1618        if self.__dict__.get("_module_name") is not None:
1619            return
1620
1621        # Selection lists a script has set are merged with the JSON instead of
1622        # being skipped, so CLI additions survive; see _merge_python_supplied.
1623        merge_keys = [
1624            k for k in SELECTION_LIST_VARS if self.get_python_supplied(k) is not None
1625        ]
1626        skip_keys = set(self.__dict__.get("_manually_set_keys", set())) - set(
1627            merge_keys
1628        )
1629        config_file = self.__dict__.get("_config_file")
1630        run_config = self.get_run_config_path()
1631
1632        if run_config and os.path.exists(run_config):
1633            self.load_config(run_config, skip_keys=skip_keys)
1634        if config_file and os.path.exists(config_file):
1635            self.load_config(config_file, skip_keys=skip_keys)
1636        self._merge_python_supplied(merge_keys)
1637
1638    def get_python_supplied(self, var_name):
1639        """Items a user script supplied for a selection list, or None.
1640
1641        Class lists (``modules_to_perforate`` / ``modules_to_track``) count
1642        toward the matching ``module_names_*`` list via their short names.
1643        Returns None when the script never set or appended to the list.
1644        """
1645        supplied = self.__dict__.get("_python_supplied", {})
1646        items = None
1647        if var_name in supplied:
1648            items = list(supplied[var_name])
1649        for class_var, names_var in _CLASS_LIST_FEEDS.items():
1650            if names_var == var_name and class_var in supplied:
1651                names = [
1652                    c.__name__ for c in supplied[class_var] if isinstance(c, type)
1653                ]
1654                items = (items or []) + [n for n in names if n not in (items or [])]
1655        return items
1656
1657    def _merge_python_supplied(self, merge_keys):
1658        """Union script-supplied items with JSON values; script wins conflicts."""
1659        for key in merge_keys:
1660            supplied = self.get_python_supplied(key)
1661            current = list(self.__dict__.get(f"_{key}", []))
1662            if key == "block_rules":
1663                # A script rule replaces a JSON rule for the same block and path.
1664                supplied_keys = {(r["block"], r["path"]) for r in supplied}
1665                current = [
1666                    r for r in current if (r["block"], r["path"]) not in supplied_keys
1667                ]
1668            merged = supplied + [v for v in current if v not in supplied]
1669            setattr(self, f"_{key}", merged)
1670        sup_fuse = self.get_python_supplied("modules_to_fuse") or []
1671        if sup_fuse:
1672            sup_ids = {module_id for pair in sup_fuse for module_id in pair}
1673            self._modules_to_fuse = [
1674                pair
1675                for pair in self._modules_to_fuse
1676                if pair in sup_fuse or not (set(pair) & sup_ids)
1677            ]
1678        for perforate_var, track_var in _SELECTION_CONFLICT_PAIRS:
1679            sup_p = self.get_python_supplied(perforate_var) or []
1680            sup_t = self.get_python_supplied(track_var) or []
1681            if not sup_p and not sup_t:
1682                continue
1683            cur_p = list(self.__dict__.get(f"_{perforate_var}", []))
1684            cur_t = list(self.__dict__.get(f"_{track_var}", []))
1685            setattr(
1686                self,
1687                f"_{perforate_var}",
1688                [v for v in cur_p if v in sup_p or v not in sup_t],
1689            )
1690            setattr(
1691                self,
1692                f"_{track_var}",
1693                [v for v in cur_t if v in sup_t or v not in sup_p],
1694            )
1695
1696    def persist_config_outputs(self, overwrite_config_file=False):
1697        """Persist current config state to local JSON outputs.
1698
1699        Parameters
1700        ----------
1701        overwrite_config_file : bool
1702            When True, also writes the configured config_file pointer target.
1703        """
1704        if self.__dict__.get("_module_name") is not None:
1705            return
1706
1707        run_config = self.get_run_config_path()
1708        if run_config:
1709            self.save_config(run_config, include_confirmed=False)
1710
1711        if overwrite_config_file:
1712            config_file = self.__dict__.get("_config_file")
1713            if config_file:
1714                self.save_config(config_file)

Configuration class for PAI settings.

This class manages all configuration parameters for the Perforated AI system, including device settings, dendrite behavior, module conversion rules, training parameters, and debugging options.

Attributes
  • use_cuda (bool): Whether CUDA is available and should be used.
  • device (torch.device): The device to use for computation (CPU, CUDA, etc.).
  • save_name (str): Name used for saving models (should not be set manually).
  • debugging_output_dimensions (int): Debug level for input dimension checking.
  • confirm_correct_sizes (bool): Whether to verify tensor sizes during execution.
  • unwrapped_modules_confirmed (bool): Confirmation flag for using unwrapped modules.
  • weight_decay_accepted (bool): Confirmation flag for accepting weight decay.
  • checked_skipped_modules (bool): Whether skipped modules have been verified.
  • verbose (bool): Enable verbose logging output.
  • extra_verbose (bool): Enable extra verbose logging output.
  • silent (bool): Suppress all PAI print statements.
  • save_old_graph_scores (bool): Whether to save historical graph scores.
  • testing_dendrite_capacity (bool): Enable dendrite capacity testing mode.
  • using_safe_tensors (bool): Use safe tensors file format for saving.
  • global_candidates (int): Number of global candidate dendrites.
  • drawing_pai (bool): Enable PAI visualization graphs.
  • test_saves (bool): Save intermediary test models.
  • pai_saves (bool): Save PAI-specific format models.
  • output_dimensions (list): Format specification for input tensor dimensions.
  • improvement_threshold (float): Relative improvement threshold for validation scores.
  • improvement_threshold_raw (float): Absolute improvement threshold for validation scores.
  • candidate_weight_initialization_multiplier (float): Multiplier for random dendrite weight initialization.
  • DOING_SWITCH_EVERY_TIME (int): Constant for switch mode: add dendrites every epoch.
  • DOING_HISTORY (int): Constant for switch mode: add dendrites based on validation history.
  • n_epochs_to_switch (int): Number of epochs without improvement before switching.
  • history_lookback (int): Number of epochs to average for validation history.
  • initial_history_after_switches (int): Epochs to wait after adding dendrites before beggining checks.
  • DOING_FIXED_SWITCH (int): Constant for switch mode: add dendrites at fixed intervals.
  • n_fixed_switch_num (int): Number of epochs between fixed switches (neuron mode).
  • first_fixed_switch_num (int): Number of epochs before first switch (for pretraining).
  • DOING_NO_SWITCH (int): Constant for switch mode: never add dendrites.
  • switch_mode (int): Current switch mode setting.
  • reset_best_score_on_switch (bool): Whether to reset best score when adding dendrites.
  • learn_dendrites_live (bool): Enable live dendrite learning (advanced feature).
  • no_extra_n_modes (bool): Disable extra neuron modes (advanced feature).
  • d_type (torch.dtype): Data type for dendrite weights.
  • retain_all_dendrites (bool): Keep dendrites even if they don't improve performance.
  • find_best_lr (bool): Automatically sweep learning rates when adding dendrites.
  • dont_give_up_unless_learning_rate_lowered (bool): Ensure search lowers learning rate at least once.
  • lr_binary_search_max_depth (int): Maximum binary search depth for LR sweep (default 4).
  • dendrite_lr_multiplier (float): Learning rate multiplier for dendrite weights and their output weights.
  • max_dendrite_tries (int): Maximum attempts to add dendrites with random initializations.
  • max_dendrites (int): Maximum total number of dendrites to add.
  • PARAM_VALS_BY_TOTAL_EPOCH (int): Constant: scheduler params tracked by total epochs.
  • PARAM_VALS_BY_UPDATE_EPOCH (int): Constant: scheduler params reset at each switch.
  • PARAM_VALS_BY_NEURON_EPOCH_START (int): Constant: scheduler params reset for neuron starts only.
  • param_vals_setting (int): Current parameter tracking mode.
  • pai_forward_function (callable): Activation function used for dendrites.
  • modules_to_perforate (list): Module types to convert to PAI modules for perforation.
  • module_names_to_perforate (list): Module names to convert to PAI modules for perforation.
  • module_ids_to_perforate (list): Specific module IDs to convert to PAI modules for perforation.
  • block_rules (list): {"block", "path", "mode"} entries applied inside every instance of a block class (a module type with children that occurs more than once).
  • modules_to_fuse (list): Pairs of [head_id, norm_id] module ids to fuse into one block.
  • modules_to_track (list): Module types to track but not convert.
  • module_names_to_track (list): Module names to track but not convert.
  • module_ids_to_track (list): Specific module IDs to track but not convert.
  • modules_to_replace (list): Module types to replace before conversion.
  • replacement_modules (list): Replacement modules for modules_to_replace.
  • modules_with_processing (list): Module types requiring custom processing.
  • modules_processing_classes (list): Processing classes for modules_with_processing.
  • module_names_with_processing (list): Module names requiring custom processing.
  • module_by_name_processing_classes (list): Processing classes for module_names_with_processing.
  • module_names_to_not_save (list): Module names to exclude from saving.
  • perforated_backpropagation (bool): Whether Perforated Backpropagation is enabled.
PAIConfig(module_name=None, module_type=None)
 792    def __init__(self, module_name=None, module_type=None):
 793        """Initialize PAIConfig with default settings.
 794
 795        module_name=None means this is the main global config.
 796        If module_name is set this is a per-module config that loads
 797        custom settings from module_settings[module_name] (by id) or
 798        module_settings[module_type] (by type) in the JSON file.
 799        """
 800        # Must be first: prevents __getattr__ from firing for _config_file
 801        # during construction (before add_pai_config_var_functions sets it).
 802        # Also disables auto-save in setters until the end of __init__.
 803        self.__dict__["_config_file"] = None
 804        self.__dict__["_manually_set_keys"] = set()
 805        self.__dict__["_loading_config_values"] = False
 806        # None = global config; any string = per-module config
 807        self.__dict__["_module_name"] = module_name
 808        # Short class name of the wrapped module (e.g. 'Conv2d'), used as
 809        # a fallback lookup key when the specific name has no saved settings.
 810        self.__dict__["_module_type"] = module_type
 811
 812        if not module_name:
 813            ### Global Constants
 814            # Device configuration
 815            self.use_cuda = torch.cuda.is_available()
 816            add_pai_config_var_functions(self, "use_cuda", self.use_cuda)
 817            self.device = torch.device("cuda" if self.use_cuda else "cpu")
 818            add_pai_config_var_functions(self, "device", self.device)
 819
 820            self.save_name = ""
 821            add_pai_config_var_functions(self, "save_name", self.save_name)
 822
 823            self.config_file = None
 824            add_pai_config_var_functions(self, "config_file", self.config_file)
 825
 826            # Debug settings
 827            self.debugging_output_dimensions = 0
 828            add_pai_config_var_functions(
 829                self, "debugging_output_dimensions", self.debugging_output_dimensions
 830            )
 831            # Debugging input tensor sizes.
 832            # This will slow things down very slightly and is not necessary but can help
 833            # catch when dimensions were not filled in correctly.
 834            self.confirm_correct_sizes = False
 835            add_pai_config_var_functions(
 836                self, "confirm_correct_sizes", self.confirm_correct_sizes
 837            )
 838
 839            # Confirmation flags for non-recommended options
 840            self.unwrapped_modules_confirmed = False
 841            add_pai_config_var_functions(
 842                self, "unwrapped_modules_confirmed", self.unwrapped_modules_confirmed
 843            )
 844            # We used to be worried this caused problems, but it is now accepted.
 845            # Leaving code in case future changes require revisiting this decision.
 846            self.weight_decay_accepted = True
 847            add_pai_config_var_functions(
 848                self, "weight_decay_accepted", self.weight_decay_accepted
 849            )
 850            self.checked_skipped_modules = False
 851            add_pai_config_var_functions(
 852                self, "checked_skipped_modules", self.checked_skipped_modules
 853            )
 854            self.configuration_confirmed = False
 855            add_pai_config_var_functions(
 856                self, "configuration_confirmed", self.configuration_confirmed
 857            )
 858            # Analysis settings
 859            self.save_old_graph_scores = True
 860            add_pai_config_var_functions(
 861                self, "save_old_graph_scores", self.save_old_graph_scores
 862            )
 863            # Testing settings
 864            self.testing_dendrite_capacity = True
 865            add_pai_config_var_functions(
 866                self, "testing_dendrite_capacity", self.testing_dendrite_capacity
 867            )
 868
 869            # File format settings
 870            self.using_safe_tensors = True
 871            add_pai_config_var_functions(
 872                self, "using_safe_tensors", self.using_safe_tensors
 873            )
 874
 875            # Checkpoint loading settings
 876            # Whether to use strict=True when loading state_dict
 877            # Set to False if loading old checkpoints that are missing new fields
 878            self.strict_loading = True
 879            add_pai_config_var_functions(
 880                self, "strict_loading", self.strict_loading
 881            )
 882
 883            # Graph and visualization settings
 884            # A graph setting which can be set to false if you want to do your own
 885            # training visualizations
 886            self.drawing_pai = True
 887            add_pai_config_var_functions(self, "drawing_pai", self.drawing_pai)
 888
 889            # Drawing extra graphs beyond the standard ones.
 890            self.drawing_extra_graphs = True
 891            add_pai_config_var_functions(
 892                self, "drawing_extra_graphs", self.drawing_extra_graphs
 893            )
 894
 895            # Saving test intermediary models, good for experimentation, bad for memory
 896            self.test_saves = True
 897            add_pai_config_var_functions(self, "test_saves", self.test_saves)
 898            # To be filled in later. pai_saves will remove some extra scaffolding for
 899            # slight memory and speed improvements
 900            self.pai_saves = False
 901            add_pai_config_var_functions(self, "pai_saves", self.pai_saves)
 902            # Improvement thresholds
 903            # Percentage improvement increase needed to call a new best validation score
 904            self.improvement_threshold = [0.001, 0.0001, 0.0]
 905            add_pai_config_var_functions(
 906                self, "improvement_threshold", self.improvement_threshold
 907            )
 908
 909            # Raw increase needed
 910            self.improvement_threshold_raw = 1e-5
 911            add_pai_config_var_functions(
 912                self, "improvement_threshold_raw", self.improvement_threshold_raw
 913            )
 914            # SWITCH MODE SETTINGS
 915
 916            # Add dendrites every time to debug implementation
 917            self.DOING_SWITCH_EVERY_TIME = 0
 918
 919            # Switch when validation hasn't improved over x epochs
 920            self.DOING_HISTORY = 1
 921            # Epochs to try before deciding to load previous best and add dendrites
 922            # Be sure this is higher than scheduler patience
 923            self.n_epochs_to_switch = 10
 924            add_pai_config_var_functions(
 925                self, "n_epochs_to_switch", self.n_epochs_to_switch
 926            )
 927            # Number to average validation scores over
 928            self.history_lookback = 1
 929            add_pai_config_var_functions(
 930                self, "history_lookback", self.history_lookback
 931            )
 932            # Amount of epochs to run after adding a new set of dendrites before checking
 933            # to add more
 934            self.initial_history_after_switches = 0
 935            add_pai_config_var_functions(
 936                self,
 937                "initial_history_after_switches",
 938                self.initial_history_after_switches,
 939            )
 940
 941            # Switch after a fixed number of epochs
 942            self.DOING_FIXED_SWITCH = 2
 943            # Number of epochs to complete before switching (neuron mode)
 944            self.n_fixed_switch_num = 250
 945            add_pai_config_var_functions(
 946                self, "n_fixed_switch_num", self.n_fixed_switch_num
 947            )
 948            # An additional flag if you want your first switch to occur later than all the
 949            # rest for initial pretraining.  This is a new minimum, if its lower than
 950            # the above it will be ignored.
 951            self.first_fixed_switch_num = -1
 952            add_pai_config_var_functions(
 953                self, "first_fixed_switch_num", self.first_fixed_switch_num
 954            )
 955
 956            # A setting to not add dendrites and just do regular training
 957            # Warning, this will also never trigger training_complete
 958            self.DOING_NO_SWITCH = 3
 959
 960            # Default switch mode
 961            self.switch_mode = self.DOING_HISTORY
 962            add_pai_config_var_functions(self, "switch_mode", self.switch_mode)
 963
 964            # Reset settings
 965            # Resets score on switch
 966            # This can be useful if you need many epochs to catch up to the best score
 967            # from the previous version after adding dendrites
 968            self.reset_best_score_on_switch = True
 969            add_pai_config_var_functions(
 970                self, "reset_best_score_on_switch", self.reset_best_score_on_switch
 971            )
 972
 973            # Advanced settings
 974            # Not used in open source implementation, leave as default
 975            self.learn_dendrites_live = False
 976            add_pai_config_var_functions(
 977                self, "learn_dendrites_live", self.learn_dendrites_live
 978            )
 979            self.no_extra_n_modes = True
 980            add_pai_config_var_functions(
 981                self, "no_extra_n_modes", self.no_extra_n_modes
 982            )
 983
 984            # Data type for new modules and dendrite to dendrite / dendrite to neuron
 985            # weights
 986            self.d_type = torch.float
 987            add_pai_config_var_functions(self, "d_type", self.d_type)
 988
 989            # Learning rate management
 990            # A setting to automatically sweep over previously used learning rates when
 991            # adding new dendrites
 992            # Sometimes it's best to go back to initial LR, but often its best to start
 993            # at a lower LR
 994            self.find_best_lr = True
 995            add_pai_config_var_functions(self, "find_best_lr", self.find_best_lr)
 996            # Enforces the above even if the previous epoch didn't lower the learning rate
 997            self.dont_give_up_unless_learning_rate_lowered = True
 998            add_pai_config_var_functions(
 999                self,
1000                "dont_give_up_unless_learning_rate_lowered",
1001                self.dont_give_up_unless_learning_rate_lowered,
1002            )
1003            # Maximum depth for binary search LR sweep. Limits total tests to O(log N).
1004            self.lr_binary_search_max_depth = 4
1005            add_pai_config_var_functions(
1006                self,
1007                "lr_binary_search_max_depth",
1008                self.lr_binary_search_max_depth,
1009            )
1010            # Dendrites and their output weights train at the optimizer's learning rate
1011            # times this. Their output weights start at 0, so with a small learning
1012            # rate, such as when fine-tuning, new dendrites barely change the network.
1013            # Applied by setup_optimizer, or by passing the optimizer's params
1014            # through UPA.get_parameter_groups when using set_optimizer_instance.
1015            self.dendrite_lr_multiplier = 1.0
1016            add_pai_config_var_functions(
1017                self, "dendrite_lr_multiplier", self.dendrite_lr_multiplier
1018            )
1019            # Whether a higher validation score is better (True) or lower is better (False).
1020            self.maximizing_score = True
1021            add_pai_config_var_functions(
1022                self, "maximizing_score", self.maximizing_score
1023            )
1024
1025            # Dendrite attempt settings
1026            # Set to 1 if you want to quit as soon as one dendrite fails
1027            # Higher values will try new random dendrite weights this many times before
1028            # accepting that more dendrites don't improve
1029            self.max_dendrite_tries = 2
1030            add_pai_config_var_functions(
1031                self, "max_dendrite_tries", self.max_dendrite_tries
1032            )
1033
1034            # Scheduler parameter settings
1035            # Have learning rate params be by total epoch
1036            self.PARAM_VALS_BY_TOTAL_EPOCH = 0
1037            # Reset the params at every switch
1038            self.PARAM_VALS_BY_UPDATE_EPOCH = 1
1039            # Reset params for dendrite starts but not for normal restarts
1040            # Not used for open source version
1041            self.PARAM_VALS_BY_NEURON_EPOCH_START = 2
1042            # Default setting
1043            self.param_vals_setting = self.PARAM_VALS_BY_UPDATE_EPOCH
1044            add_pai_config_var_functions(
1045                self, "param_vals_setting", self.param_vals_setting
1046            )
1047            # Lists for module types and names to add dendrites to
1048            # For these lists no specifier means type, name is module name
1049            # and ids is the individual modules id, eg. model.conv2
1050            self.modules_to_perforate = []
1051            add_pai_config_var_functions(
1052                self, "modules_to_perforate", self.modules_to_perforate, list_type=True
1053            )
1054            self.module_names_to_perforate = [
1055                "PAISequential",
1056                "Conv1d",
1057                "Conv2d",
1058                "Conv3d",
1059                "Linear",
1060            ]
1061            add_pai_config_var_functions(
1062                self,
1063                "module_names_to_perforate",
1064                self.module_names_to_perforate,
1065                list_type=True,
1066            )
1067            self.module_ids_to_perforate = []
1068            add_pai_config_var_functions(
1069                self,
1070                "module_ids_to_perforate",
1071                self.module_ids_to_perforate,
1072                list_type=True,
1073            )
1074
1075            # All modules should either be perforated or tracked to ensure all modules
1076            # are accounted for
1077            self.modules_to_track = []
1078            add_pai_config_var_functions(
1079                self, "modules_to_track", self.modules_to_track, list_type=True
1080            )
1081            self.module_names_to_track = []
1082            add_pai_config_var_functions(
1083                self,
1084                "module_names_to_track",
1085                self.module_names_to_track,
1086                list_type=True,
1087            )
1088            # IDs are for if you want to pass only a single module by its assigned ID rather than the module type by name
1089            self.module_ids_to_track = []
1090            add_pai_config_var_functions(
1091                self, "module_ids_to_track", self.module_ids_to_track, list_type=True
1092            )
1093
1094            # Block rules: {"block": class name, "path": relative path, "mode"}
1095            # entries applied inside every instance of that block class, e.g.
1096            # {"block": "BasicBlock", "path": ".conv2", "mode": "perforated"}.
1097            # A mode set directly by id wins; a block rule wins over a type rule.
1098            self.block_rules = []
1099            add_pai_config_var_functions(
1100                self, "block_rules", self.block_rules, list_type=True
1101            )
1102            # Pairs of [head_id, norm_id] to fuse so the norm is trained with the
1103            # head it follows; applied by fuse_modules before conversion
1104            self.modules_to_fuse = []
1105            add_pai_config_var_functions(
1106                self, "modules_to_fuse", self.modules_to_fuse, list_type=True
1107            )
1108
1109            # Parameter IDs to track as neuron parameters without recursive behavior
1110            # (e.g., [".my_custom_parameter"]).
1111            self.parameter_ids_to_track = []
1112            add_pai_config_var_functions(
1113                self,
1114                "parameter_ids_to_track",
1115                self.parameter_ids_to_track,
1116                list_type=True,
1117            )
1118
1119            # Replacement modules happen before the conversion,
1120            # so replaced modules will then also be run through the conversion steps
1121            # These are for modules that need to be replaced before addition of dendrites
1122            # See the resnet example in models_perforatedai
1123            self.modules_to_replace = []
1124            add_pai_config_var_functions(
1125                self, "modules_to_replace", self.modules_to_replace, list_type=True
1126            )
1127            # Modules to replace the above modules with
1128            self.replacement_modules = []
1129            add_pai_config_var_functions(
1130                self, "replacement_modules", self.replacement_modules, list_type=True
1131            )
1132
1133            # Dendrites default to modules which are one tensor input and one tensor
1134            # output in forward()
1135            # Other modules require to be labeled as modules with processing and assigned
1136            # processing classes
1137            # This can be done by module type or module name see customization.md in API
1138            # for example
1139            self.modules_with_processing = []
1140            add_pai_config_var_functions(
1141                self,
1142                "modules_with_processing",
1143                self.modules_with_processing,
1144                list_type=True,
1145            )
1146            self.modules_processing_classes = []
1147            add_pai_config_var_functions(
1148                self,
1149                "modules_processing_classes",
1150                self.modules_processing_classes,
1151                list_type=True,
1152            )
1153            self.module_names_with_processing = []
1154            add_pai_config_var_functions(
1155                self,
1156                "module_names_with_processing",
1157                self.module_names_with_processing,
1158                list_type=True,
1159            )
1160            self.module_by_name_processing_classes = []
1161            add_pai_config_var_functions(
1162                self,
1163                "module_by_name_processing_classes",
1164                self.module_by_name_processing_classes,
1165                list_type=True,
1166            )
1167
1168            # Similarly here as above. Some huggingface models have multiple pointers to
1169            # the same modules which cause problems
1170            # If you want to only save one of the multiple pointers you can set which ones
1171            # not to save here
1172            self.module_names_to_not_save = [".base_model"]
1173            add_pai_config_var_functions(
1174                self,
1175                "module_names_to_not_save",
1176                self.module_names_to_not_save,
1177                list_type=True,
1178            )
1179
1180            # Perforated Backpropagation settings
1181            self.perforated_backpropagation = False
1182            add_pai_config_var_functions(
1183                self, "perforated_backpropagation", self.perforated_backpropagation
1184            )
1185
1186            # This is specifically a workaround for weight tying
1187            # Not to be used for a duplicate pointer that isn't actually run twice
1188            self.weight_tying_experimental = False
1189            add_pai_config_var_functions(
1190                self, "weight_tying_experimental", self.weight_tying_experimental
1191            )
1192
1193            # Dashboard event streaming settings
1194            self.dashboard_events_enabled = False
1195            add_pai_config_var_functions(
1196                self, "dashboard_events_enabled", self.dashboard_events_enabled
1197            )
1198            self.dashboard_url = "http://localhost:3002"
1199            add_pai_config_var_functions(
1200                self, "dashboard_url", self.dashboard_url
1201            )
1202            self.dashboard_debug = False
1203            add_pai_config_var_functions(
1204                self, "dashboard_debug", self.dashboard_debug
1205            )
1206
1207            # These are settings where libraries must be doing the scoring adding to
1208            # message from your main script what metric to use
1209            self.library_validation_score = ""
1210            add_pai_config_var_functions(
1211                self, "library_validation_score", self.library_validation_score
1212            )
1213            self.library_extra_scores = []
1214            add_pai_config_var_functions(
1215                self,
1216                "library_extra_scores",
1217                self.library_extra_scores,
1218                list_type=True,
1219            )
1220            self.library_extra_scores_without_graphing = []
1221            add_pai_config_var_functions(
1222                self,
1223                "library_extra_scores_without_graphing",
1224                self.library_extra_scores_without_graphing,
1225                list_type=True,
1226            )
1227
1228            # Input dimensions needs to be set every time. It is set to what format of
1229            # planes you are expecting.
1230            # Neuron index should be set to 0, variable indexes should be set to -1.
1231            # For example, if your format is [batchsize, nodes, x, y]
1232            # output_dimensions is [-1, 0, -1, -1].
1233            # if your format is, [batchsize, time index, nodes] output_dimensions is
1234            # [-1, -1, 0]
1235            # TODO consider changing from a single set here to a set for each type of module
1236            # TODO should not set this value directly, should be a setter like set_this_output_dimensions in PAINeuronModule
1237            self.output_dimensions = [REDUCE_AXIS, NODE_AXIS, NOT_REDUCE_OR_NODE_AXIS, NOT_REDUCE_OR_NODE_AXIS]
1238            add_pai_config_var_functions(
1239                self, "output_dimensions", self.output_dimensions, list_type=True
1240            )
1241        # Verbosity settings
1242        self.verbose = False
1243        add_pai_config_var_functions(self, "verbose", self.verbose)
1244        self.extra_verbose = False
1245        add_pai_config_var_functions(self, "extra_verbose", self.extra_verbose)
1246        # Suppress all PAI prints
1247        self.silent = False
1248        add_pai_config_var_functions(self, "silent", self.silent)
1249
1250        # Epoch-boundary callback lists.  Each holds callables invoked with the tracker as
1251        # their sole argument at the corresponding boundary (see start_epoch / stop_epoch).
1252        # Declared inline (no redundant plain attribute) so only the private
1253        # _epoch_*_callbacks storage exists; save_config skips those two names so the lists
1254        # never round-trip through JSON.
1255        add_pai_config_var_functions(self, "epoch_start_callbacks", [], list_type=True)
1256        add_pai_config_var_functions(self, "epoch_stop_callbacks", [], list_type=True)
1257
1258        # In place for future implementation options of adding multiple candidate
1259        # dendrites together
1260        self.global_candidates = 1
1261        add_pai_config_var_functions(self, "global_candidates", self.global_candidates)
1262
1263        # Weight initialization settings
1264        # Multiplier when randomizing dendrite weights
1265        self.candidate_weight_initialization_multiplier = 0.01
1266        add_pai_config_var_functions(
1267            self,
1268            "candidate_weight_initialization_multiplier",
1269            self.candidate_weight_initialization_multiplier,
1270        )
1271        # Multiplier when randomizing dendrite weights
1272        self.candidate_weight_init_by_main = False
1273        add_pai_config_var_functions(
1274            self,
1275            "candidate_weight_init_by_main",
1276            self.candidate_weight_init_by_main,
1277        )
1278
1279        # Dendrite retention settings
1280        # A setting to keep dendrites even if they do not improve scores
1281        self.retain_all_dendrites = False
1282        add_pai_config_var_functions(
1283            self, "retain_all_dendrites", self.retain_all_dendrites
1284        )
1285
1286        # Max dendrites to add even if they do continue improving scores
1287        self.max_dendrites = 100
1288        add_pai_config_var_functions(self, "max_dendrites", self.max_dendrites)
1289
1290        # Activation function settings
1291        # The activation function to use for dendrites
1292        self.pai_forward_function = torch.sigmoid
1293        add_pai_config_var_functions(
1294            self, "pai_forward_function", self.pai_forward_function
1295        )
1296
1297        # Apply per-module overrides after defaults are defined so loaded values
1298        # win over initializer defaults.
1299        if module_name is not None:
1300            import os
1301
1302            global_pc = globals().get("pc")
1303            source_paths = []
1304            if global_pc is not None:
1305                config_file = getattr(global_pc, "__dict__", {}).get("_config_file")
1306                run_config = global_pc.get_run_config_path()
1307                if config_file:
1308                    source_paths.append(config_file)
1309                if run_config:
1310                    source_paths.append(run_config)
1311
1312            for source_path in source_paths:
1313                if source_path and os.path.exists(source_path):
1314                    self.load_config(
1315                        source_path,
1316                        module_name=module_name,
1317                        module_type=module_type,
1318                    )
1319                    break
1320
1321        # ------------------------------------------------------------------
1322        # Config file will be set when save_name is assigned (in perforate_model)
1323        # ------------------------------------------------------------------
1324        # _config_file stays None until save_name is set to a non-empty value

Initialize PAIConfig with default settings.

module_name=None means this is the main global config. If module_name is set this is a per-module config that loads custom settings from module_settings[module_name] (by id) or module_settings[module_type] (by type) in the JSON file.

verbose
extra_verbose
silent
global_candidates
candidate_weight_initialization_multiplier
candidate_weight_init_by_main
retain_all_dendrites
max_dendrites
pai_forward_function
def save_config(self, filename, include_confirmed=True):
1328    def save_config(self, filename, include_confirmed=True):
1329        """Save the current PAIConfig state to a JSON file.
1330
1331        Parameters
1332        ----------
1333        filename : str
1334            Destination file path (created or overwritten).
1335        include_confirmed : bool
1336            When False, ``configuration_confirmed`` is left out of the file.
1337            Run configs use this so a one-off confirmation is not replayed on
1338            later runs.
1339
1340        Notes
1341        -----
1342        Values that are not natively JSON-serialisable (torch.device,
1343        torch.dtype, nn.Module subclasses, callables) are stored as their
1344        dotted-string representations so they can be round-tripped by
1345        :py:meth:`load_config`.
1346
1347        Returns
1348        -------
1349        None
1350            This function does not return a value.
1351        """
1352        import json
1353
1354        config_dict = {}
1355
1356        # Private-storage vars added by add_pai_config_var_functions
1357        # e.g. self._module_ids_to_perforate → key 'module_ids_to_perforate'
1358        for key, val in sorted(self.__dict__.items()):
1359            if not (key.startswith("_") and not key.startswith("__")):
1360                continue
1361            # Skip internal bookkeeping keys that must not round-trip through JSON
1362            if key in (
1363                "_config_file",
1364                "_module_name",
1365                "_module_type",
1366                "_epoch_start_callbacks",
1367                "_epoch_stop_callbacks",
1368                "_manually_set_keys",
1369                "_loading_config_values",
1370                "_auto_persist_config",
1371                "_python_supplied",
1372                "_tui_editing",
1373            ):
1374                continue
1375            clean_key = key[1:]
1376            if clean_key == "configuration_confirmed" and not include_confirmed:
1377                continue
1378            # Keep callable config fields (e.g. pai_forward_function) but skip
1379            # any other private callable values that are not typed as callable.
1380            if callable(val) and PAIConfig._TYPES.get(clean_key) is not callable:
1381                continue
1382            try:
1383                config_dict[clean_key] = _serialize_pai_value(val)
1384            except Exception:
1385                config_dict[clean_key] = str(val)
1386
1387        # Plain constants (DOING_*, PARAM_VALS_BY_*, etc.)
1388        for key, val in self.__dict__.items():
1389            if key.startswith("_") or callable(val):
1390                continue
1391            if key not in config_dict:
1392                # Keep config_file runtime-only: do not persist pointer paths in
1393                # saved JSON snapshots.
1394                if key == "config_file":
1395                    continue
1396                if key == "configuration_confirmed" and not include_confirmed:
1397                    continue
1398                try:
1399                    config_dict[key] = _serialize_pai_value(val)
1400                except Exception:
1401                    config_dict[key] = str(val)
1402
1403        # Merge short class names from modules_to_perforate into module_names_to_perforate
1404        # so the UI (and JS) only needs to check one array.
1405        type_short_names = [
1406            cls.__name__
1407            for cls in self.__dict__.get("_modules_to_perforate", [])
1408            if isinstance(cls, type)
1409        ]
1410        existing = config_dict.get("module_names_to_perforate", [])
1411        config_dict["module_names_to_perforate"] = existing + [
1412            n for n in type_short_names if n not in existing
1413        ]
1414
1415        # Preserve any per-module settings written by the Studio frontend.
1416        _existing_ms: dict = {}
1417        try:
1418            with open(filename, "r") as _f:
1419                _existing_ms = json.load(_f).get("module_settings", {})
1420        except Exception:
1421            pass
1422        config_dict["module_settings"] = _existing_ms
1423
1424        # Publish customizable field type names so the Studio frontend can
1425        # render appropriate editors without needing to import the library.
1426        config_dict["_customizable_fields"] = {
1427            k: (v.__name__ if hasattr(v, "__name__") else str(v))
1428            for k, v in PAIConfig._CUSTOMIZABLE.items()
1429        }
1430
1431        # Ensure the directory exists before saving
1432        import os
1433        import tempfile
1434
1435        directory = os.path.dirname(filename)
1436        if directory:
1437            os.makedirs(directory, exist_ok=True)
1438
1439        # Atomic write: never leave the file truncated (DDP ranks may read concurrently).
1440        fd, tmp_path = tempfile.mkstemp(dir=directory or ".", suffix=".tmp")
1441        try:
1442            with os.fdopen(fd, "w") as f:
1443                json.dump(config_dict, f, indent=2)
1444            # mkstemp creates the file owner-only; match what a plain open() would give
1445            umask = os.umask(0)
1446            os.umask(umask)
1447            os.chmod(tmp_path, 0o666 & ~umask)
1448            os.replace(tmp_path, filename)
1449        except Exception:
1450            try:
1451                os.unlink(tmp_path)
1452            except OSError:
1453                pass
1454            raise
1455        print(f"[PAI Config] Saved {len(config_dict)} variables \u2192 {filename}")

Save the current PAIConfig state to a JSON file.

Parameters
  • filename (str): Destination file path (created or overwritten).
  • include_confirmed (bool): When False, configuration_confirmed is left out of the file. Run configs use this so a one-off confirmation is not replayed on later runs.
Notes

Values that are not natively JSON-serialisable (torch.device, torch.dtype, nn.Module subclasses, callables) are stored as their dotted-string representations so they can be round-tripped by load_config().

Returns
  • None: This function does not return a value.
def load_config(self, filename, module_name=None, module_type=None, skip_keys=None):
1457    def load_config(self, filename, module_name=None, module_type=None, skip_keys=None):
1458        """Load PAIConfig state from a JSON file produced by :py:meth:`save_config`.
1459
1460        If *module_name* is ``None`` (default) every serialisable variable in
1461        the file is restored on this instance.
1462
1463        If *module_name* is given the lookup priority is:
1464          1. ``module_settings[module_name]`` (exact name / id match)
1465          2. ``module_settings[module_type]``  (type-level fallback)
1466          3. No-op — the defaults already set by ``__init__`` are kept.
1467
1468        Parameters
1469        ----------
1470        filename : str
1471            Path to the JSON file to read.
1472        module_name : str, optional
1473            Display name (id) of the module whose custom settings should be loaded.
1474        module_type : str, optional
1475            Short class name of the module type, used as a fallback key.
1476
1477        skip_keys : set, optional
1478            Variable names to ignore while loading (manual overrides).
1479
1480        Returns
1481        -------
1482        None
1483            This function does not return a value.
1484        """
1485        import json
1486
1487        with open(filename, "r") as f:
1488            config_dict = json.load(f)
1489
1490        if module_name is not None:
1491            # ── Per-module load ──────────────────────────────────────────────
1492            module_settings = config_dict.get("module_settings", {})
1493            # Priority: exact name → type fallback → no-op
1494            if module_name in module_settings:
1495                custom = module_settings[module_name]
1496                resolved_key = module_name
1497            elif module_type and module_type in module_settings:
1498                custom = module_settings[module_type]
1499                resolved_key = module_type
1500            else:
1501                # No custom settings for this module or type — keep defaults.
1502                return
1503            loaded = 0
1504            skipped = 0
1505            for key, json_val in custom.items():
1506                if key not in PAIConfig._CUSTOMIZABLE:
1507                    continue
1508                type_hint = PAIConfig._TYPES.get(key)
1509                private_key = f"_{key}"
1510                # Write directly to __dict__ so we bypass any setter guards and also
1511                # correctly handle vars that are not pre-initialised on per-module
1512                # configs (e.g. output_dimensions, which only lives inside the
1513                # ``if not module_name:`` block of __init__).
1514                try:
1515                    self.__dict__[private_key] = (
1516                        _deserialize_pai_value(json_val, type_hint)
1517                        if type_hint is not None
1518                        else json_val
1519                    )
1520                    loaded += 1
1521                except Exception as exc:
1522                    print(
1523                        f"[PAI Config] Warning: could not load '{key}' for '{resolved_key}': {exc}"
1524                    )
1525                    skipped += 1
1526            print(
1527                f"[PAI Config] Loaded {loaded} custom vars for '{resolved_key}' from {filename}"
1528                + (f" ({skipped} skipped)" if skipped else "")
1529            )
1530            return
1531
1532        # ── Global load: every variable in the JSON ──────────────────────────
1533        skip_keys = set(skip_keys or [])
1534        loaded = 0
1535        skipped = 0
1536        self.__dict__["_loading_config_values"] = True
1537        try:
1538            for key, json_val in config_dict.items():
1539                # Skip internal bookkeeping and Studio-only metadata keys.
1540                # 'module_name' and 'module_type' must never overwrite the
1541                # instance's _module_name/_module_type (they are internal only).
1542                if key in (
1543                    "config_file",
1544                    "module_settings",
1545                    "module_name",
1546                    "module_type",
1547                ) or key.startswith("_"):
1548                    continue
1549                if key in skip_keys:
1550                    continue
1551                type_hint = PAIConfig._TYPES.get(key)
1552                private_key = f"_{key}"
1553                if hasattr(self, private_key):
1554                    try:
1555                        setattr(
1556                            self,
1557                            private_key,
1558                            (
1559                                _deserialize_pai_value(json_val, type_hint)
1560                                if type_hint is not None
1561                                else json_val
1562                            ),
1563                        )
1564                        loaded += 1
1565                    except Exception as exc:
1566                        print(f"[PAI Config] Warning: could not load '{key}': {exc}")
1567                        skipped += 1
1568                elif hasattr(self, key) and not callable(getattr(self, key, None)):
1569                    try:
1570                        setattr(self, key, json_val)
1571                        loaded += 1
1572                    except Exception:
1573                        skipped += 1
1574            try:
1575                self._block_rules = _normalize_block_rules(self._block_rules)
1576            except ValueError as exc:
1577                print(f"[PAI Config] Warning: ignoring invalid block_rules: {exc}")
1578                self._block_rules = []
1579        finally:
1580            self.__dict__["_loading_config_values"] = False
1581
1582        print(
1583            f"[PAI Config] Loaded {loaded} variables from {filename}"
1584            + (f" ({skipped} skipped)" if skipped else "")
1585        )

Load PAIConfig state from a JSON file produced by save_config().

If module_name is None (default) every serialisable variable in the file is restored on this instance.

If module_name is given the lookup priority is:

  1. module_settings[module_name] (exact name / id match)
  2. module_settings[module_type] (type-level fallback)
  3. No-op — the defaults already set by __init__ are kept.
Parameters
  • filename (str): Path to the JSON file to read.
  • module_name (str, optional): Display name (id) of the module whose custom settings should be loaded.
  • module_type (str, optional): Short class name of the module type, used as a fallback key.
  • skip_keys (set, optional): Variable names to ignore while loading (manual overrides).
Returns
  • None: This function does not return a value.
def get_run_config_path(self):
1587    def get_run_config_path(self):
1588        """Get the run-specific config path derived from save_name.
1589
1590        Returns
1591        -------
1592        str or None
1593            Path to the run config file, or None when save_name is unset.
1594        """
1595        import os
1596
1597        save_name = self.__dict__.get("_save_name")
1598        if not save_name:
1599            return None
1600        return os.path.join(os.getcwd(), save_name, f"{save_name}_config.json")

Get the run-specific config path derived from save_name.

Returns
  • str or None: Path to the run config file, or None when save_name is unset.
def sync_config_sources(self):
1602    def sync_config_sources(self):
1603        """Load config values from configured local JSON sources.
1604
1605        Load order (later sources override earlier ones):
1606        1. run config derived from save_name (if present)
1607        2. config_file pointer (if set)
1608
1609        An explicitly supplied config_file is therefore the highest-priority
1610        file source: it wins over a stale run config left in the save_name
1611        folder by a previous run. With no config_file set, the run config is
1612        the only file source.
1613
1614        Keys set manually in this process are never overwritten.
1615        """
1616        import os
1617
1618        if self.__dict__.get("_module_name") is not None:
1619            return
1620
1621        # Selection lists a script has set are merged with the JSON instead of
1622        # being skipped, so CLI additions survive; see _merge_python_supplied.
1623        merge_keys = [
1624            k for k in SELECTION_LIST_VARS if self.get_python_supplied(k) is not None
1625        ]
1626        skip_keys = set(self.__dict__.get("_manually_set_keys", set())) - set(
1627            merge_keys
1628        )
1629        config_file = self.__dict__.get("_config_file")
1630        run_config = self.get_run_config_path()
1631
1632        if run_config and os.path.exists(run_config):
1633            self.load_config(run_config, skip_keys=skip_keys)
1634        if config_file and os.path.exists(config_file):
1635            self.load_config(config_file, skip_keys=skip_keys)
1636        self._merge_python_supplied(merge_keys)

Load config values from configured local JSON sources.

Load order (later sources override earlier ones):

  1. run config derived from save_name (if present)
  2. config_file pointer (if set)

An explicitly supplied config_file is therefore the highest-priority file source: it wins over a stale run config left in the save_name folder by a previous run. With no config_file set, the run config is the only file source.

Keys set manually in this process are never overwritten.

def get_python_supplied(self, var_name):
1638    def get_python_supplied(self, var_name):
1639        """Items a user script supplied for a selection list, or None.
1640
1641        Class lists (``modules_to_perforate`` / ``modules_to_track``) count
1642        toward the matching ``module_names_*`` list via their short names.
1643        Returns None when the script never set or appended to the list.
1644        """
1645        supplied = self.__dict__.get("_python_supplied", {})
1646        items = None
1647        if var_name in supplied:
1648            items = list(supplied[var_name])
1649        for class_var, names_var in _CLASS_LIST_FEEDS.items():
1650            if names_var == var_name and class_var in supplied:
1651                names = [
1652                    c.__name__ for c in supplied[class_var] if isinstance(c, type)
1653                ]
1654                items = (items or []) + [n for n in names if n not in (items or [])]
1655        return items

Items a user script supplied for a selection list, or None.

Class lists (modules_to_perforate / modules_to_track) count toward the matching module_names_* list via their short names. Returns None when the script never set or appended to the list.

def persist_config_outputs(self, overwrite_config_file=False):
1696    def persist_config_outputs(self, overwrite_config_file=False):
1697        """Persist current config state to local JSON outputs.
1698
1699        Parameters
1700        ----------
1701        overwrite_config_file : bool
1702            When True, also writes the configured config_file pointer target.
1703        """
1704        if self.__dict__.get("_module_name") is not None:
1705            return
1706
1707        run_config = self.get_run_config_path()
1708        if run_config:
1709            self.save_config(run_config, include_confirmed=False)
1710
1711        if overwrite_config_file:
1712            config_file = self.__dict__.get("_config_file")
1713            if config_file:
1714                self.save_config(config_file)

Persist current config state to local JSON outputs.

Parameters
  • overwrite_config_file (bool): When True, also writes the configured config_file pointer target.
class PAISequential(torch.nn.modules.container.Sequential):
1717class PAISequential(nn.Sequential):
1718    """Sequential module wrapper for PAI.
1719
1720    This wrapper takes an array of layers and creates a sequential container
1721    that is compatible with PAI's dendrite addition system. It should be used
1722    for normalization layers and can be used for final output layers.
1723
1724    Parameters
1725    ----------
1726    layer_array : list
1727        List of PyTorch nn.Module objects to be executed sequentially.
1728
1729    Examples
1730    --------
1731    >>> layers = [nn.Linear(2 * hidden_dim, seq_width),
1732    ...           nn.LayerNorm(seq_width)]
1733    >>> sequential_block = PAISequential(layers)
1734
1735    Notes
1736    -----
1737    This should be used for:
1738        - All normalization layers (LayerNorm, BatchNorm, etc.)
1739    This can be used for:
1740        - Final output layer and softmax combinations
1741    """
1742
1743    def __init__(self, layer_array):
1744        """Initialize PAISequential with a list of layers.
1745
1746        Parameters
1747        ----------
1748        layer_array : list
1749            List of PyTorch modules to execute in sequence.
1750        """
1751        super(PAISequential, self).__init__()
1752        self.model = nn.Sequential(*layer_array)
1753
1754    def forward(self, *args, **kwargs):
1755        """Forward pass through the sequential layers.
1756
1757        Parameters
1758        ----------
1759        *args
1760            Positional arguments passed to the first layer.
1761        **kwargs
1762            Keyword arguments passed to the layers.
1763
1764        Returns
1765        -------
1766        torch.Tensor
1767            Output from the final layer in the sequence.
1768        """
1769        return self.model(*args, **kwargs)

Sequential module wrapper for PAI.

This wrapper takes an array of layers and creates a sequential container that is compatible with PAI's dendrite addition system. It should be used for normalization layers and can be used for final output layers.

Parameters
  • layer_array (list): List of PyTorch nn.Module objects to be executed sequentially.
Examples
>>> layers = [nn.Linear(2 * hidden_dim, seq_width),
...           nn.LayerNorm(seq_width)]
>>> sequential_block = PAISequential(layers)
Notes

This should be used for: - All normalization layers (LayerNorm, BatchNorm, etc.) This can be used for: - Final output layer and softmax combinations

PAISequential(layer_array)
1743    def __init__(self, layer_array):
1744        """Initialize PAISequential with a list of layers.
1745
1746        Parameters
1747        ----------
1748        layer_array : list
1749            List of PyTorch modules to execute in sequence.
1750        """
1751        super(PAISequential, self).__init__()
1752        self.model = nn.Sequential(*layer_array)

Initialize PAISequential with a list of layers.

Parameters
  • layer_array (list): List of PyTorch modules to execute in sequence.
model
def forward(self, *args, **kwargs):
1754    def forward(self, *args, **kwargs):
1755        """Forward pass through the sequential layers.
1756
1757        Parameters
1758        ----------
1759        *args
1760            Positional arguments passed to the first layer.
1761        **kwargs
1762            Keyword arguments passed to the layers.
1763
1764        Returns
1765        -------
1766        torch.Tensor
1767            Output from the final layer in the sequence.
1768        """
1769        return self.model(*args, **kwargs)

Forward pass through the sequential layers.

Parameters
  • *args: Positional arguments passed to the first layer.
  • **kwargs: Keyword arguments passed to the layers.
Returns
  • torch.Tensor: Output from the final layer in the sequence.
class FusedNormIdentity(torch.nn.modules.module.Module):
1772class FusedNormIdentity(nn.Module):
1773    """Stand-in left where a norm used to be after it is fused into its head.
1774
1775    The norm now runs inside the head's PAISequential, so this module just
1776    returns its input and the user's forward() can stay exactly as written.
1777    On the first training forward it checks that its input is the head's
1778    output; if the user's forward does anything between the head and the norm,
1779    fusing would silently change the result, so it raises instead.
1780
1781    Parameters
1782    ----------
1783    head_id : str
1784        Module id of the head, used in the error message.
1785    norm_id : str
1786        Module id of the original norm, used in the error message.
1787    """
1788
1789    def __init__(self, head_id, norm_id):
1790        super(FusedNormIdentity, self).__init__()
1791        self.head_id = head_id
1792        self.norm_id = norm_id
1793        # Plain dict so the head output is not registered as a submodule.
1794        self._check = {"head_output": None, "done": False}
1795
1796    def record_head_output(self, output):
1797        """Remember the head's output so forward can compare against it."""
1798        if not self._check["done"]:
1799            self._check["head_output"] = output
1800
1801    def forward(self, x):
1802        if not self._check["done"]:
1803            if x is not self._check["head_output"]:
1804                raise RuntimeError(
1805                    "Cannot fuse %s with %s: the input to %s is not the output "
1806                    "of %s. Something in forward() runs between them, so fusing "
1807                    "would change the result. Remove this pair from the fused "
1808                    "modules."
1809                    % (
1810                        self.head_id,
1811                        self.norm_id,
1812                        self.norm_id,
1813                        self.head_id,
1814                    )
1815                )
1816            self._check["done"] = True
1817            self._check["head_output"] = None
1818        return x

Stand-in left where a norm used to be after it is fused into its head.

The norm now runs inside the head's PAISequential, so this module just returns its input and the user's forward() can stay exactly as written. On the first training forward it checks that its input is the head's output; if the user's forward does anything between the head and the norm, fusing would silently change the result, so it raises instead.

Parameters
  • head_id (str): Module id of the head, used in the error message.
  • norm_id (str): Module id of the original norm, used in the error message.
FusedNormIdentity(head_id, norm_id)
1789    def __init__(self, head_id, norm_id):
1790        super(FusedNormIdentity, self).__init__()
1791        self.head_id = head_id
1792        self.norm_id = norm_id
1793        # Plain dict so the head output is not registered as a submodule.
1794        self._check = {"head_output": None, "done": False}

Initialize internal Module state, shared by both nn.Module and ScriptModule.

head_id
norm_id
def record_head_output(self, output):
1796    def record_head_output(self, output):
1797        """Remember the head's output so forward can compare against it."""
1798        if not self._check["done"]:
1799            self._check["head_output"] = output

Remember the head's output so forward can compare against it.

def forward(self, x):
1801    def forward(self, x):
1802        if not self._check["done"]:
1803            if x is not self._check["head_output"]:
1804                raise RuntimeError(
1805                    "Cannot fuse %s with %s: the input to %s is not the output "
1806                    "of %s. Something in forward() runs between them, so fusing "
1807                    "would change the result. Remove this pair from the fused "
1808                    "modules."
1809                    % (
1810                        self.head_id,
1811                        self.norm_id,
1812                        self.norm_id,
1813                        self.head_id,
1814                    )
1815                )
1816            self._check["done"] = True
1817            self._check["head_output"] = None
1818        return x

Define the computation performed at every call.

Should be overridden by all subclasses.

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

pc = <PAIConfig object>

Global PAIConfig instance.

This is the primary configuration object used throughout the PAI system. Modify settings through this instance to control PAI behavior.

pai_tracker = []
pai_scaler = None