perforatedai.utils_perforatedai

   1# Copyright (c) 2025 Perforated AI
   2
   3import torch
   4import torch.nn as nn
   5import torch.nn.init as init
   6import torch.nn.functional as F
   7import math
   8import sys
   9import numpy as np
  10import pdb
  11import os
  12import time
  13import warnings
  14from collections import defaultdict
  15
  16from perforatedai import globals_perforatedai as GPA
  17from perforatedai import modules_perforatedai as PA
  18from perforatedai import tracker_perforatedai as TPA
  19from perforatedai import clean_perforatedai as CL
  20from perforatedai import blockwise_perforatedai as BPA
  21from perforatedai import network_perforatedai as NPA
  22from perforatedai import configure_perforatedai as CPA
  23
  24try:
  25    from dashboard_utils.event_emitter import emitter as _dashboard_emitter
  26except ImportError:
  27    _dashboard_emitter = None
  28
  29try:
  30    from perforatedbp import utils_pbp as UPB
  31    from perforatedbp import modules_pbp as MPB
  32except ModuleNotFoundError as e:
  33    # Only pass if perforatedbp package itself is missing
  34    if e.name == "perforatedbp":
  35        pass
  36    else:
  37        # perforatedbp exists but is missing a dependency
  38        raise
  39
  40import copy
  41
  42from safetensors.torch import load_file
  43from safetensors.torch import save_file
  44from safetensors.torch import safe_open
  45
  46
  47def perforate_model(
  48    model,
  49    doing_pai=True,
  50    save_name="",
  51    making_graphs=True,
  52    maximizing_score=None,
  53    num_classes=10000000000,
  54    values_per_train_epoch=-1,
  55    values_per_val_epoch=-1,
  56    zooming_graph=True,
  57    config_file=None,
  58):
  59    """Main function to initialize the network to add dendrites
  60
  61    This kicks off the entire Perforated AI process to add
  62    the scaffolding to the network to be able to add dendrites
  63
  64    Parameters
  65    ----------
  66    model : nn.Module
  67        The neural network model to initialize.
  68    doing_pai : bool, optional
  69        Whether to actually add dendrites, by default True
  70    save_name : str, optional
  71        The name to save the model under, by default "PAI"
  72    making_graphs : bool, optional
  73        Whether to create graphs during training, by default True
  74    maximizing_score : bool or None, optional
  75        Whether to maximize the score during training.
  76        - None: use config value (defaults to True)
  77        - bool: override config value for this run
  78        Setting False is for when the score is a loss to be minimized.
  79    num_classes : int, optional
  80        The number of output classes, unused in current version
  81    values_per_train_epoch : int, optional
  82        The number of values to look back for graphing
  83        during training, by default -1 (all values).
  84    values_per_val_epoch : int, optional
  85        The number of values to look back for graphing
  86        during validation, by default -1 (all values).
  87    zooming_graph : bool, optional
  88        Whether to enable zooming on the graphs, by default True
  89    config_file : str or None, optional
  90        Optional local JSON config file path to load, by default None.
  91
  92    Returns
  93    -------
  94    model : nn.Module
  95        The modified model with dendrite scaffolding added if doing_pai is True
  96
  97    """
  98
  99    if save_name == "":
 100        if GPA.pc.get_save_name() == "":
 101            save_name = "PAI"
 102        else:
 103            save_name = GPA.pc.get_save_name()
 104
 105    if "/" in save_name:
 106        print(
 107            f"Warning: save_name '{save_name}' contains '/'. Relative paths are not implemented yet."
 108        )
 109        sys.exit(1)
 110
 111    sanitized_save_name = "".join(
 112        ch for ch in save_name if ch.isalnum() or ch in ("_", "-", ".")
 113    )
 114    if sanitized_save_name != save_name:
 115        print(
 116            f"Warning: save_name '{save_name}' contained spaces or special characters. "
 117            f"Using '{sanitized_save_name}' instead."
 118        )
 119        save_name = sanitized_save_name
 120
 121    if save_name == "":
 122        print("Warning: save_name became empty after sanitization. Using 'PAI'.")
 123        save_name = "PAI"
 124
 125    if config_file is not None:
 126        GPA.pc.set_config_file(config_file)
 127
 128    GPA.pc.set_save_name(save_name)
 129    GPA.pc.sync_config_sources()
 130
 131    if maximizing_score is None:
 132        maximizing_score = GPA.pc.get_maximizing_score()
 133    else:
 134        # Programmatic perforate_model input must win over config-file values.
 135        GPA.pc.set_maximizing_score(maximizing_score)
 136
 137    if os.environ.get("PAI_CONFIG_MODE"):
 138        GPA.pc.set_configuration_confirmed(False)
 139
 140    if not GPA.pc.get_configuration_confirmed():
 141        CPA.set_perforation_targets(model)
 142
 143    fused_pairs = apply_fused_pairs(model) if doing_pai else []
 144
 145    # Install the default dendrite loss mode before any code reads the selected loss
 146    # class through MPB.get_global_dendrite_loss_class(). The underlying private global
 147    # now starts as None (its former import-time default was removed so that
 148    # setup_new_global_dendrite_mode is the only writer); initialize() below constructs
 149    # the dendrite modules and value trackers that perform the first reads, so the
 150    # installer must run ahead of it.
 151    # The call is idempotent: a user who called setup_new_global_dendrite_mode
 152    # themselves before perforate_model keeps their own choice. It is reached only
 153    # when Perforated Backpropagation is enabled, which guarantees perforatedbp is
 154    # importable (the enable flag is set only after that import succeeds), and by
 155    # the time perforate_model runs every module has finished importing, so this
 156    # runtime import cannot create a cycle.
 157    if GPA.pc.get_perforated_backpropagation():
 158        import perforatedbp.tracker_pbp as TPB
 159
 160        TPB.install_global_default_dendrite_mode()
 161
 162    GPA.pai_tracker = TPA.PAINeuronModuleTracker(
 163        doing_pai=doing_pai, save_name=save_name
 164    )
 165    if _dashboard_emitter is not None:
 166        _dashboard_emitter.emit_run_start(GPA.pc, save_name)
 167
 168    # Get config outputs before tracker is initialized
 169    GPA.pc.persist_config_outputs(overwrite_config_file=False)
 170
 171    model = GPA.pai_tracker.initialize(
 172        model,
 173        doing_pai=doing_pai,
 174        save_name=save_name,
 175        making_graphs=making_graphs,
 176        maximizing_score=maximizing_score,
 177        num_classes=num_classes,
 178        values_per_train_epoch=-values_per_train_epoch,
 179        values_per_val_epoch=values_per_val_epoch,
 180        zooming_graph=zooming_graph,
 181    )
 182
 183    if fused_pairs:
 184        install_fuse_checks(model, fused_pairs)
 185
 186    for param in model.parameters():
 187        param.data = param.data.contiguous()
 188
 189    # When perforated backpropagation is enabled, register the epoch-boundary
 190    # hooks so a dendrite loss class's on_epoch_* methods fire automatically,
 191    # rather than requiring the application to call register_epoch_hooks() by
 192    # hand before perforate_model. Imported at call time to avoid a circular
 193    # import; its perforatedbp imports are only usable when perforated
 194    # backpropagation is enabled.
 195    if GPA.pc.get_perforated_backpropagation():
 196        from perforatedai.dendrite_loss_events import register_epoch_hooks
 197
 198        register_epoch_hooks()
 199
 200    # Save config after perforation
 201    if not GPA.pc.get_testing_dendrite_capacity():
 202        GPA.pc.save_config(os.path.join(os.getcwd(), save_name, f"{save_name}_config.json"))
 203
 204    return model
 205
 206
 207def _split_module_id(module_id):
 208    """Split a module id like '.block.linear' into ('block', 'linear')."""
 209    path = module_id[1:] if module_id.startswith(".") else module_id
 210    parent_path, _, attr = path.rpartition(".")
 211    return parent_path, attr
 212
 213
 214def fuse_modules(model, pairs):
 215    """Fuse each head with the norm that follows it.
 216
 217    For every (head_id, norm_id) the head's attribute becomes a PAISequential
 218    holding the head and the norm, and the norm's attribute becomes a
 219    FusedNormIdentity. The model's forward() does not need to change. Must be
 220    called before convert_network, and before load_system.
 221
 222    Parameters
 223    ----------
 224    model : nn.Module
 225        The model to modify in place.
 226    pairs : list of (str, str)
 227        Module ids (like '.block.linear') of each head and its norm.
 228
 229    Returns
 230    -------
 231    nn.Module
 232        The same model, with the pairs fused.
 233    """
 234    if not pairs:
 235        return model
 236    pairs = [tuple(pair) for pair in pairs]
 237
 238    occurrences = {}
 239    for _name, module in model.named_modules(remove_duplicate=False):
 240        occurrences[id(module)] = occurrences.get(id(module), 0) + 1
 241
 242    seen_ids = []
 243    for head_id, norm_id in pairs:
 244        for role, module_id in (("head", head_id), ("norm", norm_id)):
 245            try:
 246                module = model.get_submodule(module_id.lstrip("."))
 247            except AttributeError:
 248                raise ValueError(
 249                    "Cannot fuse: %s %s does not exist in the model." % (role, module_id)
 250                )
 251            if module_id.lstrip(".") == "":
 252                raise ValueError("Cannot fuse the whole model.")
 253            if module_id in seen_ids:
 254                raise ValueError(
 255                    "Cannot fuse: %s is in more than one fused pair." % module_id
 256                )
 257            seen_ids.append(module_id)
 258            if occurrences[id(module)] > 1:
 259                raise ValueError(
 260                    "Cannot fuse: %s is used in more than one place in the model."
 261                    % module_id
 262                )
 263        head = model.get_submodule(head_id.lstrip("."))
 264        if not any(param.requires_grad for param in head.parameters()):
 265            raise ValueError(
 266                "Cannot fuse: head %s is not trainable. Only trainable modules "
 267                "can be the head of a fused pair." % head_id
 268            )
 269    for first in seen_ids:
 270        for second in seen_ids:
 271            if first != second and second.startswith(first + "."):
 272                raise ValueError(
 273                    "Cannot fuse: %s is inside %s, which is also fused."
 274                    % (second, first)
 275                )
 276
 277    for head_id, norm_id in pairs:
 278        head = model.get_submodule(head_id.lstrip("."))
 279        norm = model.get_submodule(norm_id.lstrip("."))
 280        head_parent, head_attr = _split_module_id(head_id)
 281        norm_parent, norm_attr = _split_module_id(norm_id)
 282        model.get_submodule(head_parent)._modules[head_attr] = GPA.PAISequential(
 283            [head, norm]
 284        )
 285        model.get_submodule(norm_parent)._modules[norm_attr] = GPA.FusedNormIdentity(
 286            head_id, norm_id
 287        )
 288    return model
 289
 290
 291def install_fuse_checks(model, pairs):
 292    """Make each fused norm stand-in verify its input on the first forward.
 293
 294    Must be called after convert_network, because by then the head's attribute
 295    holds a PAINeuronModule whose output (not the raw PAISequential's) is what
 296    the stand-in receives.
 297
 298    Parameters
 299    ----------
 300    model : nn.Module
 301        The model after fuse_modules and convert_network.
 302    pairs : list of (str, str)
 303        The same pairs passed to fuse_modules.
 304    """
 305    for head_id, norm_id in pairs:
 306        head = model.get_submodule(head_id.lstrip("."))
 307        stand_in = model.get_submodule(norm_id.lstrip("."))
 308        head.register_forward_hook(
 309            lambda _module, _inputs, output, stand_in=stand_in: stand_in.record_head_output(
 310                output
 311            )
 312        )
 313
 314
 315def apply_fused_pairs(model):
 316    """Fuse the configured pairs and mark each head for perforation.
 317
 318    Reads modules_to_fuse from the config. A head that is also set to be
 319    tracked is rejected, since fusing exists to perforate it.
 320
 321    Parameters
 322    ----------
 323    model : nn.Module
 324        The model to modify in place.
 325
 326    Returns
 327    -------
 328    list
 329        The pairs that were fused, as [head_id, norm_id] lists.
 330    """
 331    pairs = [list(pair) for pair in GPA.pc.get_modules_to_fuse()]
 332    if not pairs:
 333        return []
 334    tracked = set(GPA.pc.get_module_ids_to_track())
 335    for head_id, norm_id in pairs:
 336        if head_id in tracked:
 337            raise ValueError(
 338                "Cannot fuse %s with %s: %s is set to be tracked. Remove it "
 339                "from the tracked modules or un-fuse the pair." % (head_id, norm_id, head_id)
 340            )
 341    fuse_modules(model, pairs)
 342    perforated = list(GPA.pc.get_module_ids_to_perforate())
 343    for head_id, _norm_id in pairs:
 344        if head_id not in perforated:
 345            perforated.append(head_id)
 346    GPA.pc.set_module_ids_to_perforate(perforated)
 347    return pairs
 348
 349
 350def get_pai_modules(net, depth, seen_ids=None):
 351    """Get a list of all neuron modules
 352
 353    Parameters
 354    ----------
 355    net : nn.Module
 356        The module to search.
 357    depth : int
 358        The current depth in the recursion.
 359
 360    Returns
 361    -------
 362    list
 363        A list of all PAI neuron modules found in the network.
 364
 365    """
 366    if seen_ids is None:
 367        seen_ids = set()
 368    all_members = net.__dir__()
 369    this_list = []
 370    if issubclass(type(net), nn.Sequential) or issubclass(type(net), nn.ModuleList):
 371        for submodule_id, layer in net.named_children():
 372            # If there is a self pointer ignore it
 373            if net.get_submodule(submodule_id) is net:
 374                continue
 375            if type(net.get_submodule(submodule_id)) is PA.PAINeuronModule:
 376                module = net.get_submodule(submodule_id)
 377                if id(module) in seen_ids:
 378                    continue
 379                seen_ids.add(id(module))
 380                this_list = this_list + [module]
 381            else:
 382                this_list = this_list + get_pai_modules(
 383                    net.get_submodule(submodule_id), depth + 1, seen_ids
 384                )
 385    else:
 386        for member in all_members:
 387            if isinstance(getattr(type(net), member, None), property):
 388                continue
 389            # if the getter fails or it is a self pointer ignore it
 390            try:
 391                if getattr(net, member, None) is net:
 392                    continue
 393            except:
 394                continue
 395            if type(getattr(net, member, None)) is PA.PAINeuronModule:
 396                module = getattr(net, member)
 397                if id(module) in seen_ids:
 398                    continue
 399                seen_ids.add(id(module))
 400                this_list = this_list + [module]
 401            elif (
 402                issubclass(type(getattr(net, member, None)), nn.Module)
 403                or issubclass(type(getattr(net, member, None)), nn.Sequential)
 404                or issubclass(type(getattr(net, member, None)), nn.ModuleList)
 405            ):
 406                this_list = this_list + get_pai_modules(
 407                    getattr(net, member), depth + 1, seen_ids
 408                )
 409
 410    return this_list
 411
 412
 413def get_tracked_modules(net, depth, seen_ids=None):
 414    """Get a list of all tracked modules
 415
 416    Parameters
 417    ----------
 418    net : nn.Module
 419        The module to search.
 420    depth : int
 421        The current depth in the recursion.
 422
 423    Returns
 424    -------
 425    list
 426        A list of all tracked modules found in the network.
 427
 428    """
 429    if seen_ids is None:
 430        seen_ids = set()
 431    all_members = net.__dir__()
 432    this_list = []
 433    if issubclass(type(net), nn.Sequential) or issubclass(type(net), nn.ModuleList):
 434        for submodule_id, layer in net.named_children():
 435            if net.get_submodule(submodule_id) is net:
 436                continue
 437            if type(net.get_submodule(submodule_id)) is PA.TrackedNeuronModule:
 438                module = net.get_submodule(submodule_id)
 439                if id(module) in seen_ids:
 440                    continue
 441                seen_ids.add(id(module))
 442                this_list = this_list + [module]
 443            else:
 444                this_list = this_list + get_tracked_modules(
 445                    net.get_submodule(submodule_id), depth + 1, seen_ids
 446                )
 447    else:
 448        for member in all_members:
 449            if isinstance(getattr(type(net), member, None), property):
 450                continue
 451            # if the getter fails or it is a self pointer ignore it
 452            try:
 453                if getattr(net, member, None) is net:
 454                    continue
 455            except:
 456                continue
 457            if type(getattr(net, member, None)) is PA.TrackedNeuronModule:
 458                module = getattr(net, member)
 459                if id(module) in seen_ids:
 460                    continue
 461                seen_ids.add(id(module))
 462                this_list = this_list + [module]
 463            elif issubclass(type(getattr(net, member, None)), nn.Module):
 464                this_list = this_list + get_tracked_modules(
 465                    getattr(net, member), depth + 1, seen_ids
 466                )
 467    return this_list
 468
 469
 470def get_pai_module_params(net, depth, seen_ids=None):
 471    """Get a list of all neuron module parameters
 472
 473    Parameters
 474    ----------
 475    net : nn.Module
 476        The module to search.
 477    depth : int
 478        The current depth in the recursion.
 479
 480    Returns
 481    -------
 482    list
 483        A list of all parameters of neuron modules found in this module.
 484
 485    """
 486
 487    if seen_ids is None:
 488        seen_ids = set()
 489    all_members = net.__dir__()
 490    this_list = []
 491    if issubclass(type(net), nn.Sequential) or issubclass(type(net), nn.ModuleList):
 492        for submodule_id, layer in net.named_children():
 493            if isinstance(net.get_submodule(submodule_id), PA.PAINeuronModule):  #
 494                module = net.get_submodule(submodule_id)
 495                if id(module) in seen_ids:
 496                    continue
 497                seen_ids.add(id(module))
 498                for param in module.parameters():
 499                    if param.requires_grad:
 500                        this_list = this_list + [param]
 501            else:
 502                this_list = this_list + get_pai_module_params(
 503                    net.get_submodule(submodule_id), depth + 1, seen_ids
 504                )
 505    else:
 506        for member in all_members:
 507            if isinstance(getattr(type(net), member, None), property):
 508                continue
 509            if getattr(net, member, None) == net:
 510                continue
 511            if isinstance(getattr(net, member, None), PA.PAINeuronModule):
 512                module = getattr(net, member)
 513                if id(module) in seen_ids:
 514                    continue
 515                seen_ids.add(id(module))
 516                for param in module.parameters():
 517                    if param.requires_grad:
 518                        this_list = this_list + [param]
 519            elif issubclass(type(getattr(net, member, None)), nn.Module):
 520                this_list = this_list + get_pai_module_params(
 521                    getattr(net, member), depth + 1, seen_ids
 522                )
 523    return this_list
 524
 525
 526def get_pai_network_params(net):
 527    """Get a list of all neuron module parameters
 528
 529    Parameters
 530    ----------
 531    net : nn.Module
 532        The full model to search.
 533
 534    Returns
 535    -------
 536    list
 537        A list of all parameters of neuron modules found in the network.
 538
 539    """
 540    param_list = get_pai_module_params(net, 0)
 541    return param_list
 542
 543
 544# Set by get_parameter_groups, to tell whether the optimizer can apply dendrite_lr_multiplier.
 545parameter_groups_requested = False
 546
 547
 548def get_parameter_groups(params, lr=None):
 549    """Split optimizer parameters so that dendrites train at a higher learning rate.
 550
 551    Dendrite parameters ("dendrite" and "tree" parameter_type) are moved out of
 552    each parameter group into a copy of that group with its learning rate
 553    multiplied by GPA.pc.get_dendrite_lr_multiplier().  A dendrite's output
 554    weights start at 0, so at a small learning rate a new dendrite barely changes
 555    the network.  Use the result as the params of the optimizer, and call this
 556    again whenever the optimizer is rebuilt after dendrites were added.
 557    setup_optimizer calls this itself.
 558
 559    Parameters
 560    ----------
 561    params : iterable
 562        Parameters or parameter groups, as they would be passed to a torch optimizer.
 563    lr : float, optional
 564        The optimizer's learning rate, for parameter groups that do not set their own.
 565
 566    Returns
 567    -------
 568    iterable
 569        params itself if the multiplier is 1 or there are no dendrite parameters.
 570        Otherwise a list of parameter groups: the given groups without their dendrite
 571        parameters, followed by the groups of dendrite parameters.
 572    """
 573    global parameter_groups_requested
 574    parameter_groups_requested = True
 575    multiplier = GPA.pc.get_dendrite_lr_multiplier()
 576    if multiplier == 1:
 577        return params
 578    params = list(params)
 579    groups = params if params and isinstance(params[0], dict) else [{"params": params}]
 580    if not any(
 581        PA.is_dendrite_parameter(p) for group in groups for p in group["params"]
 582    ):
 583        return params
 584    neuron_groups = []
 585    dendrite_groups = []
 586    for group in groups:
 587        group_params = list(group["params"])
 588        neuron_params = [p for p in group_params if not PA.is_dendrite_parameter(p)]
 589        dendrite_params = [p for p in group_params if PA.is_dendrite_parameter(p)]
 590        if neuron_params:
 591            neuron_groups.append({**group, "params": neuron_params})
 592        if dendrite_params:
 593            group_lr = group.get("lr", lr)
 594            if group_lr is None:
 595                raise ValueError(
 596                    "get_parameter_groups needs the optimizer's learning rate to set "
 597                    "the dendrite learning rate, pass it as lr"
 598                )
 599            dendrite_groups.append(
 600                {**group, "params": dendrite_params, "lr": group_lr * multiplier}
 601            )
 602    return neuron_groups + dendrite_groups
 603
 604
 605def get_neuron_learning_rate(optimizer):
 606    """Get the learning rate of the neurons, ignoring dendrite parameter groups.
 607
 608    Parameters
 609    ----------
 610    optimizer : torch.optim.Optimizer
 611        The optimizer, possibly with dendrite groups from get_parameter_groups.
 612
 613    Returns
 614    -------
 615    float
 616        The learning rate of the first parameter group that is not only dendrite parameters.
 617    """
 618    for param_group in optimizer.param_groups:
 619        if not all(PA.is_dendrite_parameter(p) for p in param_group["params"]):
 620            return param_group["lr"]
 621    return optimizer.param_groups[0]["lr"]
 622
 623
 624def replace_predefined_modules(start_module):
 625    """Replace a module with the module from globals list
 626
 627    Parameters
 628    ----------
 629    start_module : nn.Module
 630        The module to replace.
 631
 632    Returns
 633    -------
 634    nn.Module
 635        The replaced module.
 636
 637    """
 638    index = GPA.pc.get_modules_to_replace().index(type(start_module))
 639    return GPA.pc.get_replacement_modules()[index](start_module)
 640
 641
 642def scan_module_aliases(net):
 643    """Find alias module paths that point to already-seen module instances.
 644
 645    Parameters
 646    ----------
 647    net : Any PyTorch Module.
 648
 649    Returns
 650    -------
 651    dict[str, str]
 652        Mapping of alias module paths to their canonical module paths.
 653    """
 654    canonical = {}
 655    aliases = {}
 656    for name, module in net.named_modules(remove_duplicate=False):
 657        if name == "":
 658            continue
 659        sub_name = "." + name
 660        module_id = id(module)
 661        if module_id in canonical:
 662            aliases[sub_name] = canonical[module_id]
 663        else:
 664            canonical[module_id] = sub_name
 665    return aliases
 666
 667
 668# Block rules are resolved lazily while convert_module descends: reaching a
 669# module whose class is a rule's block registers that instance's rule ids, so
 670# they also apply inside modules that were just replaced. Explicit ids are
 671# always checked first, and a wrapped ancestor is never descended into.
 672_block_rule_state = {"ids": {"perforated": {}, "tracked": {}}, "hits": {}}
 673
 674
 675def _reset_block_rule_state():
 676    _block_rule_state["ids"] = {"perforated": {}, "tracked": {}}
 677    _block_rule_state["hits"] = {}
 678
 679
 680def _register_block_rule_ids(net, name_so_far):
 681    """Register each matching block rule's absolute id for this block instance."""
 682    rules = GPA.pc.get_block_rules()
 683    if not rules:
 684        return
 685    block = type(net).__name__
 686    for index, rule in enumerate(rules):
 687        if rule["block"] == block:
 688            _block_rule_state["ids"][rule["mode"]].setdefault(
 689                name_so_far + rule["path"], index
 690            )
 691
 692
 693def _block_rule_hit(sub_name, mode):
 694    index = _block_rule_state["ids"][mode].get(sub_name)
 695    if index is None:
 696        return False
 697    _block_rule_state["hits"][index] = _block_rule_state["hits"].get(index, 0) + 1
 698    return True
 699
 700
 701def _id_to_track(sub_name):
 702    """True if this id is tracked by an explicit id or, failing that, a block rule."""
 703    if sub_name in GPA.pc.get_module_ids_to_track():
 704        return True
 705    if sub_name in GPA.pc.get_module_ids_to_perforate():
 706        return False
 707    return _block_rule_hit(sub_name, "tracked")
 708
 709
 710def _id_to_perforate(sub_name):
 711    """True if this id is perforated by an explicit id or, failing that, a block rule."""
 712    if sub_name in GPA.pc.get_module_ids_to_perforate():
 713        return True
 714    if sub_name in GPA.pc.get_module_ids_to_track():
 715        return False
 716    return _block_rule_hit(sub_name, "perforated")
 717
 718
 719def _warn_unused_block_rules():
 720    for index, rule in enumerate(GPA.pc.get_block_rules()):
 721        if _block_rule_state["hits"].get(index, 0) == 0:
 722            print(
 723                "Warning: block rule %s %s (%s) did not apply to any module. "
 724                "Check that a %s with that path exists in the model and that it "
 725                "is not inside a module that is perforated or tracked as a whole."
 726                % (rule["block"], rule["path"], rule["mode"], rule["block"])
 727            )
 728
 729
 730def convert_module(
 731    net,
 732    depth,
 733    name_so_far,
 734    converted_list,
 735    converted_names_list,
 736    neuron_module_class,
 737    tracked_module_class,
 738    config_setup=False,
 739):
 740    """Recursive function to do all conversion of modules to wrappers of modules
 741
 742    This is the function that goes through all of the module lists from
 743    the globals file and does all the conversion and replacements to
 744    setup the dendrite scaffolding as instructed.
 745
 746    Parameters
 747    ----------
 748    net : nn.Module
 749        The module to convert.
 750    depth : int
 751        The current depth in the recursion.
 752    name_so_far : str
 753        The name of the module so far in the recursion.
 754    converted_list : list
 755        A list of already converted module ids to avoid infinite loops.
 756    converted_names_list : list
 757        A corresponding list to help debug duplicate conversions
 758
 759    Returns
 760    -------
 761    nn.Module
 762        The converted module.
 763
 764    """
 765    if GPA.pc.get_verbose():
 766        print("calling convert on %s depth %d" % (net, depth))
 767        print(
 768            "calling convert on %s: %s, depth %d"
 769            % (name_so_far, type(net).__name__, depth)
 770        )
 771    if isinstance(net, neuron_module_class) or (
 772        (tracked_module_class is not None) and isinstance(net, tracked_module_class)
 773    ):
 774        if GPA.pc.get_verbose():
 775            print(
 776                "This is only being called because something in your model "
 777                "is pointed to twice by two different variables. Highest "
 778                "thing on the list is one of the duplicates"
 779            )
 780        return net
 781    if depth == 0 and name_so_far == "":
 782        aliases = scan_module_aliases(net)
 783        existing_not_save = set(GPA.pc.get_module_names_to_not_save())
 784        aliases_to_skip = [
 785            alias for alias in aliases.keys() if alias not in existing_not_save
 786        ]
 787        if aliases_to_skip and not config_setup:
 788            GPA.pc.append_module_names_to_not_save(aliases_to_skip)
 789            print(
 790                "Auto-detected duplicate module aliases via named_modules; "
 791                "keeping first-seen paths and skipping:"
 792            )
 793            for alias in aliases_to_skip:
 794                print(" - %s (keeps %s)" % (alias, aliases[alias]))
 795    if depth == 0 and name_so_far == "":
 796        _reset_block_rule_state()
 797    _register_block_rule_ids(net, name_so_far)
 798    all_members = net.__dir__()
 799    if GPA.pc.get_extra_verbose():
 800        print("all members:")
 801        for member in all_members:
 802            print(" - %s" % member)
 803    if issubclass(type(net), nn.Sequential) or issubclass(type(net), nn.ModuleList):
 804        for submodule_id, layer in net.named_children():
 805            sub_name = name_so_far + "." + str(submodule_id)
 806            if _id_to_track(sub_name):
 807                if GPA.pc.get_verbose():
 808                    print("Seq ID is in track IDs: %s" % sub_name)
 809                if tracked_module_class is None:
 810                    continue
 811                if config_setup:
 812                    net.get_submodule(submodule_id).pai_mode = "tracked"
 813                else:
 814                    setattr(
 815                        net,
 816                        submodule_id,
 817                        tracked_module_class(net.get_submodule(submodule_id), sub_name),
 818                    )
 819                continue
 820            if _id_to_perforate(sub_name):
 821                if GPA.pc.get_verbose():
 822                    print("Seq ID is in convert IDs: %s" % sub_name)
 823                if config_setup:
 824                    net.get_submodule(submodule_id).pai_mode = "perforated"
 825                else:
 826                    setattr(
 827                        net,
 828                        submodule_id,
 829                        neuron_module_class(net.get_submodule(submodule_id), sub_name),
 830                    )
 831                continue
 832            if type(net.get_submodule(submodule_id)) in GPA.pc.get_modules_to_replace():
 833                if GPA.pc.get_verbose():
 834                    print(
 835                        "Seq sub is in replacement module so replacing: %s" % sub_name
 836                    )
 837                if config_setup:
 838                    net.get_submodule(submodule_id).pai_mode = "replaced"
 839                else:
 840                    setattr(
 841                        net,
 842                        submodule_id,
 843                        replace_predefined_modules(net.get_submodule(submodule_id)),
 844                    )
 845            if (
 846                type(net.get_submodule(submodule_id)) in GPA.pc.get_modules_to_track()
 847            ) or (
 848                type(net.get_submodule(submodule_id)).__name__
 849                in GPA.pc.get_module_names_to_track()
 850            ):
 851                if GPA.pc.get_verbose():
 852                    print(
 853                        "Seq sub is in tracking list so initiating tracked for: %s"
 854                        % sub_name
 855                    )
 856                if tracked_module_class is None:
 857                    continue
 858                if config_setup:
 859                    net.get_submodule(submodule_id).pai_mode = "tracked"
 860                else:
 861                    setattr(
 862                        net,
 863                        submodule_id,
 864                        tracked_module_class(net.get_submodule(submodule_id), sub_name),
 865                    )
 866            elif (
 867                type(net.get_submodule(submodule_id))
 868                in GPA.pc.get_modules_to_perforate()
 869                or type(net.get_submodule(submodule_id)).__name__
 870                in GPA.pc.get_module_names_to_perforate()
 871            ):
 872                if GPA.pc.get_verbose():
 873                    print(
 874                        "Seq sub is in conversion list so initing PAI for: "
 875                        "%s" % sub_name
 876                    )
 877                if (
 878                    issubclass(
 879                        type(net.get_submodule(submodule_id)),
 880                        torch.nn.modules.batchnorm._BatchNorm,
 881                    )
 882                    or issubclass(
 883                        type(net.get_submodule(submodule_id)),
 884                        torch.nn.modules.instancenorm._InstanceNorm,
 885                    )
 886                    or issubclass(
 887                        type(net.get_submodule(submodule_id)),
 888                        torch.nn.modules.normalization.LayerNorm,
 889                    )
 890                ):
 891                    print(
 892                        "You have an unwrapped normalization layer, this "
 893                        "is not recommended: " + name_so_far
 894                    )
 895                    pdb.set_trace()
 896                if config_setup:
 897                    net.get_submodule(submodule_id).pai_mode = "perforated"
 898                else:
 899                    setattr(
 900                        net,
 901                        submodule_id,
 902                        neuron_module_class(net.get_submodule(submodule_id), sub_name),
 903                    )
 904            else:
 905                if net != net.get_submodule(submodule_id):
 906                    converted_list += [id(net.get_submodule(submodule_id))]
 907                    converted_names_list += [sub_name]
 908                    if GPA.pc.get_verbose():
 909                        print(
 910                            "sub is module but in no lists so going deeper: %s"
 911                            % sub_name
 912                        )
 913
 914                    setattr(
 915                        net,
 916                        submodule_id,
 917                        convert_module(
 918                            net.get_submodule(submodule_id),
 919                            depth + 1,
 920                            sub_name,
 921                            converted_list,
 922                            converted_names_list,
 923                            neuron_module_class,
 924                            tracked_module_class,
 925                            config_setup,
 926                        ),
 927                    )
 928                # else:
 929                # print('%s is a self pointer so skipping' % (name_so_far + '[' + str(submodule_id) + ']'))
 930    elif type(net) in GPA.pc.get_modules_to_track():
 931        # print('skipping type for returning from call to: %s' % (name_so_far))
 932        return net
 933    else:
 934        for member in all_members:
 935            if isinstance(getattr(type(net), member, None), property):
 936                continue
 937            # Immediately check if able to get the member, if not skip it
 938            try:
 939                getattr(net, member, None)
 940            except:
 941                continue
 942            sub_name = name_so_far + "." + member
 943            member_obj = getattr(net, member, None)
 944
 945            if isinstance(member_obj, (torch.nn.Parameter, torch.nn.parameter.Parameter)):
 946                if sub_name in GPA.pc.get_parameter_ids_to_track():
 947                    if GPA.pc.get_verbose():
 948                        print("tracking parameter by ID: %s" % sub_name)
 949                    if config_setup:
 950                        member_obj.pai_mode = "tracked"
 951                    else:
 952                        member_obj.parameter_type = "neuron"
 953                        member_obj.wrapped = True
 954                continue
 955
 956            # Track module object ids once at this level so duplicate aliases are
 957            # caught consistently (including direct children of the root module).
 958            if isinstance(member_obj, nn.Module):
 959                if id(member_obj) in converted_list:
 960                    original_sub_name = converted_names_list[
 961                        converted_list.index(id(member_obj))
 962                    ]
 963                    print(
 964                        "The following module has a duplicate pointer within "
 965                        "your model: %s" % sub_name
 966                    )
 967                    print("Keeping first pointer: %s" % original_sub_name)
 968                    print("Skipping duplicate pointer: %s" % sub_name)
 969                    print(
 970                        "If you prefer to keep %s and skip %s, add %s to module_names_to_not_save before convert."
 971                        % (sub_name, original_sub_name, original_sub_name)
 972                    )
 973                    if not config_setup:
 974                        GPA.pc.append_module_names_to_not_save([sub_name])
 975                    continue
 976                converted_list += [id(member_obj)]
 977                converted_names_list += [sub_name]
 978            if _id_to_track(sub_name):
 979                if GPA.pc.get_verbose():
 980                    print("Seq ID is in track IDs: %s" % sub_name)
 981                if tracked_module_class is None:
 982                    continue
 983                if config_setup:
 984                    getattr(net, member).pai_mode = "tracked"
 985                else:
 986                    setattr(
 987                        net, member, tracked_module_class(getattr(net, member), sub_name)
 988                    )
 989                continue
 990            if _id_to_perforate(sub_name):
 991                if GPA.pc.get_verbose():
 992                    print("Seq ID is in convert IDs: %s" % sub_name)
 993                if config_setup:
 994                    getattr(net, member).pai_mode = "perforated"
 995                else:
 996                    setattr(
 997                        net, member, neuron_module_class(getattr(net, member), sub_name)
 998                    )
 999                continue
1000            if id(getattr(net, member, None)) == id(net):
1001                if GPA.pc.get_verbose():
1002                    print("member sub is a self pointer: %s" % sub_name)
1003                continue
1004            if sub_name in GPA.pc.get_module_names_to_not_save():
1005                if GPA.pc.get_verbose():
1006                    print("Skipping %s during convert" % sub_name)
1007                else:
1008                    if sub_name == ".base_model":
1009                        print(
1010                            "By default skipping base_model. See "
1011                            '"Safetensors Errors" section of '
1012                            "customization.md to include it."
1013                        )
1014                continue
1015            if type(getattr(net, member, None)) in GPA.pc.get_modules_to_replace():
1016                if GPA.pc.get_verbose():
1017                    print("sub is in replacement module so replacing: %s" % sub_name)
1018                if config_setup:
1019                    getattr(net, member).pai_mode = "replaced"
1020                else:
1021                    setattr(
1022                        net, member, replace_predefined_modules(getattr(net, member, None))
1023                    )
1024            if (
1025                type(getattr(net, member, None)) in GPA.pc.get_modules_to_track()
1026                or type(getattr(net, member, None)).__name__
1027                in GPA.pc.get_module_names_to_track()
1028                or sub_name in GPA.pc.get_module_ids_to_track()
1029            ):
1030                if GPA.pc.get_verbose():
1031                    print(
1032                        "sub is in tracking list so initiating tracked for: %s"
1033                        % sub_name
1034                    )
1035                if tracked_module_class is None:
1036                    continue
1037                if config_setup:
1038                    getattr(net, member).pai_mode = "tracked"
1039                else:
1040                    setattr(
1041                        net, member, tracked_module_class(getattr(net, member), sub_name)
1042                    )
1043            elif (
1044                type(getattr(net, member, None)) in GPA.pc.get_modules_to_perforate()
1045                or type(getattr(net, member, None)).__name__
1046                in GPA.pc.get_module_names_to_perforate()
1047                or (sub_name in GPA.pc.get_module_ids_to_perforate())
1048            ):
1049                if GPA.pc.get_verbose():
1050                    print(
1051                        "sub is in conversion list so initiating PAI for: %s" % sub_name
1052                    )
1053                if config_setup:
1054                    getattr(net, member).pai_mode = "perforated"
1055                else:
1056                    setattr(
1057                        net,
1058                        member,
1059                        neuron_module_class(getattr(net, member), sub_name),
1060                    )
1061            elif (
1062                issubclass(type(getattr(net, member, None)), nn.Module)
1063                or issubclass(type(getattr(net, member, None)), nn.Sequential)
1064                or issubclass(type(getattr(net, member, None)), nn.ModuleList)
1065            ):
1066                if net != getattr(net, member):
1067                    if GPA.pc.get_verbose():
1068                        print(
1069                            "sub is module but in no lists so going deeper: %s"
1070                            % sub_name
1071                        )
1072                    setattr(
1073                        net,
1074                        member,
1075                        convert_module(
1076                            getattr(net, member),
1077                            depth + 1,
1078                            sub_name,
1079                            converted_list,
1080                            converted_names_list,
1081                            neuron_module_class,
1082                            tracked_module_class,
1083                            config_setup,
1084                        ),
1085                    )
1086            if (
1087                issubclass(
1088                    type(getattr(net, member, None)),
1089                    torch.nn.modules.batchnorm._BatchNorm,
1090                )
1091                or issubclass(
1092                    type(getattr(net, member, None)),
1093                    torch.nn.modules.instancenorm._InstanceNorm,
1094                )
1095                or issubclass(
1096                    type(getattr(net, member, None)),
1097                    torch.nn.modules.normalization.LayerNorm,
1098                )
1099            ):
1100                if not GPA.pc.get_unwrapped_modules_confirmed():
1101                    print(
1102                        "potentially found a norm Layer that "
1103                        "is not accounted for, this is not recommended: %s" % (sub_name)
1104                    )
1105                    print(
1106                        "Set GPA.pc.set_unwrapped_modules_confirmed(True) to skip "
1107                        "this next time only if you are unable to debug"
1108                    )
1109                    print(
1110                        "inspect your network to "
1111                        "see what the module type containing this layer is."
1112                    )
1113                    print("Then do one of the following:")
1114                    print(
1115                        " - Add the module type to "
1116                        "GPA.pc.get_module_names_to_perforate() to wrap it entirely"
1117                    )
1118                    print(
1119                        " - If the norm layer is part of a sequential wrap "
1120                        "it and the previous layer in a PAISequential"
1121                    )
1122                    print(
1123                        " - If you do not want to add dendrites to this "
1124                        "module add the type to GPA.pc.get_module_names_to_track()"
1125                    )
1126                    pdb.set_trace()
1127            else:
1128                if GPA.pc.get_verbose():
1129                    if member[0] != "_" or GPA.pc.get_extra_verbose() is True:
1130                        print("not calling convert on %s depth %d" % (member, depth))
1131    if GPA.pc.get_verbose():
1132        print("returning from call to: %s" % (name_so_far))
1133    return net
1134
1135
1136def convert_network(net, layer_name=""):
1137    """Function that calls convert_module and checks results
1138
1139    Parameters
1140    ----------
1141    net : nn.Module
1142        The network to convert.
1143    layer_name : str, optional
1144        The name of the layer if converting a single layer, by default ""
1145
1146    Returns
1147    -------
1148    nn.Module
1149        The converted network.
1150
1151    """
1152    if GPA.pc.get_perforated_backpropagation():
1153        UPB.initialize_pb()
1154    PA.set_main_parameters(net)
1155    if type(net) in GPA.pc.get_modules_to_replace():
1156        net = replace_predefined_modules(net)
1157    if (type(net) in GPA.pc.get_modules_to_perforate()) or (
1158        type(net).__name__ in GPA.pc.get_module_names_to_perforate()
1159    ):
1160        if layer_name == "":
1161            print(
1162                "converting a single layer without a name, add a "
1163                "layer_name param to the call"
1164            )
1165            sys.exit(-1)
1166        net = PA.PAINeuronModule(net, layer_name)
1167    else:
1168        net = convert_module(
1169            net, 0, "", [], [], PA.PAINeuronModule, PA.TrackedNeuronModule
1170        )
1171        _warn_unused_block_rules()
1172    if GPA.pai_tracker.member_vars["doing_pai"]:
1173        missed_ones = []
1174        tracked_ones = []
1175        for name, param in net.named_parameters():
1176            wrapped = "wrapped" in param.__dir__()
1177            if wrapped:
1178                if GPA.pc.get_verbose():
1179                    print("param %s is now wrapped" % (name))
1180            else:
1181                tracked = "tracked" in param.__dir__()
1182                if tracked:
1183                    tracked_ones.append(name)
1184                else:
1185                    missed_ones.append(name)
1186        if (
1187            len(missed_ones) != 0 or len(tracked_ones) != 0
1188        ) and GPA.pc.get_unwrapped_modules_confirmed() is False:
1189            print(
1190                "\n------------------------------------------------------------------"
1191            )
1192            print(
1193                "%d params are not wrapped, %d params are not tracked or wrapped."
1194                % (len(tracked_ones), len(missed_ones))
1195            )
1196            if GPA.pc.get_verbose():
1197                print(
1198                    "------------------------------------------------------------------"
1199                )
1200                print(
1201                    "The following params are not wrapped.\n------------------------------------------------------------------"
1202                )
1203                for name in tracked_ones:
1204                    print("." + name)
1205                print(
1206                    "\n------------------------------------------------------------------"
1207                )
1208                print(
1209                    "The following params are not tracked or wrapped.\n------------------------------------------------------------------"
1210                )
1211                for name in missed_ones:
1212                    print("." + name)
1213            print(
1214                "\n------------------------------------------------------------------"
1215            )
1216            print(
1217                "Modules that are not wrapped will not have Dendrites to optimize them"
1218            )
1219            print(
1220                "Modules modules that are not tracked can cause errors and is NOT recommended"
1221            )
1222            print(
1223                "Any modules in the second list should be added to module_names_to_track"
1224            )
1225
1226            print(
1227                "Set GPA.pc.set_unwrapped_modules_confirmed(True) to skip this next time"
1228            )
1229            print(
1230                "Inspect your network and see what the module types of these values are to add them to PGB.module_names_to_perforate"
1231            )
1232            # If did miss some then set trace to debug
1233            if len(missed_ones) != 0:
1234                print(
1235                    "------------------------------------------------------------------\nType 'c' + enter to continue the run to confirm you do not want them to be refined"
1236                )
1237
1238                pdb.set_trace()
1239                print("confirmed")
1240    net.register_buffer(
1241        "tracker_string",
1242        torch.tensor([], dtype=torch.uint8, device=next((p.device for p in net.parameters()), None)),
1243    )
1244    return net
1245
1246
1247def string_to_tensor(string):
1248    """Helper function to convert a layer_tracker into a string
1249
1250    This is required for safetensors saving
1251
1252    Parameters
1253    ----------
1254    string : str
1255        The string to convert.
1256
1257    Returns
1258    -------
1259    torch.Tensor
1260        The converted tensor.
1261
1262    """
1263    ords = list(map(ord, string))
1264    ords = torch.tensor(ords, dtype=torch.uint8)
1265    return ords
1266
1267
1268def string_from_tensor(string_tensor):
1269    """Convert a tensor back into a string
1270
1271    Parameters
1272    ----------
1273    string_tensor : torch.Tensor
1274        The tensor to convert.
1275
1276    Returns
1277    -------
1278    str
1279        The converted string.
1280
1281    """
1282    ords = string_tensor.tolist()
1283    to_return = ""
1284    # Doing block processing like this helps with memory errors
1285    while len(ords) != 0:
1286        remaining_ords = ords[100000:]
1287        ords = ords[:100000]
1288        to_append = "".join(map(chr, ords))
1289        to_return = to_return + to_append
1290        ords = remaining_ords
1291    return to_return
1292
1293
1294def save_system(net, folder, name):
1295    """Save the entire system
1296
1297    This saves the network itself as well as the tracker information
1298
1299    Parameters
1300    ----------
1301    net : nn.Module
1302        The network to save.
1303    folder : str
1304        The folder to save the network in.
1305    name : str
1306        The name to save the network under.
1307
1308    Returns
1309    -------
1310    None
1311
1312    """
1313    if GPA.pc.get_verbose():
1314        print("saving system %s" % name)
1315    temp = string_to_tensor(GPA.pai_tracker.to_string())
1316    if hasattr(net, "tracker_string"):
1317        net.tracker_string = string_to_tensor(GPA.pai_tracker.to_string()).to(
1318            next(net.parameters()).device
1319        )
1320    else:
1321        net.register_buffer(
1322            "tracker_string",
1323            string_to_tensor(GPA.pai_tracker.to_string()).to(
1324                next(net.parameters()).device
1325            ),
1326        )
1327    # Before saving the tracker must be cleared to not contain pointers to the
1328    # models modules
1329    old_list = GPA.pai_tracker.neuron_module_vector
1330    GPA.pai_tracker.neuron_module_vector = []
1331    save_net(net, folder, name)
1332    GPA.pai_tracker.neuron_module_vector = old_list
1333    pai_save_system(net, folder, name)
1334
1335
1336def load_system(
1337    net,
1338    folder,
1339    name,
1340    load_from_restart=False,
1341    switch_call=False,
1342    load_from_manual_save=False,
1343    reset_best_scores=True,
1344):
1345    """Load the entire system
1346
1347    This is what should be used to load a saved system and restart training
1348
1349    Parameters
1350    ----------
1351    net : nn.Module
1352        The network to load into.
1353    folder : str
1354        The folder to load the network from.
1355    name : str
1356        The name to load the network from.
1357    load_from_restart : bool, optional
1358        Whether this is being loaded from an automatic restart, by default False
1359    switch_call : bool, optional
1360        Whether this is being called from a switch, by default False
1361    load_from_manual_save : bool, optional
1362        Whether this is being loaded from a manual save, by default False
1363    reset_best_scores : bool, optional
1364        Whether to clear current_best_validation_score and restart
1365        epoch_last_improved at the loaded epoch, by default True. Pass False
1366        to keep the values saved in the checkpoint.
1367
1368    Returns
1369    -------
1370    nn.Module
1371        The loaded network.
1372
1373    Notes
1374    -----
1375    If you manually call save_system then load_from_manual_save should be True
1376
1377    """
1378    if GPA.pc.get_verbose():
1379        print("loading system %s" % name)
1380    if not switch_call and not load_from_manual_save:
1381        print("Loading system %s (user initiated)" % name)
1382    net = load_net(net, folder, name)
1383    GPA.pai_tracker.reset_module_vector(net, load_from_restart)
1384
1385    GPA.pai_tracker.from_string(string_from_tensor(net.tracker_string))
1386    GPA.pai_tracker.saved_time = time.time()
1387    GPA.pai_tracker.loaded = True
1388    if reset_best_scores:
1389        GPA.pai_tracker.member_vars["current_best_validation_score"] = 0
1390        GPA.pai_tracker.member_vars["epoch_last_improved"] = GPA.pai_tracker.member_vars[
1391            "num_epochs_run"
1392        ]
1393    if GPA.pc.get_verbose():
1394        print(
1395            "after loading epoch last improved is %d mode is %c"
1396            % (
1397                GPA.pai_tracker.member_vars["epoch_last_improved"],
1398                GPA.pai_tracker.member_vars["mode"],
1399            )
1400        )
1401
1402    # Saves always take place before the call to start_epoch so call it here
1403    # when loading to correct off by 1 problems
1404    if (not switch_call) and (not load_from_manual_save):
1405        GPA.pai_tracker.start_epoch(internal_call=True)
1406    return net
1407
1408
1409def load_pretrained_model(
1410    net,
1411    folder,
1412    name,
1413    remove_dendrite_scaffolding=False,
1414):
1415    """Load a pretrained perforated model and reset tracker for fresh training.
1416
1417    This function loads a pretrained model's weights and dendrite structure while
1418    resetting all tracker state (epochs, switch history, etc.) to start training
1419    from scratch on a new task. This is useful for transfer learning where you want
1420    pretrained weights but need fresh training dynamics.
1421
1422    Parameters
1423    ----------
1424    net : nn.Module
1425        The network to load into.
1426    folder : str
1427        The folder containing the pretrained model.
1428    name : str
1429        The name of the checkpoint to load (e.g., 'best_model', 'beforeSwitch_0').
1430    remove_dendrite_scaffolding : bool, optional
1431        If True, removes dendrite scaffolding for inference or finetuning without
1432        adding more dendrites using blockwise_network and refresh_net. Default False.
1433
1434    Returns
1435    -------
1436    nn.Module
1437        The loaded network with reset tracker state.
1438
1439    Examples
1440    --------
1441    Load pretrained weights for continued dendrite training:
1442    >>> model = load_pretrained_model(model, "pretrained-prefc", "beforeSwitch_0")
1443
1444    Load pretrained weights for finetuning without adding more dendrites:
1445    >>> model = load_pretrained_model(model, "pretrained-prefc", "best_model", 
1446    ...                               remove_dendrite_scaffolding=True)
1447
1448    Notes
1449    -----
1450    This function:
1451    - Loads model weights and dendrite structure from checkpoint
1452    - Resets all epoch counters to -1 (will become 0 after first start_epoch)
1453    - Resets switch history and validation score tracking
1454    - Clears accuracy/loss history arrays
1455    - Optionally removes dendrite scaffolding (no more dendrite additions)
1456    
1457    The tracker is reset to behave as if starting fresh training, while keeping
1458    the learned weights and dendrite structure from the pretrained model.
1459    """
1460    from perforatedai import globals_perforatedai as GPA
1461    
1462    if GPA.pc.get_verbose():
1463        print(f"Loading pretrained model from {folder}/{name}")
1464    
1465    # Load the model weights and dendrite structure
1466    net = load_system(net, folder, name, load_from_manual_save=True)
1467    
1468    if GPA.pc.get_verbose():
1469        print("Resetting tracker state for fresh training...")
1470    
1471    # Reset structural training state to true initial values.
1472    # Keeping pretrained architecture/weights while zeroing cycle counters avoids
1473    # stale dendrite bookkeeping referencing empty score buffers.
1474    GPA.pai_tracker.reset_module_vector(net, load_from_restart=True)
1475    GPA.pai_tracker.member_vars["mode"] = "n"
1476    GPA.pai_tracker.member_vars["num_dendrites_added"] = 0
1477    GPA.pai_tracker.member_vars["num_dendrites_integrated"] = 0
1478    GPA.pai_tracker.member_vars["num_cycles"] = 0
1479    GPA.pai_tracker.member_vars["num_dendrite_tries"] = 0
1480    GPA.pai_tracker.member_vars["current_n_set_global_best"] = True
1481
1482    # Reset epoch counters
1483    GPA.pai_tracker.member_vars["num_epochs_run"] = -1
1484    GPA.pai_tracker.member_vars["total_epochs_run"] = -1
1485    GPA.pai_tracker.member_vars["epoch_last_improved"] = 0
1486    GPA.pai_tracker.member_vars["last_switch"] = 0
1487    GPA.pai_tracker.member_vars["manual_train_switch"] = False
1488    
1489    # Reset switch history
1490    GPA.pai_tracker.member_vars["switch_epochs"] = []
1491    GPA.pai_tracker.member_vars["n_switch_epochs"] = []
1492    GPA.pai_tracker.member_vars["p_switch_epochs"] = []
1493    GPA.pai_tracker.member_vars["param_counts"] = []
1494    
1495    # Reset validation scores and tracking
1496    GPA.pai_tracker.member_vars["current_best_validation_score"] = 0
1497    GPA.pai_tracker.member_vars["global_best_validation_score"] = 0
1498    GPA.pai_tracker.member_vars["running_accuracy"] = 0
1499    
1500    # Clear accuracy/loss history arrays
1501    GPA.pai_tracker.member_vars["accuracies"] = []
1502    GPA.pai_tracker.member_vars["last_improved_accuracies"] = []
1503    GPA.pai_tracker.member_vars["test_accuracies"] = []
1504    GPA.pai_tracker.member_vars["n_accuracies"] = []
1505    GPA.pai_tracker.member_vars["p_accuracies"] = []
1506    GPA.pai_tracker.member_vars["running_accuracies"] = []
1507    GPA.pai_tracker.member_vars["training_loss"] = []
1508    GPA.pai_tracker.member_vars["training_learning_rates"] = []
1509    GPA.pai_tracker.member_vars["test_scores"] = []
1510    
1511    # Clear extra scores
1512    GPA.pai_tracker.member_vars["extra_scores"] = {}
1513    GPA.pai_tracker.member_vars["extra_scores_without_graphing"] = {}
1514    GPA.pai_tracker.member_vars["n_extra_scores"] = {}
1515    
1516    # Keep per-layer dendrite score buffers initialized by reset_module_vector.
1517    
1518    # Clear timing arrays
1519    GPA.pai_tracker.member_vars["n_epoch_times"] = []
1520    GPA.pai_tracker.member_vars["p_epoch_times"] = []
1521    GPA.pai_tracker.member_vars["n_train_times"] = []
1522    GPA.pai_tracker.member_vars["p_train_times"] = []
1523    GPA.pai_tracker.member_vars["n_val_times"] = []
1524    GPA.pai_tracker.member_vars["p_val_times"] = []
1525    
1526    # Clear overwritten tracking
1527    GPA.pai_tracker.member_vars["overwritten_extras"] = []
1528    GPA.pai_tracker.member_vars["overwritten_vals"] = []
1529    GPA.pai_tracker.member_vars["overwritten_epochs"] = 0
1530    
1531    # Reset learning rate search state
1532    GPA.pai_tracker.member_vars["initial_lr_test_epoch_count"] = -1
1533    GPA.pai_tracker.member_vars["current_n_learning_rate_initial_skip_steps"] = 0
1534    GPA.pai_tracker.member_vars["last_max_learning_rate_steps"] = 0
1535    GPA.pai_tracker.member_vars["last_max_learning_rate_value"] = -1
1536    GPA.pai_tracker.member_vars["current_cycle_lr_max_scores"] = []
1537    GPA.pai_tracker.member_vars["current_step_count"] = 0
1538    GPA.pai_tracker.member_vars["committed_to_initial_rate"] = True
1539    GPA.pai_tracker.member_vars["best_mean_score_improved_this_epoch"] = 0
1540    GPA.pai_tracker.member_vars["step_status"] = TPA.STEP_CLEARED
1541    
1542    # Reset saved time
1543    GPA.pai_tracker.start_time = time.time()
1544    GPA.pai_tracker.saved_time = 0
1545
1546    # Match tracker initialization behavior so first validation uses epoch 0.
1547    GPA.pai_tracker.start_epoch(internal_call=True)
1548    
1549    if GPA.pc.get_verbose():
1550        print(
1551            f"Tracker reset complete. Dendrites: {GPA.pai_tracker.member_vars['num_dendrites_integrated']}, "
1552            f"Mode: {GPA.pai_tracker.member_vars['mode']}"
1553        )
1554    
1555    # Optionally remove dendrite scaffolding
1556    if remove_dendrite_scaffolding:
1557        if GPA.pc.get_verbose():
1558            print("Removing dendrite scaffolding (no dendrite additions)...")
1559        
1560        from perforatedai import blockwise_perforatedai as BPA
1561        from perforatedai import clean_perforatedai as CPA
1562        
1563        net = BPA.blockwise_network(net)
1564        net = CPA.refresh_net(net)
1565        
1566        if GPA.pc.get_verbose():
1567            print("Dendrite scaffolding removed. Model ready for inference or finetuning.")
1568    
1569    return net
1570
1571
1572import json
1573from collections import defaultdict
1574from safetensors.torch import save_file, safe_open
1575import torch
1576
1577
1578def save_model_with_weight_tying(model, filepath):
1579    """Save model with safetensors while handling weight tying automatically
1580
1581    Parameters
1582    ----------
1583    model : Any PyTorch Module.
1584    filepath : Path to filename.
1585
1586    Returns
1587    -------
1588    dict[str, str]
1589        Mapping from secondary parameter keys to their primary tied key.
1590    """
1591    state_dict = model.state_dict()
1592
1593    # Find all weight tied parameters
1594    tensor_to_keys = defaultdict(list)
1595    for key, tensor in state_dict.items():
1596        # Use tensor data pointer as unique identifier
1597        tensor_id = tensor.data_ptr()
1598        tensor_to_keys[tensor_id].append(key)
1599
1600    # Find tied weights (tensors referenced by multiple keys)
1601    tied_weights = {}
1602    keys_to_remove = set()
1603    for tensor_id, keys in tensor_to_keys.items():
1604        if len(keys) > 1 and not tensor_id == 0:
1605            # Multiple keys reference the same tensor - this is weight tying
1606            # Sort keys for deterministic ordering
1607            keys = sorted(keys)
1608            primary_key = keys[0]  # Keep the first key
1609            for secondary_key in keys[1:]:
1610                tied_weights[secondary_key] = primary_key
1611                keys_to_remove.add(secondary_key)
1612
1613    # Remove tied weights from state_dict (keep only primary references)
1614    filtered_state_dict = {
1615        k: v for k, v in state_dict.items() if k not in keys_to_remove
1616    }
1617
1618    # Create metadata for weight tying information
1619    metadata = {}
1620    if tied_weights:
1621        # Store weight tying info as JSON string in metadata
1622        metadata["weight_tying"] = json.dumps(tied_weights)
1623    save_file(filtered_state_dict, filepath, metadata=metadata)
1624    print(f"Saved model with {len(tied_weights)} weight tying relationships")
1625    return tied_weights
1626
1627
1628def load_model_with_weight_tying(model, filepath):
1629    """Load model from safetensors while restoring weight tying
1630
1631    Parameters
1632    ----------
1633    model : Any PyTorch module.
1634    filepath : Path to model file.
1635
1636    Returns
1637    -------
1638    Loaded model.
1639    """
1640    with safe_open(filepath, framework="pt") as f:
1641        metadata = f.metadata()
1642        state_dict = {key: f.get_tensor(key) for key in f.keys()}
1643
1644    # Restore weight tying if metadata exists
1645    tied_weights = {}
1646    if metadata and "weight_tying" in metadata:
1647        tied_weights = json.loads(metadata["weight_tying"])
1648        for secondary_key, primary_key in tied_weights.items():
1649            if primary_key in state_dict:
1650                # Restore the tied reference
1651                state_dict[secondary_key] = state_dict[primary_key]
1652                print(f"Restored weight tying: {secondary_key} -> {primary_key}")
1653
1654    # Handle tracker_string loading with flexible key matching
1655    tracker_key = None
1656    if "tracker_string" in state_dict:
1657        tracker_key = "tracker_string"
1658    else:
1659        # Search for keys containing "tracker_string"
1660        tracker_keys = [key for key in state_dict.keys() if "tracker_string" in key]
1661        if len(tracker_keys) == 1:
1662            tracker_key = tracker_keys[0]
1663        elif len(tracker_keys) > 1:
1664            print(f"Error: Multiple tracker_string keys found: {tracker_keys}")
1665            pdb.set_trace()
1666        else:
1667            print("Error: No tracker_string found in state_dict")
1668
1669    if tracker_key is not None and hasattr(model, "tracker_string"):
1670        model.tracker_string = state_dict[tracker_key]
1671
1672    model.load_state_dict(state_dict)
1673    return model
1674
1675
1676def _save_file_deduped(state_dict, filepath):
1677    """Save a state dict via safetensors, deduplicating shared-memory tensors.
1678
1679    Shared-memory tensors (weight-tied parameters) are detected by data_ptr().
1680    Only the alphabetically-first key is written to disk; the rest are recorded
1681    in the file's metadata so they can be restored transparently on load.
1682    """
1683    tensor_to_keys = defaultdict(list)
1684    for key, tensor in state_dict.items():
1685        tensor_id = tensor.data_ptr()
1686        tensor_to_keys[tensor_id].append(key)
1687
1688    tied_weights = {}
1689    keys_to_remove = set()
1690    for tensor_id, keys in tensor_to_keys.items():
1691        if len(keys) > 1 and tensor_id != 0:
1692            sorted_keys = sorted(keys)
1693            primary_key = sorted_keys[0]
1694            for secondary_key in sorted_keys[1:]:
1695                tied_weights[secondary_key] = primary_key
1696                keys_to_remove.add(secondary_key)
1697
1698    filtered = {k: v for k, v in state_dict.items() if k not in keys_to_remove}
1699    if tied_weights:
1700        save_file(filtered, filepath, metadata={"weight_tying": json.dumps(tied_weights)})
1701    else:
1702        save_file(filtered, filepath)
1703
1704
1705def save_net(net, folder, name):
1706    """Save the network
1707
1708    This is called within save_system after the tracker has been
1709    turned into a single tensor to be saved as a part of the network
1710
1711    Parameters
1712    ----------
1713    net : nn.Module
1714        The network to save.
1715    folder : str
1716        The folder to save the network in.
1717    name : str
1718        The name to save the network under.
1719
1720    Returns
1721    -------
1722    None
1723
1724    """
1725    # If running a DDP only save with first thread
1726    if "RANK" in os.environ:
1727        if int(os.environ["RANK"]) != 0:
1728            return
1729    if not os.path.isdir(folder):
1730        os.makedirs(folder)
1731    save_point = folder + "/"
1732    if not os.path.isdir(save_point):
1733        os.mkdir(save_point)
1734    for param in net.parameters():
1735        param.data = param.data.contiguous()
1736    if GPA.pc.get_using_safe_tensors():
1737        # Strip the . so that the naming is the same for everywhere but it works with state_dict naming
1738        not_save = [ns.lstrip('.') for ns in GPA.pc.get_module_names_to_not_save()]
1739        state_dict = {k: v for k, v in net.state_dict().items()
1740                      if not any(k.startswith(ns) for ns in not_save)}
1741        _save_file_deduped(state_dict, save_point + name + ".pt")
1742    else:
1743        torch.save(net, save_point + name + ".pt")
1744
1745
1746def save_pai_net(net, folder, name):
1747    """Save the final pai network
1748
1749    This can be called after training to save the final network
1750    with all scaffolding removed so only the refined weights remain
1751
1752    Parameters
1753    ----------
1754    net : nn.Module
1755        The network to save.
1756    folder : str
1757        The folder to save the network in.
1758    name : str
1759        The name to save the network under.
1760
1761    Returns
1762    -------
1763    None
1764
1765    """
1766    # if running a DDP only save with first thread
1767    if "RANK" in os.environ:
1768        if int(os.environ["RANK"]) != 0:
1769            return
1770
1771    # print('calling save: %s' % name)
1772    # GPA.pai_tracker.archive_layer()
1773    # These deep copys are required or the real model will also have its layers replaced
1774    net = prepare_final_model(net)
1775    if not os.path.isdir(folder):
1776        os.makedirs(folder)
1777    save_point = folder + "/"
1778    if not os.path.isdir(save_point):
1779        os.mkdir(save_point)
1780
1781    if GPA.pc.get_using_safe_tensors():
1782        _save_file_deduped(net.state_dict(), save_point + name + "_pai.pt")
1783    else:
1784        torch.save(net, save_point + name + "_pai.pt")
1785
1786
1787def save_pai_net(net, folder, name):
1788    """Save the final pai network
1789
1790    This can be called after training to save the final network
1791    with all scaffolding removed so only the refined weights remain
1792
1793    Parameters
1794    ----------
1795    net : nn.Module
1796        The network to save.
1797    folder : str
1798        The folder to save the network in.
1799    name : str
1800        The name to save the network under.
1801
1802    Returns
1803    -------
1804    None
1805
1806    """
1807    # if running a DDP only save with first thread
1808    if "RANK" in os.environ:
1809        if int(os.environ["RANK"]) != 0:
1810            return
1811
1812    # print('calling save: %s' % name)
1813    # GPA.pai_tracker.archive_layer()
1814    # These deep copys are required or the real model will also have its layers replaced
1815    net = prepare_final_model(net)
1816    if not os.path.isdir(folder):
1817        os.makedirs(folder)
1818    save_point = folder + "/"
1819    if not os.path.isdir(save_point):
1820        os.mkdir(save_point)
1821
1822    if GPA.pc.get_using_safe_tensors():
1823        _save_file_deduped(net.state_dict(), save_point + name + "_pai.pt")
1824    else:
1825        torch.save(net, save_point + name + "_pai.pt")
1826
1827
1828def manual_load_state_dict(model, state_dict):
1829    """Load a state dict into a model key-by-key with relaxed checks.
1830
1831    Parameters
1832    ----------
1833    model : nn.Module
1834        Model receiving parameters.
1835    state_dict : dict
1836        Source parameter dictionary.
1837
1838    Notes
1839    -----
1840    Keys configured in ``module_names_to_not_save`` are skipped.
1841
1842    Returns
1843    -------
1844    None
1845        This function does not return a value.
1846    """
1847    own_state = model.state_dict()
1848    not_save = [ns.lstrip('.') for ns in GPA.pc.get_module_names_to_not_save()]
1849    for name, param in state_dict.items():
1850        if any(name.startswith(ns) for ns in not_save):
1851            print("skipping loading %s based on module_names_to_not_save" % name)
1852            continue
1853        if name not in own_state:
1854            print(f"Warning: {name} not found in model state_dict")
1855            continue
1856        if isinstance(param, torch.nn.Parameter):
1857            # Backwards compatibility for serialized parameters
1858            param = param.data
1859        try:
1860            own_state[name].copy_(param)
1861        except Exception as e:
1862            print(f"Error loading {name}: {e}")
1863    print("Manual load complete")
1864
1865
1866def load_net(net, folder, name):
1867    """load the network
1868
1869    This is called within load_system after the tracker has been
1870    loaded
1871
1872    Parameters
1873    ----------
1874    net : nn.Module
1875        The network to save.
1876    folder : str
1877        The folder to save the network in.
1878    name : str
1879        The name to save the network under.
1880
1881    Returns
1882    -------
1883    nn.Module
1884        The loaded network.
1885
1886    """
1887    save_point = folder + "/"
1888    if GPA.pc.get_using_safe_tensors():
1889        model_path = save_point + name + ".pt"
1890        state_dict = load_file(model_path)
1891        try:
1892            with safe_open(model_path, framework="pt") as f:
1893                metadata = f.metadata()
1894            if metadata and "weight_tying" in metadata:
1895                tied_weights = json.loads(metadata["weight_tying"])
1896                for secondary_key, primary_key in tied_weights.items():
1897                    if primary_key in state_dict:
1898                        state_dict[secondary_key] = state_dict[primary_key]
1899        except Exception:
1900            pass
1901    else:
1902        # Try three different torch.load call signatures for compatibility across
1903        # different PyTorch versions.  All three are attempted before giving up so
1904        # the user can see every error at once and decide how to fix the file.
1905        error_weights_only_false = None
1906        error_no_weights_only    = None
1907        error_no_state_dict      = None
1908
1909        try:
1910            state_dict = torch.load(
1911                save_point + name + ".pt",
1912                map_location=torch.device("cpu"),
1913                weights_only=False,
1914            ).state_dict()
1915        except Exception as caught_error:
1916            error_weights_only_false = caught_error
1917
1918        if error_weights_only_false is not None:
1919            try:
1920                state_dict = torch.load(
1921                    save_point + name + ".pt",
1922                    map_location=torch.device("cpu"),
1923                ).state_dict()
1924            except Exception as caught_error:
1925                error_no_weights_only = caught_error
1926
1927        if error_no_weights_only is not None:
1928            try:
1929                state_dict = torch.load(
1930                    save_point + name + ".pt",
1931                    map_location=torch.device("cpu"),
1932                )
1933            except Exception as caught_error:
1934                error_no_state_dict = caught_error
1935
1936        if error_no_state_dict is not None:
1937            separator = "\n" + "=" * 60 + "\n"
1938            print(separator.join([
1939                "\nAll four load attempts failed for: " + save_point + name + ".pt",
1940                "Attempt 1 (weights_only=False, .state_dict()):\n"      + str(error_weights_only_false),
1941                "Attempt 2 (default weights_only, .state_dict()):\n"    + str(error_no_weights_only),
1942                "Attempt 3 (default weights_only, no .state_dict()):\n" + str(error_no_state_dict),
1943                "You must find a way to fix at least one of the above errors to load successfully.\n",
1944                "Suggested problems to look into:\n",
1945                "1 - Modules which have member variables that are methods, which cant be pickled.  See __setstate__ and __getstate__ functions to append."
1946            ]))
1947            raise error_no_state_dict
1948    return load_net_from_dict(net, state_dict)
1949
1950def get_module_base_name(module):
1951    """Normalize a wrapped module name for state-dict key lookup.
1952
1953    Parameters
1954    ----------
1955    module : nn.Module
1956        Module containing a ``name`` attribute.
1957
1958    Returns
1959    -------
1960    str
1961        Base name with leading dot and optional ``module.`` prefix removed.
1962    """
1963    module_name = module.name
1964    # This should always be true
1965    if module_name[0] == ".":
1966        # strip "."
1967        module_name = module_name[1:]
1968    # If it was a dataparallel it will also have a module at the start
1969    # so strip that for loading
1970    if module_name[:6] == "module":
1971        module_name = module_name[7:]
1972    return module_name
1973
1974
1975def load_net_from_dict(net, state_dict):
1976    """load the network
1977
1978    This is called within load_net
1979
1980    Parameters
1981    ----------
1982    net : nn.Module
1983        The network to save.
1984    state_dict : dict
1985        The state dictionary to load.
1986
1987    Returns
1988    -------
1989    nn.Module
1990        The loaded network.
1991
1992    """
1993    if GPA.pc.get_verbose():
1994        print("loading net from dict")
1995    pai_modules = get_pai_modules(net, 0)
1996    if pai_modules == []:
1997        print(
1998            "PAI load_net and load_system uses a state_dict so it must be\n"
1999            "called with a net after perforate_model has been called"
2000        )
2001        print(
2002            "This is being flagged because you are attempting to load a model\n"
2003            "that does not have any pai_modules in it.  Confirm that you are calling\n"
2004            "perforate_model on the correct model, and the same model is the one\n"
2005            "being passed into add_validation_score"
2006        )
2007        import pdb # This needs to be here for cython for some reason.
2008        pdb.set_trace()
2009        sys.exit(-1)
2010    if GPA.pc.get_verbose():
2011        print(
2012            "setting up arrays and simulating cycles for %d pai modules"
2013            % len(pai_modules)
2014        )
2015    not_save = GPA.pc.get_module_names_to_not_save()
2016    for module in pai_modules:
2017        if any(module.name.startswith(ns) for ns in not_save):
2018            print("skipping loading %s based on module_names_to_not_save" % module.name)
2019            continue
2020        # Set up name to be what will be saved in the state dict
2021        module_name = get_module_base_name(module)
2022        module.clear_dendrites()
2023        for tracker in module.dendrite_module.dendrite_values:
2024            try:
2025                tracker.setup_arrays(
2026                    state_dict[
2027                        module_name + ".dendrite_module.dendrite_values.0.dendrite_storage_shape"
2028                    ].tolist()
2029                )
2030            except Exception as e:
2031                print(e)
2032                first_key = next(iter(state_dict.keys()))
2033                error_msg = f"""
2034This value is missing from the state dict.
2035When missing this value it typically means you converted a module but didn't
2036actually use it in your forward and backward pass.
2037
2038Module was: {module.name}
2039
2040There are many reasons this can happen:
2041
20421 - Check your model definition and forward function and ensure this module is 
2043    being used properly.
2044    
2045    With GPA.pc.set_verbose(True) you can confirm this is the case if you do not 
2046    see a "setting d shape for" this module at the first training batch.
2047    
2048    If this is the case, and it is correct to not be passing data through it,
2049    set it to be a tracked module with:
2050    GPA.pc.append_module_ids_to_track(["{module.name}"]) to leave it out
2051
20522 - This can happen if you adjusted your model definition after calling 
2053    perforate_model (for example with torch.compile). If the module name printed 
2054    above does not contain all modules leading to the main definition, this is 
2055    likely the case for your problem. Fix by calling perforate_model after all 
2056    other model initialization steps.
2057
20583 - This can happen if the model where you called perforate_model and the model 
2059    within add_validation_score are not the same. Check if the module above and 
2060    .{first_key} have the same prefix. If one starts with .model or .base etc 
2061    and the other does not, this is the problem.
2062
20634 - If you are using this module but then not actually including the correct 
2064    output tensor in the forward. For example if you are using an LSTM and 
2065    forwarding hidden instead of output but your processors are set up to work 
2066    with output.
2067
20685 - If you are not properly calling backward at all. If this is the first module 
2069    in your network it is more likely this is the problem. One check in these 
2070    cases is to make sure you do not call an initial validation score before the 
2071    first backward call. If you do this, while testing_dendrite_capacity is True, 
2072    this error will be triggered.
2073
20746 - You have converted a module that is in a frozen part of the network and thus 
2075    no gradients are flowing.
2076
20777 - You are running multiple experiments at once with the same save_name. When 
2078    running concurrent trials be sure to add save_name=<unique_name> to 
2079    perforate_model.
2080"""
2081                print(error_msg)
2082                import pdb # This needs to be here for cython for some reason.
2083                pdb.set_trace()
2084
2085        # Perform as many cycles as the state dict has
2086        num_cycles = int(state_dict[module_name + ".dendrite_module.num_cycles"].item())
2087        if num_cycles > 0:
2088            simulate_cycles(module, num_cycles, doing_pai=True)
2089    # Handle tracker_string loading with flexible key matching
2090    tracker_key = None
2091    if "tracker_string" in state_dict:
2092        tracker_key = "tracker_string"
2093    else:
2094        # Search for keys containing "tracker_string"
2095        tracker_keys = [key for key in state_dict.keys() if "tracker_string" in key]
2096        if len(tracker_keys) == 1:
2097            tracker_key = tracker_keys[0]
2098        elif len(tracker_keys) > 1:
2099            print(f"Error: Multiple tracker_string keys found: {tracker_keys}")
2100            import pdb # This needs to be here for cython for some reason.
2101            pdb.set_trace()
2102        else:
2103            print("Error: No tracker_string found in state_dict")
2104            import pdb # This needs to be here for cython for some reason.
2105            pdb.set_trace()
2106
2107    if hasattr(net, "tracker_string"):
2108        net.tracker_string = state_dict[tracker_key]
2109    else:
2110        net.register_buffer("tracker_string", state_dict[tracker_key])
2111    try:
2112        load_result = net.load_state_dict(state_dict, strict=False)
2113        not_save_state_names = [ns.lstrip('.') for ns in not_save]
2114
2115        def is_ignored_key(key):
2116            """Check whether a state-dict key should be ignored.
2117
2118            Parameters
2119            ----------
2120            key : str
2121                State-dict key to test.
2122
2123            Returns
2124            -------
2125            bool
2126                ``True`` when key belongs to a not-saved namespace.
2127            """
2128            return any(key.startswith(ns) for ns in not_save_state_names)
2129
2130        missing_keys = [key for key in load_result.missing_keys if not is_ignored_key(key)]
2131        unexpected_keys = [key for key in load_result.unexpected_keys if not is_ignored_key(key)]
2132
2133        if GPA.pc.get_strict_loading() and (missing_keys or unexpected_keys):
2134            raise RuntimeError(
2135                "Error(s) in loading state_dict for %s:\n\tMissing key(s) in state_dict: %s. \n\tUnexpected key(s) in state_dict: %s."
2136                % (type(net).__name__, missing_keys, unexpected_keys)
2137            )
2138    except Exception as e:
2139        """
2140        When modules have high depth to them (i.e. modules within modules not number of layers)
2141        PyTorch can have trouble loading state dicts even when they are correct.
2142        This is a workaround to manually load the state dict if this happens.
2143        """
2144        filtered_net_keys = {
2145            key
2146            for key in net.state_dict().keys()
2147            if not any(key.startswith(ns.lstrip('.')) for ns in not_save)
2148        }
2149        if filtered_net_keys == set(state_dict.keys()):
2150            print("Attempting manual loading of state_dict")
2151            manual_load_state_dict(net, state_dict)
2152        else:
2153            print(f"Error loading state_dict: {e}")
2154            print("If the error is due to missing keys (e.g., from code changes), you can try:")
2155            print("  GPA.pc.set_strict_loading(False)")
2156            print("  Do not change this unless you are certain the missing keys are not important to load and are expected due to code changes or arch changes.")
2157            print("\ntype 'c' to print full state dicts\n")
2158            import pdb # This needs to be here for cython for some reason.
2159            pdb.set_trace()
2160            print("net state dict is:")
2161            print(net.state_dict())
2162            print("loaded state dict is:")
2163            print(state_dict)
2164            print(
2165                "Try to check differences.  Likely is caused by a module not "
2166                "being converted that should be or vice versa"
2167            )
2168            pdb.set_trace()
2169    net.to(GPA.pc.get_device())
2170    return net
2171
2172
2173def pai_save_system(net, folder, name):
2174    """Save the entire system with scaffolding removed
2175
2176    This is used for the final network for inference after training
2177
2178    Parameters
2179    ----------
2180    net : nn.Module
2181        The network to save.
2182    folder : str
2183        The folder to save the network in.
2184    name : str
2185        The name to save the network under.
2186
2187    Returns
2188    -------
2189    None
2190
2191    """
2192    net.member_vars = {}
2193    for member_var in GPA.pai_tracker.member_vars:
2194        if member_var == "scheduler_instance" or member_var == "optimizer_instance":
2195            continue
2196        net.member_vars[member_var] = GPA.pai_tracker.member_vars[member_var]
2197    pai_save_net(net, folder, name)
2198
2199
2200def deep_copy_pai(net):
2201    """Deep copy a PAI network
2202
2203
2204    Parameters
2205    ----------
2206    net : nn.Module
2207        The network to copy.
2208
2209    Returns
2210    -------
2211    nn.Module
2212        The copied network.
2213
2214    Notes
2215    ----
2216    This is required because processors must be cleared before calling copy
2217
2218    """
2219    # Dont check this stuff if its before the perforate_model has been called and you're just copying a regular model
2220    if(GPA.pai_tracker != []):
2221        # Clear gradients before saving the model
2222        if ((GPA.pai_tracker.member_vars["optimizer_instance"]) is not None) and (
2223            GPA.pai_tracker.member_vars["optimizer_instance"] != []
2224        ):
2225            GPA.pai_tracker.member_vars["optimizer_instance"].zero_grad()
2226        GPA.pai_tracker.clear_all_processors()
2227    return copy.deepcopy(net)
2228
2229
2230def prepare_final_model(net):
2231    """Prepare model for final save by removing scaffolding.
2232
2233    This performs all cleanup steps to convert a PAI model with scaffolding
2234    into a clean final model ready for inference or distribution.
2235
2236    Parameters
2237    ----------
2238    net : nn.Module
2239        The network to prepare.
2240
2241    Returns
2242    -------
2243    nn.Module
2244        The cleaned model with scaffolding removed.
2245    """
2246    # Deep copy and clean the model (removes scaffolding)
2247    net = deep_copy_pai(net)
2248    net = BPA.blockwise_network(net)
2249    net = deep_copy_pai(net)
2250    net = CL.refresh_net(net)
2251
2252    # Remove tracker_string (not needed for final model)
2253    if hasattr(net, "tracker_string"):
2254        del net.tracker_string
2255
2256    # Make parameters contiguous
2257    for param in net.parameters():
2258        param.data = param.data.contiguous()
2259
2260    return net
2261
2262
2263def pai_save_net(net, folder, name):
2264    """Save the entire system with scaffolding removed
2265
2266    This is called within pai_save_system after the tracker has been
2267    turned into a single tensor to be saved as a part of the network
2268
2269
2270    Parameters
2271    ----------
2272    net : nn.Module
2273        The network to save.
2274    folder : str
2275        The folder to save the network in.
2276    name : str
2277        The name to save the network under.
2278
2279    Returns
2280    -------
2281    None
2282
2283    Notes
2284    ----
2285    For open source implementation this is not as important since
2286    minimal values are already being used.
2287
2288    """
2289
2290    if GPA.pc.get_perforated_backpropagation():
2291        UPB.pb_save_net(net, folder, name)
2292    else:
2293        return
2294
2295
2296def simulate_cycles(module, num_cycles, doing_pai):
2297    """Simulate dendrite addition cycles
2298
2299    Simulate the back and forth processes of adding dendrites to build a
2300    pretrained dendrite model before loading weights.  Required for loading
2301    dendrite save files from non dendrite initial models.
2302
2303    If calling this by hand to start off a network with dendrites added,
2304    make sure to pass a single datapoint forward and backward through the network
2305    so that array sizes are initialized.
2306
2307    Parameters
2308    ----------
2309    module : PA.PAINeuronModule
2310        The module to simulate cycles on.
2311    num_cycles : int
2312        The number of cycles to simulate.
2313    doing_pai : bool
2314        Whether to actually do the simulation.
2315
2316    Returns
2317    -------
2318    None
2319
2320    """
2321
2322    check_skipped = GPA.pc.get_checked_skipped_modules()
2323    if doing_pai is False:
2324        return
2325    GPA.pc.set_checked_skipped_modules(True)
2326    mode = "n"
2327    for i in range(num_cycles):
2328        if mode == "n":
2329            module.set_mode("p")
2330            module.create_new_dendrite_module()
2331            mode = "p"
2332        else:
2333            module.set_mode("n")
2334            mode = "n"
2335    GPA.pc.set_checked_skipped_modules(check_skipped)
2336
2337
2338def count_params(net):
2339    """Count the number of parameters in the network
2340
2341    If doing perforated backpropagation this calls the PB function
2342    which does not count scaffolding parameters since the final model
2343    will not have them.
2344
2345    Parameters
2346    ----------
2347    net : nn.Module
2348        The network to count parameters in.
2349
2350    Returns
2351    -------
2352    int
2353        The number of parameters in the network.
2354
2355    """
2356    if GPA.pc.get_perforated_backpropagation():
2357        return UPB.pb_count_params(net)
2358    parameters = net.named_parameters()
2359    unique_params = {
2360        p.data_ptr(): p for name, p in parameters if "parent_module" not in name
2361    }.values()
2362    return sum(p.numel() for p in unique_params)
2363
2364
2365def change_learning_modes(net, folder, name, doing_pai):
2366    """Change between neuron and dendrite learning modes
2367
2368    High level steps for entire system to switch back and forth between
2369    neuron learning and dendrite learning
2370
2371    Parameters
2372    ----------
2373    net : nn.Module
2374        The network to change modes on.
2375    folder : str
2376        The folder to save/load the network in/from.
2377    name : str
2378        The name to save/load the network under.
2379    doing_pai : bool
2380        Whether to add dendrites when changing modes.
2381
2382    Returns
2383    -------
2384    int
2385        The number of parameters in the network.
2386
2387    Notes
2388    -----
2389    If doing_pai is False this just allows training to continue longer rather than early stopping
2390
2391    """
2392    # If not adding dendrites this just allows training to continue longer with flags
2393    # every time early stopping should be occurring
2394    if doing_pai is False:
2395        if GPA.pc.get_verbose():
2396            print(
2397                f'Not doing PAI, cycle {GPA.pai_tracker.member_vars["num_dendrites_added"] + 1} '
2398                f'of {GPA.pc.get_max_dendrites()}, resetting LR and continuing.'
2399            )
2400        GPA.pai_tracker.member_vars["num_dendrites_added"] += 1
2401        # Record the switch to p and straight back to n, like the open source n-p-n switch
2402        GPA.pai_tracker.member_vars["switch_epochs"].append(
2403            GPA.pai_tracker.member_vars["num_epochs_run"]
2404        )
2405        GPA.pai_tracker.member_vars["switch_epochs"].append(
2406            GPA.pai_tracker.member_vars["num_epochs_run"]
2407        )
2408        GPA.pai_tracker.member_vars["last_switch"] = GPA.pai_tracker.member_vars[
2409            "switch_epochs"
2410        ][-1]
2411        GPA.pai_tracker.reset_vals_for_score_reset()
2412        # Start a new LR search like set_dendrite_training and set_neuron_training do
2413        GPA.pai_tracker.member_vars["current_n_learning_rate_initial_skip_steps"] = 0
2414        GPA.pai_tracker.member_vars["last_max_learning_rate_steps"] = GPA.pai_tracker.member_vars[
2415            "current_step_count"
2416        ]
2417        if GPA.pc.get_find_best_lr():
2418            TPA._lr_search_initialize()
2419        return net
2420    if GPA.pai_tracker.member_vars["mode"] == "n":
2421        current_epoch = GPA.pai_tracker.member_vars["num_epochs_run"]
2422        overwritten_epochs = GPA.pai_tracker.member_vars["overwritten_epochs"]
2423        overwritten_extra = GPA.pai_tracker.member_vars["extra_scores"]
2424        if GPA.pc.get_drawing_pai():
2425            overwritten_val = GPA.pai_tracker.member_vars["accuracies"]
2426        else:
2427            overwritten_val = GPA.pai_tracker.member_vars["neuron_accuracies"]
2428        """
2429        If true don't load the best system
2430        because it will delete dendrites if the previous best was better than
2431        the current best
2432        """
2433        if not GPA.pc.get_silent():
2434            print("Importing best Model for switch to PA...")
2435        net = load_system(net, folder, name, switch_call=True)
2436        GPA.pai_tracker.set_dendrite_training()
2437        GPA.pai_tracker.member_vars["overwritten_epochs"] = overwritten_epochs
2438        GPA.pai_tracker.member_vars["overwritten_epochs"] += (
2439            current_epoch - GPA.pai_tracker.member_vars["num_epochs_run"]
2440        )
2441        GPA.pai_tracker.member_vars["total_epochs_run"] = (
2442            GPA.pai_tracker.member_vars["num_epochs_run"]
2443            + GPA.pai_tracker.member_vars["overwritten_epochs"]
2444        )
2445
2446        if GPA.pc.get_save_old_graph_scores():
2447            GPA.pai_tracker.member_vars["overwritten_extras"].append(overwritten_extra)
2448            GPA.pai_tracker.member_vars["overwritten_vals"].append(overwritten_val)
2449        else:
2450            GPA.pai_tracker.member_vars["overwritten_extras"] = [overwritten_extra]
2451            GPA.pai_tracker.member_vars["overwritten_vals"] = [overwritten_val]
2452        if GPA.pc.get_drawing_pai():
2453            GPA.pai_tracker.member_vars["n_switch_epochs"].append(
2454                GPA.pai_tracker.member_vars["num_epochs_run"]
2455            )
2456        else:
2457            if len(GPA.pai_tracker.member_vars["switch_epochs"]) == 0:
2458                GPA.pai_tracker.member_vars["n_switch_epochs"].append(
2459                    GPA.pai_tracker.member_vars["num_epochs_run"]
2460                )
2461            else:
2462                GPA.pai_tracker.member_vars["n_switch_epochs"].append(
2463                    GPA.pai_tracker.member_vars["n_switch_epochs"][-1]
2464                    + (
2465                        (GPA.pai_tracker.member_vars["num_epochs_run"])
2466                        - (GPA.pai_tracker.member_vars["switch_epochs"][-1])
2467                    )
2468                )
2469
2470        GPA.pai_tracker.member_vars["switch_epochs"].append(
2471            GPA.pai_tracker.member_vars["num_epochs_run"]
2472        )
2473        GPA.pai_tracker.member_vars["last_switch"] = GPA.pai_tracker.member_vars[
2474            "switch_epochs"
2475        ][-1]
2476
2477        # Because open source version is only doing neuron training for
2478        # gradient descent dendrites, switch back to n mode right away
2479        if (
2480            not GPA.pc.get_perforated_backpropagation()
2481        ) or GPA.pc.get_no_extra_n_modes():
2482            net = change_learning_modes(net, folder, name, doing_pai)
2483    else:
2484        if not GPA.pc.get_silent():
2485            print("Switching back to N...")
2486        set_best = GPA.pai_tracker.member_vars["current_n_set_global_best"]
2487        GPA.pai_tracker.set_neuron_training()
2488        if len(GPA.pai_tracker.member_vars["p_switch_epochs"]) == 0:
2489            GPA.pai_tracker.member_vars["p_switch_epochs"].append(
2490                (
2491                    (GPA.pai_tracker.member_vars["num_epochs_run"] - 1)
2492                    - (GPA.pai_tracker.member_vars["switch_epochs"][-1])
2493                )
2494            )
2495        else:
2496            GPA.pai_tracker.member_vars["p_switch_epochs"].append(
2497                GPA.pai_tracker.member_vars["p_switch_epochs"][-1]
2498                + (
2499                    (GPA.pai_tracker.member_vars["num_epochs_run"])
2500                    - (GPA.pai_tracker.member_vars["switch_epochs"][-1])
2501                )
2502            )
2503        GPA.pai_tracker.member_vars["switch_epochs"].append(
2504            GPA.pai_tracker.member_vars["num_epochs_run"]
2505        )
2506        GPA.pai_tracker.member_vars["last_switch"] = GPA.pai_tracker.member_vars[
2507            "switch_epochs"
2508        ][-1]
2509        # Will be false for open source implementation
2510        if GPA.pc.get_retain_all_dendrites() or (
2511            GPA.pc.get_learn_dendrites_live() and set_best
2512        ):
2513            if not GPA.pc.get_silent():
2514                print(
2515                    "Saving model before starting normal training to "
2516                    "retain PBNodes regardless of next N Phase results"
2517                )
2518            save_system(net, folder, name)
2519        # if its just doing P for learn PAI live then switch back immediately
2520        if GPA.pc.get_perforated_backpropagation() and GPA.pc.get_no_extra_n_modes():
2521            net = change_learning_modes(net, folder, name, doing_pai)
2522
2523    GPA.pai_tracker.member_vars["param_counts"].append(count_params(net))
2524
2525    return net
2526
2527
2528def find_param_name_by_id(model, param_id):
2529    """
2530    This is only used for debugging.
2531    Return the fully-qualified parameter name (e.g. "layer1.conv.weight")
2532    for the parameter whose id matches param_id. Returns None if not found.
2533
2534    This uses model.named_parameters(), which already recurses through submodules.
2535
2536    Parameters
2537    ----------
2538    model : Model to look for param id.
2539    param_id : pointer to a parameter.
2540
2541    Returns
2542    -------
2543    String representing the module within the model or None if not found.
2544    """
2545    for name, p in model.named_parameters(recurse=True):
2546        if id(p) == param_id:
2547            return "." + name
2548    return None
2549
2550
2551def add_method_delegation_to_module(wrapper_module, method_name):
2552    """Add delegating methods to a wrapper module that has a main_module attribute.
2553
2554    This adds the specified methods to the wrapper module instance so they
2555    properly delegate to the wrapped main_module. Works for any wrapper module
2556    (TrackedNeuronModule, PAINeuronModule, etc.) that has a main_module attribute.
2557
2558    Args:
2559        wrapper_module: A wrapper module instance with a main_module attribute
2560        method_name: The method name to delegate (e.g., '_gradient_checkpointing_func')
2561
2562    Parameters
2563    ----------
2564    wrapper_module : PyTorch Module that contains a sub module.
2565    method_name : Name of method to wrap.
2566
2567    Returns
2568    -------
2569    None
2570    """
2571    import types
2572
2573    if hasattr(wrapper_module.main_module, method_name):
2574        # Create a delegating method that forwards to main_module
2575        def make_delegated_method(name):
2576            """Create a bound delegation function for a given attribute name.
2577
2578            Parameters
2579            ----------
2580            name : str
2581                Attribute name to forward to ``main_module``.
2582
2583            Returns
2584            -------
2585            callable
2586                Function that delegates access or invocation.
2587            """
2588            def delegated_method(self, *args, **kwargs):
2589                """Delegate attribute access or method call to ``main_module``.
2590
2591                Parameters
2592                ----------
2593                *args : tuple
2594                    Positional arguments forwarded to delegated callables.
2595                **kwargs : dict
2596                    Keyword arguments forwarded to delegated callables.
2597
2598                Returns
2599                -------
2600                Any
2601                    Delegated attribute value or method result.
2602                """
2603                main_module_attr = getattr(self.main_module, name, None)
2604                if main_module_attr is None:
2605                    raise AttributeError(
2606                        f"'{type(self.main_module).__name__}' object has no attribute '{name}'"
2607                    )
2608                if callable(main_module_attr):
2609                    return main_module_attr(*args, **kwargs)
2610                return main_module_attr
2611
2612            return delegated_method
2613
2614        # Bind it to this specific instance
2615        setattr(
2616            wrapper_module,
2617            method_name,
2618            types.MethodType(make_delegated_method(method_name), wrapper_module),
2619        )
2620
2621
2622def apply_method_delegation_to_model(model, method_name, main_module_type):
2623    """Recursively apply method delegation to all wrapper modules with main_module in a model.
2624
2625    This traverses the entire model and adds method delegation for any module that has
2626    a main_module attribute and optionally matches specified types.
2627
2628    Args:
2629        model: The PyTorch model to traverse
2630        method_name: The method name to delegate (e.g., '_gradient_checkpointing_func')
2631        main_module_type: main_module type name to filter by.
2632                          Example: 'Qwen2DecoderLayer'
2633
2634    Example:
2635        # Apply gradient checkpointing delegation to all decoder layers
2636        apply_method_delegation_to_model(
2637            model,
2638            '_gradient_checkpointing_func',
2639            main_module_type='Qwen2DecoderLayer'
2640        )
2641
2642    Parameters
2643    ----------
2644    model : PyTorch model.
2645    method_name : method to delegate.
2646    main_module_type : type of module that has this method.
2647
2648    Returns
2649    -------
2650    None
2651        This function does not return a value.
2652    """
2653    count = 0
2654    for name, module in model.named_modules():
2655        # Check if module has main_module attribute (it's a wrapper)
2656        if hasattr(module, "main_module"):
2657            # Check if we should apply based on main_module type
2658            should_apply = True
2659            if main_module_type is not None:
2660                main_module_type_name = type(module.main_module).__name__
2661                should_apply = main_module_type_name == main_module_type
2662
2663            if should_apply:
2664                add_method_delegation_to_module(module, method_name)
2665                count += 1
2666
2667    print(f"[PAI] Applied method delegation to {count} wrapper module instances")
2668
2669
2670def make_json_serializable(obj):
2671    """Recursively convert non-JSON-serializable objects to strings.
2672
2673    Parameters
2674    ----------
2675    obj : any
2676        The object to convert
2677
2678    Returns
2679    -------
2680    Any
2681        JSON-serializable version of the object
2682    """
2683    if isinstance(obj, (str, int, float, bool, type(None))):
2684        return obj
2685    elif isinstance(obj, dict):
2686        return {k: make_json_serializable(v) for k, v in obj.items()}
2687    elif isinstance(obj, (list, tuple)):
2688        return [make_json_serializable(item) for item in obj]
2689    else:
2690        # Convert non-serializable types to string
2691        return str(obj)
2692
2693
2694def extract_gpa_config():
2695    """Extract all configuration from GPA.pc by calling all get_* methods.
2696
2697    Returns
2698    -------
2699    dict[str, Any]
2700        Dictionary with all GPA.pc configuration values and type metadata
2701
2702    Examples
2703    --------
2704    >>> config = extract_gpa_config()
2705    >>> # Returns: {'max_dendrites': 10, 'device': 'cuda', '_types': {...}}
2706
2707    Parameters
2708    ----------
2709    None
2710
2711    """
2712    config = {}
2713    config_types = {}
2714
2715    # Get all attributes from GPA.pc
2716    for attr_name in dir(GPA.pc):
2717        # Check if it starts with 'get_'
2718        if attr_name.startswith("get_"):
2719            try:
2720                # Get the method
2721                method = getattr(GPA.pc, attr_name)
2722
2723                # Check if it's callable
2724                if callable(method):
2725                    # Call it and store result with key as name without 'get_'
2726                    key = attr_name[4:]  # Remove 'get_' prefix
2727                    value = method()
2728
2729                    # Check if this is an array (has corresponding append_ method)
2730                    append_method_name = f"append_{key}"
2731                    is_array = hasattr(GPA.pc, append_method_name)
2732
2733                    if is_array and isinstance(value, (list, tuple)):
2734                        # Store array element type
2735                        if len(value) > 0:
2736                            element_type = type(value[0]).__name__
2737                        else:
2738                            element_type = None  # empty array, no conversion needed
2739                        config_types[key] = {
2740                            "is_array": True,
2741                            "element_type": element_type,
2742                        }
2743                    else:
2744                        # Store value type
2745                        config_types[key] = {
2746                            "is_array": False,
2747                            "type": type(value).__name__,
2748                        }
2749
2750                    # Make sure value is JSON serializable
2751                    config[key] = make_json_serializable(value)
2752            except Exception as e:
2753                # Skip if method fails
2754                if GPA.pc.get_verbose():
2755                    print(f"Skipping {attr_name}: {e}")
2756                continue
2757
2758    # Add types metadata to config
2759    config["_types"] = config_types
2760
2761    return config
2762
2763
2764def convert_to_type(value, type_name):
2765    """Convert a value to the specified type.
2766
2767    Parameters
2768    ----------
2769    value : any
2770        The value to convert
2771    type_name : str
2772        The target type name
2773
2774    Returns
2775    -------
2776    Any
2777        The converted value
2778    """
2779    if type_name == "NoneType" or value is None:
2780        return None
2781    elif type_name == "bool":
2782        if isinstance(value, str):
2783            return value.lower() in ("true", "1", "yes")
2784        return bool(value)
2785    elif type_name == "int":
2786        return int(value)
2787    elif type_name == "float":
2788        return float(value)
2789    elif type_name == "str":
2790        return str(value)
2791    elif type_name == "list":
2792        if not isinstance(value, list):
2793            return [value]
2794        return value
2795    elif type_name == "dict":
2796        if not isinstance(value, dict):
2797            return {}
2798        return value
2799    elif type_name == "type":
2800        # Handle type objects - convert string representation back to type
2801        if isinstance(value, str):
2802            # Try to evaluate the type string (e.g., "<class 'torch.nn.Linear'>")
2803            # Extract the class path from the string
2804            if value.startswith("<class '") and value.endswith("'>"):
2805                class_path = value[
2806                    8:-2
2807                ]  # Extract 'torch.nn.Linear' from "<class 'torch.nn.Linear'>"
2808                parts = class_path.split(".")
2809                # Try to import and get the type
2810                try:
2811                    module_name = ".".join(parts[:-1])
2812                    class_name = parts[-1]
2813                    module = __import__(module_name, fromlist=[class_name])
2814                    return getattr(module, class_name)
2815                except Exception as e:
2816                    print(
2817                        f"Warning: Could not convert type string '{value}' to actual type: {e}"
2818                    )
2819                    return value
2820            return value
2821        return value
2822    elif type_name == "dtype":
2823        # Handle torch dtype objects
2824        if isinstance(value, str):
2825            # Convert string like "torch.float32" to actual dtype
2826            import torch
2827
2828            try:
2829                # Try to get the dtype from torch module
2830                if value.startswith("torch."):
2831                    dtype_name = value.split(".")[
2832                        1
2833                    ]  # Get 'float32' from 'torch.float32'
2834                    return getattr(torch, dtype_name)
2835                else:
2836                    return getattr(torch, value)
2837            except Exception as e:
2838                print(
2839                    f"Warning: Could not convert dtype string '{value}' to actual dtype: {e}"
2840                )
2841                return value
2842        return value
2843    elif type_name == "device":
2844        # Handle torch device objects
2845        if isinstance(value, str):
2846            # Convert string like "cuda" or "cpu" to torch.device
2847            import torch
2848
2849            try:
2850                return torch.device(value)
2851            except Exception as e:
2852                print(
2853                    f"Warning: Could not convert device string '{value}' to actual device: {e}"
2854                )
2855                return value
2856        return value
2857    elif type_name == "builtin_function_or_method":
2858        # Handle torch functions like torch.sigmoid, torch.relu, etc.
2859        if isinstance(value, str):
2860            # Parse string like "<built-in method sigmoid of type object at 0x...>"
2861            # to extract the function name
2862            import torch
2863
2864            try:
2865                if "<built-in method " in value and " of type object" in value:
2866                    # Extract function name between '<built-in method ' and ' of type object'
2867                    start = value.find("<built-in method ") + len("<built-in method ")
2868                    end = value.find(" of type object")
2869                    func_name = value[start:end]
2870                    # Try to get the function from torch module
2871                    if hasattr(torch, func_name):
2872                        return getattr(torch, func_name)
2873                    else:
2874                        print(f"Warning: torch.{func_name} not found")
2875                        return value
2876                else:
2877                    return value
2878            except Exception as e:
2879                print(
2880                    f"Warning: Could not convert builtin function string '{value}': {e}"
2881                )
2882                return value
2883        return value
2884    else:
2885        # Unknown type - error and debug
2886        print(f"ERROR: Unknown type '{type_name}' for value: {value}")
2887        print(f"Type of value is: {type(value).__name__}")
2888        pdb.set_trace()
2889        return value
2890
2891
2892def convert_to_type_array(value, element_type):
2893    """Convert an array's elements to the specified type.
2894
2895    Parameters
2896    ----------
2897    value : list or tuple
2898        The array to convert
2899    element_type : str or None
2900        The target type name for elements, None if array was empty
2901
2902    Returns
2903    -------
2904    list
2905        The array with converted elements
2906    """
2907    if not isinstance(value, (list, tuple)):
2908        return value
2909    # If element_type is None (empty array), no conversion needed
2910    if element_type is None:
2911        return list(value) if isinstance(value, tuple) else value
2912    return [convert_to_type(item, element_type) for item in value]
2913
2914
2915def set_gpa_config(config):
2916    """Set GPA.pc configuration by calling all set_* methods.
2917
2918    This is the reverse of extract_gpa_config(). It takes a configuration
2919    dictionary and calls the corresponding set_* methods on GPA.pc.
2920    Uses type metadata to ensure values are converted to the correct type.
2921
2922    Parameters
2923    ----------
2924    config : dict
2925        Dictionary with configuration values (keys without 'set_' prefix)
2926        and optional '_types' metadata
2927
2928    Examples
2929    --------
2930    >>> config = {'verbose': True, 'device': 'cuda'}
2931    >>> set_gpa_config(config)
2932    # Calls GPA.pc.set_verbose(True), GPA.pc.set_device('cuda'), etc.
2933
2934    Returns
2935    -------
2936    Count of parameters that were set
2937    """
2938    set_count = 0
2939    skip_count = 0
2940
2941    # Extract type information
2942    config_types = config.get("_types", {})
2943
2944    for key, value in config.items():
2945        # Skip the types metadata
2946        if key == "_types":
2947            continue
2948
2949        # Construct the set method name
2950        set_method_name = f"set_{key}"
2951
2952        # Check if the set method exists
2953        if hasattr(GPA.pc, set_method_name):
2954            try:
2955                method = getattr(GPA.pc, set_method_name)
2956                if callable(method):
2957                    # Convert value to correct type if we have type info
2958                    if key in config_types:
2959                        type_info = config_types[key]
2960                        if type_info.get("is_array", False):
2961                            # Convert array elements to correct type
2962                            element_type = type_info.get("element_type", "str")
2963                            value = convert_to_type_array(value, element_type)
2964                        else:
2965                            # Convert single value to correct type
2966                            value_type = type_info.get("type", "str")
2967                            value = convert_to_type(value, value_type)
2968
2969                    method(value)
2970                    set_count += 1
2971                    if GPA.pc.get_verbose():
2972                        print(f"Set {key} = {value}")
2973            except Exception as e:
2974                skip_count += 1
2975                if GPA.pc.get_verbose():
2976                    print(f"Failed to set {key}: {e}")
2977        else:
2978            skip_count += 1
2979            if GPA.pc.get_verbose():
2980                print(f"No setter found for {key} (looking for {set_method_name})")
2981
2982    if GPA.pc.get_verbose():
2983        print(f"Applied {set_count} PAI configuration settings ({skip_count} skipped)")
2984
2985    return set_count
2986
2987
2988try:
2989    from huggingface_hub import PyTorchModelHubMixin, hf_hub_download, HfApi
2990
2991    def upload_to_huggingface(
2992        model,
2993        repo_id,
2994        license="apache-2.0",
2995        pipeline_tag=None,
2996        repo_url=None,
2997        tags=None,
2998        include_pai_config=True,
2999        **kwargs,
3000    ):
3001        """Upload a model to HuggingFace Hub.
3002
3003        Uploads model weights and PAI configuration to HuggingFace Hub.
3004        The configuration is saved in config.json and can be restored when loading.
3005
3006        Parameters
3007        ----------
3008        model : nn.Module
3009            The model to upload
3010        repo_id : str
3011            Repository ID (format: "username/model-name")
3012        license : str, optional
3013            License for the model card, by default "apache-2.0"
3014        pipeline_tag : str, optional
3015            Pipeline tag for the model (e.g., "text-classification", "image-classification")
3016        repo_url : str, optional
3017            URL to the model's repository/documentation
3018        tags : list, optional
3019            List of tags for the model card
3020        include_pai_config : bool, optional
3021            Whether to include all GPA.pc configuration in the model config, by default True
3022        **kwargs
3023            Additional arguments passed to HfApi (token, private, etc.)
3024
3025        Returns
3026        -------
3027        str
3028            URL of the uploaded model
3029
3030        Examples
3031        --------
3032        >>> url = upload_to_huggingface(
3033        ...     model,
3034        ...     "username/my-model",
3035        ...     license="mit",
3036        ...     pipeline_tag="image-classification",
3037        ...     tags=["pytorch", "vision"]
3038        ... )
3039        """
3040        try:
3041            from huggingface_hub import HfApi
3042        except ImportError:
3043            raise ImportError(
3044                "huggingface_hub is required. Install it with: pip install huggingface_hub"
3045            )
3046
3047        import tempfile
3048        import os
3049
3050        # Prepare model same way as save_pai_net does
3051        model = prepare_final_model(model)
3052
3053        # Calculate parameter count
3054        param_count = count_params(model)
3055
3056        # Format parameter count for tags (e.g., "11m" for 11 million)
3057        if param_count >= 1e9:
3058            param_tag = f"{param_count/1e9:.0f}b"
3059        elif param_count >= 1e6:
3060            param_tag = f"{param_count/1e6:.0f}m"
3061        elif param_count >= 1e3:
3062            param_tag = f"{param_count/1e3:.0f}k"
3063        else:
3064            param_tag = str(param_count)
3065
3066        # Create a temporary directory for files
3067        with tempfile.TemporaryDirectory() as tmpdir:
3068            # Save model weights
3069            model_path = os.path.join(tmpdir, "model.safetensors")
3070            save_file(model.state_dict(), model_path)
3071
3072            # Create config with PAI configuration
3073            config = {}
3074            if include_pai_config:
3075                pai_config = extract_gpa_config()
3076                config["pai_config"] = pai_config
3077                if GPA.pc.get_verbose():
3078                    print(f"Extracted {len(pai_config)} PAI configuration parameters")
3079
3080            # Add parameter count at top level
3081            config["num_parameters"] = param_count
3082
3083            # Add metadata
3084            if license:
3085                config["license"] = license
3086            if pipeline_tag:
3087                config["pipeline_tag"] = pipeline_tag
3088            if repo_url:
3089                config["repo_url"] = repo_url
3090
3091            # Add tags with parameter count
3092            if tags is None:
3093                tags = []
3094            elif not isinstance(tags, list):
3095                tags = [tags]
3096            else:
3097                tags = tags.copy()  # Don't modify the original list
3098
3099            # Add perforated-ai tag if not present
3100            if "perforated-ai" not in tags:
3101                tags.insert(0, "perforated-ai")
3102
3103            # Add parameter count tag if not present
3104            if param_tag not in tags:
3105                tags.append(param_tag)
3106
3107            config["tags"] = tags
3108
3109            # Save config.json
3110            config_path = os.path.join(tmpdir, "config.json")
3111            with open(config_path, "w") as f:
3112                json.dump(config, f, indent=2)
3113
3114            # Upload to HuggingFace
3115            api = HfApi()
3116
3117            # Extract token from kwargs if present
3118            token = kwargs.pop("token", None)
3119            private = kwargs.pop("private", None)
3120
3121            # Create repo if it doesn't exist
3122            try:
3123                api.create_repo(
3124                    repo_id=repo_id, token=token, private=private, exist_ok=True
3125                )
3126            except Exception as e:
3127                print(f"Repo may already exist: {e}")
3128
3129            # Upload folder
3130            api.upload_folder(
3131                folder_path=tmpdir, repo_id=repo_id, token=token, **kwargs
3132            )
3133
3134        print(f"Model uploaded to: https://huggingface.co/{repo_id}")
3135        if include_pai_config:
3136            print(f"PAI configuration saved in config.json")
3137        print(f"To reload, use: model = from_hf_pretrained(model, '{repo_id}')")
3138
3139        return f"https://huggingface.co/{repo_id}"
3140
3141    def from_hf_pretrained(net, repo_id, force_download=False):
3142        """Load a PerforatedAI model from HuggingFace Hub using PyTorchModelHubMixin.
3143
3144        Args:
3145            net: The base model architecture (will be converted to PAI format)
3146            repo_id: HuggingFace Hub repository ID (e.g., "username/model-name")
3147            force_download: If True, always download the latest version, bypassing cache (default: False)
3148
3149        Returns:
3150            net: The loaded model with PAI modules initialized
3151
3152        Parameters
3153        ----------
3154        net : PyTorch Model.
3155        repo_id : Name of HuggingFace repository.
3156        force_download : Force an update even if local file exists.
3157
3158        Returns
3159        -------
3160        Loaded Model
3161        """
3162
3163        # Wrap in a class that inherits from PyTorchModelHubMixin
3164        class PAIHFModel(net.__class__, PyTorchModelHubMixin):
3165            def __init__(self, *args, **kwargs):
3166                """Initialize the temporary HuggingFace-compatible wrapper."""
3167                super().__init__(*args, **kwargs)
3168
3169        # Create an instance that can use from_pretrained
3170        wrapped_net = PAIHFModel.__new__(PAIHFModel)
3171        wrapped_net.__dict__ = net.__dict__
3172        wrapped_net.__class__ = PAIHFModel
3173
3174        # Download config.json to restore PAI configuration
3175        try:
3176            config_path = hf_hub_download(repo_id=repo_id, filename="config.json", force_download=force_download)
3177            with open(config_path, "r") as f:
3178                config = json.load(f)
3179                if "pai_config" in config:
3180                    # print(f"Restoring PAI configuration from HuggingFace")
3181                    set_gpa_config(config["pai_config"])
3182                else:
3183                    print("Warning: No pai_config found in config.json")
3184        except Exception as e:
3185            print(f"Warning: Could not load PAI config from HuggingFace: {e}")
3186
3187        # Download model files from HuggingFace
3188        model_path = hf_hub_download(repo_id=repo_id, filename="model.safetensors", force_download=force_download)
3189        state_dict = load_file(model_path)
3190        wrapped_net = NPA.load_pai_model_from_dict(wrapped_net, state_dict)
3191        return wrapped_net
3192
3193except:
3194
3195    def upload_to_huggingface(*args, **kwargs):
3196        """Raise an informative error when HuggingFace dependencies are missing.
3197
3198        Parameters
3199        ----------
3200        *args : tuple[Any, ...]
3201            Positional arguments accepted for API compatibility.
3202        **kwargs : dict[str, Any]
3203            Keyword arguments accepted for API compatibility.
3204
3205        Returns
3206        -------
3207        None
3208            Always raises ``ImportError``.
3209        """
3210        raise ImportError(
3211            "huggingface_hub is required for upload_to_huggingface. "
3212            "Install it with: pip install huggingface_hub"
3213        )
3214
3215    def from_hf_pretrained(*args, **kwargs):
3216        """Raise an informative error when HuggingFace dependencies are missing.
3217
3218        Parameters
3219        ----------
3220        *args : tuple[Any, ...]
3221            Positional arguments accepted for API compatibility.
3222        **kwargs : dict[str, Any]
3223            Keyword arguments accepted for API compatibility.
3224
3225        Returns
3226        -------
3227        None
3228            Always raises ``ImportError``.
3229        """
3230        raise ImportError(
3231            "huggingface_hub is required for from_hf_pretrained. "
3232            "Install it with: pip install huggingface_hub"
3233        )
def perforate_model( model, doing_pai=True, save_name='', making_graphs=True, maximizing_score=None, num_classes=10000000000, values_per_train_epoch=-1, values_per_val_epoch=-1, zooming_graph=True, config_file=None):
 48def perforate_model(
 49    model,
 50    doing_pai=True,
 51    save_name="",
 52    making_graphs=True,
 53    maximizing_score=None,
 54    num_classes=10000000000,
 55    values_per_train_epoch=-1,
 56    values_per_val_epoch=-1,
 57    zooming_graph=True,
 58    config_file=None,
 59):
 60    """Main function to initialize the network to add dendrites
 61
 62    This kicks off the entire Perforated AI process to add
 63    the scaffolding to the network to be able to add dendrites
 64
 65    Parameters
 66    ----------
 67    model : nn.Module
 68        The neural network model to initialize.
 69    doing_pai : bool, optional
 70        Whether to actually add dendrites, by default True
 71    save_name : str, optional
 72        The name to save the model under, by default "PAI"
 73    making_graphs : bool, optional
 74        Whether to create graphs during training, by default True
 75    maximizing_score : bool or None, optional
 76        Whether to maximize the score during training.
 77        - None: use config value (defaults to True)
 78        - bool: override config value for this run
 79        Setting False is for when the score is a loss to be minimized.
 80    num_classes : int, optional
 81        The number of output classes, unused in current version
 82    values_per_train_epoch : int, optional
 83        The number of values to look back for graphing
 84        during training, by default -1 (all values).
 85    values_per_val_epoch : int, optional
 86        The number of values to look back for graphing
 87        during validation, by default -1 (all values).
 88    zooming_graph : bool, optional
 89        Whether to enable zooming on the graphs, by default True
 90    config_file : str or None, optional
 91        Optional local JSON config file path to load, by default None.
 92
 93    Returns
 94    -------
 95    model : nn.Module
 96        The modified model with dendrite scaffolding added if doing_pai is True
 97
 98    """
 99
100    if save_name == "":
101        if GPA.pc.get_save_name() == "":
102            save_name = "PAI"
103        else:
104            save_name = GPA.pc.get_save_name()
105
106    if "/" in save_name:
107        print(
108            f"Warning: save_name '{save_name}' contains '/'. Relative paths are not implemented yet."
109        )
110        sys.exit(1)
111
112    sanitized_save_name = "".join(
113        ch for ch in save_name if ch.isalnum() or ch in ("_", "-", ".")
114    )
115    if sanitized_save_name != save_name:
116        print(
117            f"Warning: save_name '{save_name}' contained spaces or special characters. "
118            f"Using '{sanitized_save_name}' instead."
119        )
120        save_name = sanitized_save_name
121
122    if save_name == "":
123        print("Warning: save_name became empty after sanitization. Using 'PAI'.")
124        save_name = "PAI"
125
126    if config_file is not None:
127        GPA.pc.set_config_file(config_file)
128
129    GPA.pc.set_save_name(save_name)
130    GPA.pc.sync_config_sources()
131
132    if maximizing_score is None:
133        maximizing_score = GPA.pc.get_maximizing_score()
134    else:
135        # Programmatic perforate_model input must win over config-file values.
136        GPA.pc.set_maximizing_score(maximizing_score)
137
138    if os.environ.get("PAI_CONFIG_MODE"):
139        GPA.pc.set_configuration_confirmed(False)
140
141    if not GPA.pc.get_configuration_confirmed():
142        CPA.set_perforation_targets(model)
143
144    fused_pairs = apply_fused_pairs(model) if doing_pai else []
145
146    # Install the default dendrite loss mode before any code reads the selected loss
147    # class through MPB.get_global_dendrite_loss_class(). The underlying private global
148    # now starts as None (its former import-time default was removed so that
149    # setup_new_global_dendrite_mode is the only writer); initialize() below constructs
150    # the dendrite modules and value trackers that perform the first reads, so the
151    # installer must run ahead of it.
152    # The call is idempotent: a user who called setup_new_global_dendrite_mode
153    # themselves before perforate_model keeps their own choice. It is reached only
154    # when Perforated Backpropagation is enabled, which guarantees perforatedbp is
155    # importable (the enable flag is set only after that import succeeds), and by
156    # the time perforate_model runs every module has finished importing, so this
157    # runtime import cannot create a cycle.
158    if GPA.pc.get_perforated_backpropagation():
159        import perforatedbp.tracker_pbp as TPB
160
161        TPB.install_global_default_dendrite_mode()
162
163    GPA.pai_tracker = TPA.PAINeuronModuleTracker(
164        doing_pai=doing_pai, save_name=save_name
165    )
166    if _dashboard_emitter is not None:
167        _dashboard_emitter.emit_run_start(GPA.pc, save_name)
168
169    # Get config outputs before tracker is initialized
170    GPA.pc.persist_config_outputs(overwrite_config_file=False)
171
172    model = GPA.pai_tracker.initialize(
173        model,
174        doing_pai=doing_pai,
175        save_name=save_name,
176        making_graphs=making_graphs,
177        maximizing_score=maximizing_score,
178        num_classes=num_classes,
179        values_per_train_epoch=-values_per_train_epoch,
180        values_per_val_epoch=values_per_val_epoch,
181        zooming_graph=zooming_graph,
182    )
183
184    if fused_pairs:
185        install_fuse_checks(model, fused_pairs)
186
187    for param in model.parameters():
188        param.data = param.data.contiguous()
189
190    # When perforated backpropagation is enabled, register the epoch-boundary
191    # hooks so a dendrite loss class's on_epoch_* methods fire automatically,
192    # rather than requiring the application to call register_epoch_hooks() by
193    # hand before perforate_model. Imported at call time to avoid a circular
194    # import; its perforatedbp imports are only usable when perforated
195    # backpropagation is enabled.
196    if GPA.pc.get_perforated_backpropagation():
197        from perforatedai.dendrite_loss_events import register_epoch_hooks
198
199        register_epoch_hooks()
200
201    # Save config after perforation
202    if not GPA.pc.get_testing_dendrite_capacity():
203        GPA.pc.save_config(os.path.join(os.getcwd(), save_name, f"{save_name}_config.json"))
204
205    return model

Main function to initialize the network to add dendrites

This kicks off the entire Perforated AI process to add the scaffolding to the network to be able to add dendrites

Parameters
  • model (nn.Module): The neural network model to initialize.
  • doing_pai (bool, optional): Whether to actually add dendrites, by default True
  • save_name (str, optional): The name to save the model under, by default "PAI"
  • making_graphs (bool, optional): Whether to create graphs during training, by default True
  • maximizing_score (bool or None, optional): Whether to maximize the score during training.
    • None: use config value (defaults to True)
    • bool: override config value for this run Setting False is for when the score is a loss to be minimized.
  • num_classes (int, optional): The number of output classes, unused in current version
  • values_per_train_epoch (int, optional): The number of values to look back for graphing during training, by default -1 (all values).
  • values_per_val_epoch (int, optional): The number of values to look back for graphing during validation, by default -1 (all values).
  • zooming_graph (bool, optional): Whether to enable zooming on the graphs, by default True
  • config_file (str or None, optional): Optional local JSON config file path to load, by default None.
Returns
  • model (nn.Module): The modified model with dendrite scaffolding added if doing_pai is True
def fuse_modules(model, pairs):
215def fuse_modules(model, pairs):
216    """Fuse each head with the norm that follows it.
217
218    For every (head_id, norm_id) the head's attribute becomes a PAISequential
219    holding the head and the norm, and the norm's attribute becomes a
220    FusedNormIdentity. The model's forward() does not need to change. Must be
221    called before convert_network, and before load_system.
222
223    Parameters
224    ----------
225    model : nn.Module
226        The model to modify in place.
227    pairs : list of (str, str)
228        Module ids (like '.block.linear') of each head and its norm.
229
230    Returns
231    -------
232    nn.Module
233        The same model, with the pairs fused.
234    """
235    if not pairs:
236        return model
237    pairs = [tuple(pair) for pair in pairs]
238
239    occurrences = {}
240    for _name, module in model.named_modules(remove_duplicate=False):
241        occurrences[id(module)] = occurrences.get(id(module), 0) + 1
242
243    seen_ids = []
244    for head_id, norm_id in pairs:
245        for role, module_id in (("head", head_id), ("norm", norm_id)):
246            try:
247                module = model.get_submodule(module_id.lstrip("."))
248            except AttributeError:
249                raise ValueError(
250                    "Cannot fuse: %s %s does not exist in the model." % (role, module_id)
251                )
252            if module_id.lstrip(".") == "":
253                raise ValueError("Cannot fuse the whole model.")
254            if module_id in seen_ids:
255                raise ValueError(
256                    "Cannot fuse: %s is in more than one fused pair." % module_id
257                )
258            seen_ids.append(module_id)
259            if occurrences[id(module)] > 1:
260                raise ValueError(
261                    "Cannot fuse: %s is used in more than one place in the model."
262                    % module_id
263                )
264        head = model.get_submodule(head_id.lstrip("."))
265        if not any(param.requires_grad for param in head.parameters()):
266            raise ValueError(
267                "Cannot fuse: head %s is not trainable. Only trainable modules "
268                "can be the head of a fused pair." % head_id
269            )
270    for first in seen_ids:
271        for second in seen_ids:
272            if first != second and second.startswith(first + "."):
273                raise ValueError(
274                    "Cannot fuse: %s is inside %s, which is also fused."
275                    % (second, first)
276                )
277
278    for head_id, norm_id in pairs:
279        head = model.get_submodule(head_id.lstrip("."))
280        norm = model.get_submodule(norm_id.lstrip("."))
281        head_parent, head_attr = _split_module_id(head_id)
282        norm_parent, norm_attr = _split_module_id(norm_id)
283        model.get_submodule(head_parent)._modules[head_attr] = GPA.PAISequential(
284            [head, norm]
285        )
286        model.get_submodule(norm_parent)._modules[norm_attr] = GPA.FusedNormIdentity(
287            head_id, norm_id
288        )
289    return model

Fuse each head with the norm that follows it.

For every (head_id, norm_id) the head's attribute becomes a PAISequential holding the head and the norm, and the norm's attribute becomes a FusedNormIdentity. The model's forward() does not need to change. Must be called before convert_network, and before load_system.

Parameters
  • model (nn.Module): The model to modify in place.
  • pairs (list of (str, str)): Module ids (like '.block.linear') of each head and its norm.
Returns
  • nn.Module: The same model, with the pairs fused.
def install_fuse_checks(model, pairs):
292def install_fuse_checks(model, pairs):
293    """Make each fused norm stand-in verify its input on the first forward.
294
295    Must be called after convert_network, because by then the head's attribute
296    holds a PAINeuronModule whose output (not the raw PAISequential's) is what
297    the stand-in receives.
298
299    Parameters
300    ----------
301    model : nn.Module
302        The model after fuse_modules and convert_network.
303    pairs : list of (str, str)
304        The same pairs passed to fuse_modules.
305    """
306    for head_id, norm_id in pairs:
307        head = model.get_submodule(head_id.lstrip("."))
308        stand_in = model.get_submodule(norm_id.lstrip("."))
309        head.register_forward_hook(
310            lambda _module, _inputs, output, stand_in=stand_in: stand_in.record_head_output(
311                output
312            )
313        )

Make each fused norm stand-in verify its input on the first forward.

Must be called after convert_network, because by then the head's attribute holds a PAINeuronModule whose output (not the raw PAISequential's) is what the stand-in receives.

Parameters
  • model (nn.Module): The model after fuse_modules and convert_network.
  • pairs (list of (str, str)): The same pairs passed to fuse_modules.
def apply_fused_pairs(model):
316def apply_fused_pairs(model):
317    """Fuse the configured pairs and mark each head for perforation.
318
319    Reads modules_to_fuse from the config. A head that is also set to be
320    tracked is rejected, since fusing exists to perforate it.
321
322    Parameters
323    ----------
324    model : nn.Module
325        The model to modify in place.
326
327    Returns
328    -------
329    list
330        The pairs that were fused, as [head_id, norm_id] lists.
331    """
332    pairs = [list(pair) for pair in GPA.pc.get_modules_to_fuse()]
333    if not pairs:
334        return []
335    tracked = set(GPA.pc.get_module_ids_to_track())
336    for head_id, norm_id in pairs:
337        if head_id in tracked:
338            raise ValueError(
339                "Cannot fuse %s with %s: %s is set to be tracked. Remove it "
340                "from the tracked modules or un-fuse the pair." % (head_id, norm_id, head_id)
341            )
342    fuse_modules(model, pairs)
343    perforated = list(GPA.pc.get_module_ids_to_perforate())
344    for head_id, _norm_id in pairs:
345        if head_id not in perforated:
346            perforated.append(head_id)
347    GPA.pc.set_module_ids_to_perforate(perforated)
348    return pairs

Fuse the configured pairs and mark each head for perforation.

Reads modules_to_fuse from the config. A head that is also set to be tracked is rejected, since fusing exists to perforate it.

Parameters
  • model (nn.Module): The model to modify in place.
Returns
  • list: The pairs that were fused, as [head_id, norm_id] lists.
def get_pai_modules(net, depth, seen_ids=None):
351def get_pai_modules(net, depth, seen_ids=None):
352    """Get a list of all neuron modules
353
354    Parameters
355    ----------
356    net : nn.Module
357        The module to search.
358    depth : int
359        The current depth in the recursion.
360
361    Returns
362    -------
363    list
364        A list of all PAI neuron modules found in the network.
365
366    """
367    if seen_ids is None:
368        seen_ids = set()
369    all_members = net.__dir__()
370    this_list = []
371    if issubclass(type(net), nn.Sequential) or issubclass(type(net), nn.ModuleList):
372        for submodule_id, layer in net.named_children():
373            # If there is a self pointer ignore it
374            if net.get_submodule(submodule_id) is net:
375                continue
376            if type(net.get_submodule(submodule_id)) is PA.PAINeuronModule:
377                module = net.get_submodule(submodule_id)
378                if id(module) in seen_ids:
379                    continue
380                seen_ids.add(id(module))
381                this_list = this_list + [module]
382            else:
383                this_list = this_list + get_pai_modules(
384                    net.get_submodule(submodule_id), depth + 1, seen_ids
385                )
386    else:
387        for member in all_members:
388            if isinstance(getattr(type(net), member, None), property):
389                continue
390            # if the getter fails or it is a self pointer ignore it
391            try:
392                if getattr(net, member, None) is net:
393                    continue
394            except:
395                continue
396            if type(getattr(net, member, None)) is PA.PAINeuronModule:
397                module = getattr(net, member)
398                if id(module) in seen_ids:
399                    continue
400                seen_ids.add(id(module))
401                this_list = this_list + [module]
402            elif (
403                issubclass(type(getattr(net, member, None)), nn.Module)
404                or issubclass(type(getattr(net, member, None)), nn.Sequential)
405                or issubclass(type(getattr(net, member, None)), nn.ModuleList)
406            ):
407                this_list = this_list + get_pai_modules(
408                    getattr(net, member), depth + 1, seen_ids
409                )
410
411    return this_list

Get a list of all neuron modules

Parameters
  • net (nn.Module): The module to search.
  • depth (int): The current depth in the recursion.
Returns
  • list: A list of all PAI neuron modules found in the network.
def get_tracked_modules(net, depth, seen_ids=None):
414def get_tracked_modules(net, depth, seen_ids=None):
415    """Get a list of all tracked modules
416
417    Parameters
418    ----------
419    net : nn.Module
420        The module to search.
421    depth : int
422        The current depth in the recursion.
423
424    Returns
425    -------
426    list
427        A list of all tracked modules found in the network.
428
429    """
430    if seen_ids is None:
431        seen_ids = set()
432    all_members = net.__dir__()
433    this_list = []
434    if issubclass(type(net), nn.Sequential) or issubclass(type(net), nn.ModuleList):
435        for submodule_id, layer in net.named_children():
436            if net.get_submodule(submodule_id) is net:
437                continue
438            if type(net.get_submodule(submodule_id)) is PA.TrackedNeuronModule:
439                module = net.get_submodule(submodule_id)
440                if id(module) in seen_ids:
441                    continue
442                seen_ids.add(id(module))
443                this_list = this_list + [module]
444            else:
445                this_list = this_list + get_tracked_modules(
446                    net.get_submodule(submodule_id), depth + 1, seen_ids
447                )
448    else:
449        for member in all_members:
450            if isinstance(getattr(type(net), member, None), property):
451                continue
452            # if the getter fails or it is a self pointer ignore it
453            try:
454                if getattr(net, member, None) is net:
455                    continue
456            except:
457                continue
458            if type(getattr(net, member, None)) is PA.TrackedNeuronModule:
459                module = getattr(net, member)
460                if id(module) in seen_ids:
461                    continue
462                seen_ids.add(id(module))
463                this_list = this_list + [module]
464            elif issubclass(type(getattr(net, member, None)), nn.Module):
465                this_list = this_list + get_tracked_modules(
466                    getattr(net, member), depth + 1, seen_ids
467                )
468    return this_list

Get a list of all tracked modules

Parameters
  • net (nn.Module): The module to search.
  • depth (int): The current depth in the recursion.
Returns
  • list: A list of all tracked modules found in the network.
def get_pai_module_params(net, depth, seen_ids=None):
471def get_pai_module_params(net, depth, seen_ids=None):
472    """Get a list of all neuron module parameters
473
474    Parameters
475    ----------
476    net : nn.Module
477        The module to search.
478    depth : int
479        The current depth in the recursion.
480
481    Returns
482    -------
483    list
484        A list of all parameters of neuron modules found in this module.
485
486    """
487
488    if seen_ids is None:
489        seen_ids = set()
490    all_members = net.__dir__()
491    this_list = []
492    if issubclass(type(net), nn.Sequential) or issubclass(type(net), nn.ModuleList):
493        for submodule_id, layer in net.named_children():
494            if isinstance(net.get_submodule(submodule_id), PA.PAINeuronModule):  #
495                module = net.get_submodule(submodule_id)
496                if id(module) in seen_ids:
497                    continue
498                seen_ids.add(id(module))
499                for param in module.parameters():
500                    if param.requires_grad:
501                        this_list = this_list + [param]
502            else:
503                this_list = this_list + get_pai_module_params(
504                    net.get_submodule(submodule_id), depth + 1, seen_ids
505                )
506    else:
507        for member in all_members:
508            if isinstance(getattr(type(net), member, None), property):
509                continue
510            if getattr(net, member, None) == net:
511                continue
512            if isinstance(getattr(net, member, None), PA.PAINeuronModule):
513                module = getattr(net, member)
514                if id(module) in seen_ids:
515                    continue
516                seen_ids.add(id(module))
517                for param in module.parameters():
518                    if param.requires_grad:
519                        this_list = this_list + [param]
520            elif issubclass(type(getattr(net, member, None)), nn.Module):
521                this_list = this_list + get_pai_module_params(
522                    getattr(net, member), depth + 1, seen_ids
523                )
524    return this_list

Get a list of all neuron module parameters

Parameters
  • net (nn.Module): The module to search.
  • depth (int): The current depth in the recursion.
Returns
  • list: A list of all parameters of neuron modules found in this module.
def get_pai_network_params(net):
527def get_pai_network_params(net):
528    """Get a list of all neuron module parameters
529
530    Parameters
531    ----------
532    net : nn.Module
533        The full model to search.
534
535    Returns
536    -------
537    list
538        A list of all parameters of neuron modules found in the network.
539
540    """
541    param_list = get_pai_module_params(net, 0)
542    return param_list

Get a list of all neuron module parameters

Parameters
  • net (nn.Module): The full model to search.
Returns
  • list: A list of all parameters of neuron modules found in the network.
parameter_groups_requested = False
def get_parameter_groups(params, lr=None):
549def get_parameter_groups(params, lr=None):
550    """Split optimizer parameters so that dendrites train at a higher learning rate.
551
552    Dendrite parameters ("dendrite" and "tree" parameter_type) are moved out of
553    each parameter group into a copy of that group with its learning rate
554    multiplied by GPA.pc.get_dendrite_lr_multiplier().  A dendrite's output
555    weights start at 0, so at a small learning rate a new dendrite barely changes
556    the network.  Use the result as the params of the optimizer, and call this
557    again whenever the optimizer is rebuilt after dendrites were added.
558    setup_optimizer calls this itself.
559
560    Parameters
561    ----------
562    params : iterable
563        Parameters or parameter groups, as they would be passed to a torch optimizer.
564    lr : float, optional
565        The optimizer's learning rate, for parameter groups that do not set their own.
566
567    Returns
568    -------
569    iterable
570        params itself if the multiplier is 1 or there are no dendrite parameters.
571        Otherwise a list of parameter groups: the given groups without their dendrite
572        parameters, followed by the groups of dendrite parameters.
573    """
574    global parameter_groups_requested
575    parameter_groups_requested = True
576    multiplier = GPA.pc.get_dendrite_lr_multiplier()
577    if multiplier == 1:
578        return params
579    params = list(params)
580    groups = params if params and isinstance(params[0], dict) else [{"params": params}]
581    if not any(
582        PA.is_dendrite_parameter(p) for group in groups for p in group["params"]
583    ):
584        return params
585    neuron_groups = []
586    dendrite_groups = []
587    for group in groups:
588        group_params = list(group["params"])
589        neuron_params = [p for p in group_params if not PA.is_dendrite_parameter(p)]
590        dendrite_params = [p for p in group_params if PA.is_dendrite_parameter(p)]
591        if neuron_params:
592            neuron_groups.append({**group, "params": neuron_params})
593        if dendrite_params:
594            group_lr = group.get("lr", lr)
595            if group_lr is None:
596                raise ValueError(
597                    "get_parameter_groups needs the optimizer's learning rate to set "
598                    "the dendrite learning rate, pass it as lr"
599                )
600            dendrite_groups.append(
601                {**group, "params": dendrite_params, "lr": group_lr * multiplier}
602            )
603    return neuron_groups + dendrite_groups

Split optimizer parameters so that dendrites train at a higher learning rate.

Dendrite parameters ("dendrite" and "tree" parameter_type) are moved out of each parameter group into a copy of that group with its learning rate multiplied by GPA.pc.get_dendrite_lr_multiplier(). A dendrite's output weights start at 0, so at a small learning rate a new dendrite barely changes the network. Use the result as the params of the optimizer, and call this again whenever the optimizer is rebuilt after dendrites were added. setup_optimizer calls this itself.

Parameters
  • params (iterable): Parameters or parameter groups, as they would be passed to a torch optimizer.
  • lr (float, optional): The optimizer's learning rate, for parameter groups that do not set their own.
Returns
  • iterable: params itself if the multiplier is 1 or there are no dendrite parameters. Otherwise a list of parameter groups: the given groups without their dendrite parameters, followed by the groups of dendrite parameters.
def get_neuron_learning_rate(optimizer):
606def get_neuron_learning_rate(optimizer):
607    """Get the learning rate of the neurons, ignoring dendrite parameter groups.
608
609    Parameters
610    ----------
611    optimizer : torch.optim.Optimizer
612        The optimizer, possibly with dendrite groups from get_parameter_groups.
613
614    Returns
615    -------
616    float
617        The learning rate of the first parameter group that is not only dendrite parameters.
618    """
619    for param_group in optimizer.param_groups:
620        if not all(PA.is_dendrite_parameter(p) for p in param_group["params"]):
621            return param_group["lr"]
622    return optimizer.param_groups[0]["lr"]

Get the learning rate of the neurons, ignoring dendrite parameter groups.

Parameters
  • optimizer (torch.optim.Optimizer): The optimizer, possibly with dendrite groups from get_parameter_groups.
Returns
  • float: The learning rate of the first parameter group that is not only dendrite parameters.
def replace_predefined_modules(start_module):
625def replace_predefined_modules(start_module):
626    """Replace a module with the module from globals list
627
628    Parameters
629    ----------
630    start_module : nn.Module
631        The module to replace.
632
633    Returns
634    -------
635    nn.Module
636        The replaced module.
637
638    """
639    index = GPA.pc.get_modules_to_replace().index(type(start_module))
640    return GPA.pc.get_replacement_modules()[index](start_module)

Replace a module with the module from globals list

Parameters
  • start_module (nn.Module): The module to replace.
Returns
  • nn.Module: The replaced module.
def scan_module_aliases(net):
643def scan_module_aliases(net):
644    """Find alias module paths that point to already-seen module instances.
645
646    Parameters
647    ----------
648    net : Any PyTorch Module.
649
650    Returns
651    -------
652    dict[str, str]
653        Mapping of alias module paths to their canonical module paths.
654    """
655    canonical = {}
656    aliases = {}
657    for name, module in net.named_modules(remove_duplicate=False):
658        if name == "":
659            continue
660        sub_name = "." + name
661        module_id = id(module)
662        if module_id in canonical:
663            aliases[sub_name] = canonical[module_id]
664        else:
665            canonical[module_id] = sub_name
666    return aliases

Find alias module paths that point to already-seen module instances.

Parameters
  • net (Any PyTorch Module.):
Returns
  • dict[str, str]: Mapping of alias module paths to their canonical module paths.
def convert_module( net, depth, name_so_far, converted_list, converted_names_list, neuron_module_class, tracked_module_class, config_setup=False):
 731def convert_module(
 732    net,
 733    depth,
 734    name_so_far,
 735    converted_list,
 736    converted_names_list,
 737    neuron_module_class,
 738    tracked_module_class,
 739    config_setup=False,
 740):
 741    """Recursive function to do all conversion of modules to wrappers of modules
 742
 743    This is the function that goes through all of the module lists from
 744    the globals file and does all the conversion and replacements to
 745    setup the dendrite scaffolding as instructed.
 746
 747    Parameters
 748    ----------
 749    net : nn.Module
 750        The module to convert.
 751    depth : int
 752        The current depth in the recursion.
 753    name_so_far : str
 754        The name of the module so far in the recursion.
 755    converted_list : list
 756        A list of already converted module ids to avoid infinite loops.
 757    converted_names_list : list
 758        A corresponding list to help debug duplicate conversions
 759
 760    Returns
 761    -------
 762    nn.Module
 763        The converted module.
 764
 765    """
 766    if GPA.pc.get_verbose():
 767        print("calling convert on %s depth %d" % (net, depth))
 768        print(
 769            "calling convert on %s: %s, depth %d"
 770            % (name_so_far, type(net).__name__, depth)
 771        )
 772    if isinstance(net, neuron_module_class) or (
 773        (tracked_module_class is not None) and isinstance(net, tracked_module_class)
 774    ):
 775        if GPA.pc.get_verbose():
 776            print(
 777                "This is only being called because something in your model "
 778                "is pointed to twice by two different variables. Highest "
 779                "thing on the list is one of the duplicates"
 780            )
 781        return net
 782    if depth == 0 and name_so_far == "":
 783        aliases = scan_module_aliases(net)
 784        existing_not_save = set(GPA.pc.get_module_names_to_not_save())
 785        aliases_to_skip = [
 786            alias for alias in aliases.keys() if alias not in existing_not_save
 787        ]
 788        if aliases_to_skip and not config_setup:
 789            GPA.pc.append_module_names_to_not_save(aliases_to_skip)
 790            print(
 791                "Auto-detected duplicate module aliases via named_modules; "
 792                "keeping first-seen paths and skipping:"
 793            )
 794            for alias in aliases_to_skip:
 795                print(" - %s (keeps %s)" % (alias, aliases[alias]))
 796    if depth == 0 and name_so_far == "":
 797        _reset_block_rule_state()
 798    _register_block_rule_ids(net, name_so_far)
 799    all_members = net.__dir__()
 800    if GPA.pc.get_extra_verbose():
 801        print("all members:")
 802        for member in all_members:
 803            print(" - %s" % member)
 804    if issubclass(type(net), nn.Sequential) or issubclass(type(net), nn.ModuleList):
 805        for submodule_id, layer in net.named_children():
 806            sub_name = name_so_far + "." + str(submodule_id)
 807            if _id_to_track(sub_name):
 808                if GPA.pc.get_verbose():
 809                    print("Seq ID is in track IDs: %s" % sub_name)
 810                if tracked_module_class is None:
 811                    continue
 812                if config_setup:
 813                    net.get_submodule(submodule_id).pai_mode = "tracked"
 814                else:
 815                    setattr(
 816                        net,
 817                        submodule_id,
 818                        tracked_module_class(net.get_submodule(submodule_id), sub_name),
 819                    )
 820                continue
 821            if _id_to_perforate(sub_name):
 822                if GPA.pc.get_verbose():
 823                    print("Seq ID is in convert IDs: %s" % sub_name)
 824                if config_setup:
 825                    net.get_submodule(submodule_id).pai_mode = "perforated"
 826                else:
 827                    setattr(
 828                        net,
 829                        submodule_id,
 830                        neuron_module_class(net.get_submodule(submodule_id), sub_name),
 831                    )
 832                continue
 833            if type(net.get_submodule(submodule_id)) in GPA.pc.get_modules_to_replace():
 834                if GPA.pc.get_verbose():
 835                    print(
 836                        "Seq sub is in replacement module so replacing: %s" % sub_name
 837                    )
 838                if config_setup:
 839                    net.get_submodule(submodule_id).pai_mode = "replaced"
 840                else:
 841                    setattr(
 842                        net,
 843                        submodule_id,
 844                        replace_predefined_modules(net.get_submodule(submodule_id)),
 845                    )
 846            if (
 847                type(net.get_submodule(submodule_id)) in GPA.pc.get_modules_to_track()
 848            ) or (
 849                type(net.get_submodule(submodule_id)).__name__
 850                in GPA.pc.get_module_names_to_track()
 851            ):
 852                if GPA.pc.get_verbose():
 853                    print(
 854                        "Seq sub is in tracking list so initiating tracked for: %s"
 855                        % sub_name
 856                    )
 857                if tracked_module_class is None:
 858                    continue
 859                if config_setup:
 860                    net.get_submodule(submodule_id).pai_mode = "tracked"
 861                else:
 862                    setattr(
 863                        net,
 864                        submodule_id,
 865                        tracked_module_class(net.get_submodule(submodule_id), sub_name),
 866                    )
 867            elif (
 868                type(net.get_submodule(submodule_id))
 869                in GPA.pc.get_modules_to_perforate()
 870                or type(net.get_submodule(submodule_id)).__name__
 871                in GPA.pc.get_module_names_to_perforate()
 872            ):
 873                if GPA.pc.get_verbose():
 874                    print(
 875                        "Seq sub is in conversion list so initing PAI for: "
 876                        "%s" % sub_name
 877                    )
 878                if (
 879                    issubclass(
 880                        type(net.get_submodule(submodule_id)),
 881                        torch.nn.modules.batchnorm._BatchNorm,
 882                    )
 883                    or issubclass(
 884                        type(net.get_submodule(submodule_id)),
 885                        torch.nn.modules.instancenorm._InstanceNorm,
 886                    )
 887                    or issubclass(
 888                        type(net.get_submodule(submodule_id)),
 889                        torch.nn.modules.normalization.LayerNorm,
 890                    )
 891                ):
 892                    print(
 893                        "You have an unwrapped normalization layer, this "
 894                        "is not recommended: " + name_so_far
 895                    )
 896                    pdb.set_trace()
 897                if config_setup:
 898                    net.get_submodule(submodule_id).pai_mode = "perforated"
 899                else:
 900                    setattr(
 901                        net,
 902                        submodule_id,
 903                        neuron_module_class(net.get_submodule(submodule_id), sub_name),
 904                    )
 905            else:
 906                if net != net.get_submodule(submodule_id):
 907                    converted_list += [id(net.get_submodule(submodule_id))]
 908                    converted_names_list += [sub_name]
 909                    if GPA.pc.get_verbose():
 910                        print(
 911                            "sub is module but in no lists so going deeper: %s"
 912                            % sub_name
 913                        )
 914
 915                    setattr(
 916                        net,
 917                        submodule_id,
 918                        convert_module(
 919                            net.get_submodule(submodule_id),
 920                            depth + 1,
 921                            sub_name,
 922                            converted_list,
 923                            converted_names_list,
 924                            neuron_module_class,
 925                            tracked_module_class,
 926                            config_setup,
 927                        ),
 928                    )
 929                # else:
 930                # print('%s is a self pointer so skipping' % (name_so_far + '[' + str(submodule_id) + ']'))
 931    elif type(net) in GPA.pc.get_modules_to_track():
 932        # print('skipping type for returning from call to: %s' % (name_so_far))
 933        return net
 934    else:
 935        for member in all_members:
 936            if isinstance(getattr(type(net), member, None), property):
 937                continue
 938            # Immediately check if able to get the member, if not skip it
 939            try:
 940                getattr(net, member, None)
 941            except:
 942                continue
 943            sub_name = name_so_far + "." + member
 944            member_obj = getattr(net, member, None)
 945
 946            if isinstance(member_obj, (torch.nn.Parameter, torch.nn.parameter.Parameter)):
 947                if sub_name in GPA.pc.get_parameter_ids_to_track():
 948                    if GPA.pc.get_verbose():
 949                        print("tracking parameter by ID: %s" % sub_name)
 950                    if config_setup:
 951                        member_obj.pai_mode = "tracked"
 952                    else:
 953                        member_obj.parameter_type = "neuron"
 954                        member_obj.wrapped = True
 955                continue
 956
 957            # Track module object ids once at this level so duplicate aliases are
 958            # caught consistently (including direct children of the root module).
 959            if isinstance(member_obj, nn.Module):
 960                if id(member_obj) in converted_list:
 961                    original_sub_name = converted_names_list[
 962                        converted_list.index(id(member_obj))
 963                    ]
 964                    print(
 965                        "The following module has a duplicate pointer within "
 966                        "your model: %s" % sub_name
 967                    )
 968                    print("Keeping first pointer: %s" % original_sub_name)
 969                    print("Skipping duplicate pointer: %s" % sub_name)
 970                    print(
 971                        "If you prefer to keep %s and skip %s, add %s to module_names_to_not_save before convert."
 972                        % (sub_name, original_sub_name, original_sub_name)
 973                    )
 974                    if not config_setup:
 975                        GPA.pc.append_module_names_to_not_save([sub_name])
 976                    continue
 977                converted_list += [id(member_obj)]
 978                converted_names_list += [sub_name]
 979            if _id_to_track(sub_name):
 980                if GPA.pc.get_verbose():
 981                    print("Seq ID is in track IDs: %s" % sub_name)
 982                if tracked_module_class is None:
 983                    continue
 984                if config_setup:
 985                    getattr(net, member).pai_mode = "tracked"
 986                else:
 987                    setattr(
 988                        net, member, tracked_module_class(getattr(net, member), sub_name)
 989                    )
 990                continue
 991            if _id_to_perforate(sub_name):
 992                if GPA.pc.get_verbose():
 993                    print("Seq ID is in convert IDs: %s" % sub_name)
 994                if config_setup:
 995                    getattr(net, member).pai_mode = "perforated"
 996                else:
 997                    setattr(
 998                        net, member, neuron_module_class(getattr(net, member), sub_name)
 999                    )
1000                continue
1001            if id(getattr(net, member, None)) == id(net):
1002                if GPA.pc.get_verbose():
1003                    print("member sub is a self pointer: %s" % sub_name)
1004                continue
1005            if sub_name in GPA.pc.get_module_names_to_not_save():
1006                if GPA.pc.get_verbose():
1007                    print("Skipping %s during convert" % sub_name)
1008                else:
1009                    if sub_name == ".base_model":
1010                        print(
1011                            "By default skipping base_model. See "
1012                            '"Safetensors Errors" section of '
1013                            "customization.md to include it."
1014                        )
1015                continue
1016            if type(getattr(net, member, None)) in GPA.pc.get_modules_to_replace():
1017                if GPA.pc.get_verbose():
1018                    print("sub is in replacement module so replacing: %s" % sub_name)
1019                if config_setup:
1020                    getattr(net, member).pai_mode = "replaced"
1021                else:
1022                    setattr(
1023                        net, member, replace_predefined_modules(getattr(net, member, None))
1024                    )
1025            if (
1026                type(getattr(net, member, None)) in GPA.pc.get_modules_to_track()
1027                or type(getattr(net, member, None)).__name__
1028                in GPA.pc.get_module_names_to_track()
1029                or sub_name in GPA.pc.get_module_ids_to_track()
1030            ):
1031                if GPA.pc.get_verbose():
1032                    print(
1033                        "sub is in tracking list so initiating tracked for: %s"
1034                        % sub_name
1035                    )
1036                if tracked_module_class is None:
1037                    continue
1038                if config_setup:
1039                    getattr(net, member).pai_mode = "tracked"
1040                else:
1041                    setattr(
1042                        net, member, tracked_module_class(getattr(net, member), sub_name)
1043                    )
1044            elif (
1045                type(getattr(net, member, None)) in GPA.pc.get_modules_to_perforate()
1046                or type(getattr(net, member, None)).__name__
1047                in GPA.pc.get_module_names_to_perforate()
1048                or (sub_name in GPA.pc.get_module_ids_to_perforate())
1049            ):
1050                if GPA.pc.get_verbose():
1051                    print(
1052                        "sub is in conversion list so initiating PAI for: %s" % sub_name
1053                    )
1054                if config_setup:
1055                    getattr(net, member).pai_mode = "perforated"
1056                else:
1057                    setattr(
1058                        net,
1059                        member,
1060                        neuron_module_class(getattr(net, member), sub_name),
1061                    )
1062            elif (
1063                issubclass(type(getattr(net, member, None)), nn.Module)
1064                or issubclass(type(getattr(net, member, None)), nn.Sequential)
1065                or issubclass(type(getattr(net, member, None)), nn.ModuleList)
1066            ):
1067                if net != getattr(net, member):
1068                    if GPA.pc.get_verbose():
1069                        print(
1070                            "sub is module but in no lists so going deeper: %s"
1071                            % sub_name
1072                        )
1073                    setattr(
1074                        net,
1075                        member,
1076                        convert_module(
1077                            getattr(net, member),
1078                            depth + 1,
1079                            sub_name,
1080                            converted_list,
1081                            converted_names_list,
1082                            neuron_module_class,
1083                            tracked_module_class,
1084                            config_setup,
1085                        ),
1086                    )
1087            if (
1088                issubclass(
1089                    type(getattr(net, member, None)),
1090                    torch.nn.modules.batchnorm._BatchNorm,
1091                )
1092                or issubclass(
1093                    type(getattr(net, member, None)),
1094                    torch.nn.modules.instancenorm._InstanceNorm,
1095                )
1096                or issubclass(
1097                    type(getattr(net, member, None)),
1098                    torch.nn.modules.normalization.LayerNorm,
1099                )
1100            ):
1101                if not GPA.pc.get_unwrapped_modules_confirmed():
1102                    print(
1103                        "potentially found a norm Layer that "
1104                        "is not accounted for, this is not recommended: %s" % (sub_name)
1105                    )
1106                    print(
1107                        "Set GPA.pc.set_unwrapped_modules_confirmed(True) to skip "
1108                        "this next time only if you are unable to debug"
1109                    )
1110                    print(
1111                        "inspect your network to "
1112                        "see what the module type containing this layer is."
1113                    )
1114                    print("Then do one of the following:")
1115                    print(
1116                        " - Add the module type to "
1117                        "GPA.pc.get_module_names_to_perforate() to wrap it entirely"
1118                    )
1119                    print(
1120                        " - If the norm layer is part of a sequential wrap "
1121                        "it and the previous layer in a PAISequential"
1122                    )
1123                    print(
1124                        " - If you do not want to add dendrites to this "
1125                        "module add the type to GPA.pc.get_module_names_to_track()"
1126                    )
1127                    pdb.set_trace()
1128            else:
1129                if GPA.pc.get_verbose():
1130                    if member[0] != "_" or GPA.pc.get_extra_verbose() is True:
1131                        print("not calling convert on %s depth %d" % (member, depth))
1132    if GPA.pc.get_verbose():
1133        print("returning from call to: %s" % (name_so_far))
1134    return net

Recursive function to do all conversion of modules to wrappers of modules

This is the function that goes through all of the module lists from the globals file and does all the conversion and replacements to setup the dendrite scaffolding as instructed.

Parameters
  • net (nn.Module): The module to convert.
  • depth (int): The current depth in the recursion.
  • name_so_far (str): The name of the module so far in the recursion.
  • converted_list (list): A list of already converted module ids to avoid infinite loops.
  • converted_names_list (list): A corresponding list to help debug duplicate conversions
Returns
  • nn.Module: The converted module.
def convert_network(net, layer_name=''):
1137def convert_network(net, layer_name=""):
1138    """Function that calls convert_module and checks results
1139
1140    Parameters
1141    ----------
1142    net : nn.Module
1143        The network to convert.
1144    layer_name : str, optional
1145        The name of the layer if converting a single layer, by default ""
1146
1147    Returns
1148    -------
1149    nn.Module
1150        The converted network.
1151
1152    """
1153    if GPA.pc.get_perforated_backpropagation():
1154        UPB.initialize_pb()
1155    PA.set_main_parameters(net)
1156    if type(net) in GPA.pc.get_modules_to_replace():
1157        net = replace_predefined_modules(net)
1158    if (type(net) in GPA.pc.get_modules_to_perforate()) or (
1159        type(net).__name__ in GPA.pc.get_module_names_to_perforate()
1160    ):
1161        if layer_name == "":
1162            print(
1163                "converting a single layer without a name, add a "
1164                "layer_name param to the call"
1165            )
1166            sys.exit(-1)
1167        net = PA.PAINeuronModule(net, layer_name)
1168    else:
1169        net = convert_module(
1170            net, 0, "", [], [], PA.PAINeuronModule, PA.TrackedNeuronModule
1171        )
1172        _warn_unused_block_rules()
1173    if GPA.pai_tracker.member_vars["doing_pai"]:
1174        missed_ones = []
1175        tracked_ones = []
1176        for name, param in net.named_parameters():
1177            wrapped = "wrapped" in param.__dir__()
1178            if wrapped:
1179                if GPA.pc.get_verbose():
1180                    print("param %s is now wrapped" % (name))
1181            else:
1182                tracked = "tracked" in param.__dir__()
1183                if tracked:
1184                    tracked_ones.append(name)
1185                else:
1186                    missed_ones.append(name)
1187        if (
1188            len(missed_ones) != 0 or len(tracked_ones) != 0
1189        ) and GPA.pc.get_unwrapped_modules_confirmed() is False:
1190            print(
1191                "\n------------------------------------------------------------------"
1192            )
1193            print(
1194                "%d params are not wrapped, %d params are not tracked or wrapped."
1195                % (len(tracked_ones), len(missed_ones))
1196            )
1197            if GPA.pc.get_verbose():
1198                print(
1199                    "------------------------------------------------------------------"
1200                )
1201                print(
1202                    "The following params are not wrapped.\n------------------------------------------------------------------"
1203                )
1204                for name in tracked_ones:
1205                    print("." + name)
1206                print(
1207                    "\n------------------------------------------------------------------"
1208                )
1209                print(
1210                    "The following params are not tracked or wrapped.\n------------------------------------------------------------------"
1211                )
1212                for name in missed_ones:
1213                    print("." + name)
1214            print(
1215                "\n------------------------------------------------------------------"
1216            )
1217            print(
1218                "Modules that are not wrapped will not have Dendrites to optimize them"
1219            )
1220            print(
1221                "Modules modules that are not tracked can cause errors and is NOT recommended"
1222            )
1223            print(
1224                "Any modules in the second list should be added to module_names_to_track"
1225            )
1226
1227            print(
1228                "Set GPA.pc.set_unwrapped_modules_confirmed(True) to skip this next time"
1229            )
1230            print(
1231                "Inspect your network and see what the module types of these values are to add them to PGB.module_names_to_perforate"
1232            )
1233            # If did miss some then set trace to debug
1234            if len(missed_ones) != 0:
1235                print(
1236                    "------------------------------------------------------------------\nType 'c' + enter to continue the run to confirm you do not want them to be refined"
1237                )
1238
1239                pdb.set_trace()
1240                print("confirmed")
1241    net.register_buffer(
1242        "tracker_string",
1243        torch.tensor([], dtype=torch.uint8, device=next((p.device for p in net.parameters()), None)),
1244    )
1245    return net

Function that calls convert_module and checks results

Parameters
  • net (nn.Module): The network to convert.
  • layer_name (str, optional): The name of the layer if converting a single layer, by default ""
Returns
  • nn.Module: The converted network.
def string_to_tensor(string):
1248def string_to_tensor(string):
1249    """Helper function to convert a layer_tracker into a string
1250
1251    This is required for safetensors saving
1252
1253    Parameters
1254    ----------
1255    string : str
1256        The string to convert.
1257
1258    Returns
1259    -------
1260    torch.Tensor
1261        The converted tensor.
1262
1263    """
1264    ords = list(map(ord, string))
1265    ords = torch.tensor(ords, dtype=torch.uint8)
1266    return ords

Helper function to convert a layer_tracker into a string

This is required for safetensors saving

Parameters
  • string (str): The string to convert.
Returns
  • torch.Tensor: The converted tensor.
def string_from_tensor(string_tensor):
1269def string_from_tensor(string_tensor):
1270    """Convert a tensor back into a string
1271
1272    Parameters
1273    ----------
1274    string_tensor : torch.Tensor
1275        The tensor to convert.
1276
1277    Returns
1278    -------
1279    str
1280        The converted string.
1281
1282    """
1283    ords = string_tensor.tolist()
1284    to_return = ""
1285    # Doing block processing like this helps with memory errors
1286    while len(ords) != 0:
1287        remaining_ords = ords[100000:]
1288        ords = ords[:100000]
1289        to_append = "".join(map(chr, ords))
1290        to_return = to_return + to_append
1291        ords = remaining_ords
1292    return to_return

Convert a tensor back into a string

Parameters
  • string_tensor (torch.Tensor): The tensor to convert.
Returns
  • str: The converted string.
def save_system(net, folder, name):
1295def save_system(net, folder, name):
1296    """Save the entire system
1297
1298    This saves the network itself as well as the tracker information
1299
1300    Parameters
1301    ----------
1302    net : nn.Module
1303        The network to save.
1304    folder : str
1305        The folder to save the network in.
1306    name : str
1307        The name to save the network under.
1308
1309    Returns
1310    -------
1311    None
1312
1313    """
1314    if GPA.pc.get_verbose():
1315        print("saving system %s" % name)
1316    temp = string_to_tensor(GPA.pai_tracker.to_string())
1317    if hasattr(net, "tracker_string"):
1318        net.tracker_string = string_to_tensor(GPA.pai_tracker.to_string()).to(
1319            next(net.parameters()).device
1320        )
1321    else:
1322        net.register_buffer(
1323            "tracker_string",
1324            string_to_tensor(GPA.pai_tracker.to_string()).to(
1325                next(net.parameters()).device
1326            ),
1327        )
1328    # Before saving the tracker must be cleared to not contain pointers to the
1329    # models modules
1330    old_list = GPA.pai_tracker.neuron_module_vector
1331    GPA.pai_tracker.neuron_module_vector = []
1332    save_net(net, folder, name)
1333    GPA.pai_tracker.neuron_module_vector = old_list
1334    pai_save_system(net, folder, name)

Save the entire system

This saves the network itself as well as the tracker information

Parameters
  • net (nn.Module): The network to save.
  • folder (str): The folder to save the network in.
  • name (str): The name to save the network under.
Returns
  • None
def load_system( net, folder, name, load_from_restart=False, switch_call=False, load_from_manual_save=False, reset_best_scores=True):
1337def load_system(
1338    net,
1339    folder,
1340    name,
1341    load_from_restart=False,
1342    switch_call=False,
1343    load_from_manual_save=False,
1344    reset_best_scores=True,
1345):
1346    """Load the entire system
1347
1348    This is what should be used to load a saved system and restart training
1349
1350    Parameters
1351    ----------
1352    net : nn.Module
1353        The network to load into.
1354    folder : str
1355        The folder to load the network from.
1356    name : str
1357        The name to load the network from.
1358    load_from_restart : bool, optional
1359        Whether this is being loaded from an automatic restart, by default False
1360    switch_call : bool, optional
1361        Whether this is being called from a switch, by default False
1362    load_from_manual_save : bool, optional
1363        Whether this is being loaded from a manual save, by default False
1364    reset_best_scores : bool, optional
1365        Whether to clear current_best_validation_score and restart
1366        epoch_last_improved at the loaded epoch, by default True. Pass False
1367        to keep the values saved in the checkpoint.
1368
1369    Returns
1370    -------
1371    nn.Module
1372        The loaded network.
1373
1374    Notes
1375    -----
1376    If you manually call save_system then load_from_manual_save should be True
1377
1378    """
1379    if GPA.pc.get_verbose():
1380        print("loading system %s" % name)
1381    if not switch_call and not load_from_manual_save:
1382        print("Loading system %s (user initiated)" % name)
1383    net = load_net(net, folder, name)
1384    GPA.pai_tracker.reset_module_vector(net, load_from_restart)
1385
1386    GPA.pai_tracker.from_string(string_from_tensor(net.tracker_string))
1387    GPA.pai_tracker.saved_time = time.time()
1388    GPA.pai_tracker.loaded = True
1389    if reset_best_scores:
1390        GPA.pai_tracker.member_vars["current_best_validation_score"] = 0
1391        GPA.pai_tracker.member_vars["epoch_last_improved"] = GPA.pai_tracker.member_vars[
1392            "num_epochs_run"
1393        ]
1394    if GPA.pc.get_verbose():
1395        print(
1396            "after loading epoch last improved is %d mode is %c"
1397            % (
1398                GPA.pai_tracker.member_vars["epoch_last_improved"],
1399                GPA.pai_tracker.member_vars["mode"],
1400            )
1401        )
1402
1403    # Saves always take place before the call to start_epoch so call it here
1404    # when loading to correct off by 1 problems
1405    if (not switch_call) and (not load_from_manual_save):
1406        GPA.pai_tracker.start_epoch(internal_call=True)
1407    return net

Load the entire system

This is what should be used to load a saved system and restart training

Parameters
  • net (nn.Module): The network to load into.
  • folder (str): The folder to load the network from.
  • name (str): The name to load the network from.
  • load_from_restart (bool, optional): Whether this is being loaded from an automatic restart, by default False
  • switch_call (bool, optional): Whether this is being called from a switch, by default False
  • load_from_manual_save (bool, optional): Whether this is being loaded from a manual save, by default False
  • reset_best_scores (bool, optional): Whether to clear current_best_validation_score and restart epoch_last_improved at the loaded epoch, by default True. Pass False to keep the values saved in the checkpoint.
Returns
  • nn.Module: The loaded network.
Notes

If you manually call save_system then load_from_manual_save should be True

def load_pretrained_model(net, folder, name, remove_dendrite_scaffolding=False):
1410def load_pretrained_model(
1411    net,
1412    folder,
1413    name,
1414    remove_dendrite_scaffolding=False,
1415):
1416    """Load a pretrained perforated model and reset tracker for fresh training.
1417
1418    This function loads a pretrained model's weights and dendrite structure while
1419    resetting all tracker state (epochs, switch history, etc.) to start training
1420    from scratch on a new task. This is useful for transfer learning where you want
1421    pretrained weights but need fresh training dynamics.
1422
1423    Parameters
1424    ----------
1425    net : nn.Module
1426        The network to load into.
1427    folder : str
1428        The folder containing the pretrained model.
1429    name : str
1430        The name of the checkpoint to load (e.g., 'best_model', 'beforeSwitch_0').
1431    remove_dendrite_scaffolding : bool, optional
1432        If True, removes dendrite scaffolding for inference or finetuning without
1433        adding more dendrites using blockwise_network and refresh_net. Default False.
1434
1435    Returns
1436    -------
1437    nn.Module
1438        The loaded network with reset tracker state.
1439
1440    Examples
1441    --------
1442    Load pretrained weights for continued dendrite training:
1443    >>> model = load_pretrained_model(model, "pretrained-prefc", "beforeSwitch_0")
1444
1445    Load pretrained weights for finetuning without adding more dendrites:
1446    >>> model = load_pretrained_model(model, "pretrained-prefc", "best_model", 
1447    ...                               remove_dendrite_scaffolding=True)
1448
1449    Notes
1450    -----
1451    This function:
1452    - Loads model weights and dendrite structure from checkpoint
1453    - Resets all epoch counters to -1 (will become 0 after first start_epoch)
1454    - Resets switch history and validation score tracking
1455    - Clears accuracy/loss history arrays
1456    - Optionally removes dendrite scaffolding (no more dendrite additions)
1457    
1458    The tracker is reset to behave as if starting fresh training, while keeping
1459    the learned weights and dendrite structure from the pretrained model.
1460    """
1461    from perforatedai import globals_perforatedai as GPA
1462    
1463    if GPA.pc.get_verbose():
1464        print(f"Loading pretrained model from {folder}/{name}")
1465    
1466    # Load the model weights and dendrite structure
1467    net = load_system(net, folder, name, load_from_manual_save=True)
1468    
1469    if GPA.pc.get_verbose():
1470        print("Resetting tracker state for fresh training...")
1471    
1472    # Reset structural training state to true initial values.
1473    # Keeping pretrained architecture/weights while zeroing cycle counters avoids
1474    # stale dendrite bookkeeping referencing empty score buffers.
1475    GPA.pai_tracker.reset_module_vector(net, load_from_restart=True)
1476    GPA.pai_tracker.member_vars["mode"] = "n"
1477    GPA.pai_tracker.member_vars["num_dendrites_added"] = 0
1478    GPA.pai_tracker.member_vars["num_dendrites_integrated"] = 0
1479    GPA.pai_tracker.member_vars["num_cycles"] = 0
1480    GPA.pai_tracker.member_vars["num_dendrite_tries"] = 0
1481    GPA.pai_tracker.member_vars["current_n_set_global_best"] = True
1482
1483    # Reset epoch counters
1484    GPA.pai_tracker.member_vars["num_epochs_run"] = -1
1485    GPA.pai_tracker.member_vars["total_epochs_run"] = -1
1486    GPA.pai_tracker.member_vars["epoch_last_improved"] = 0
1487    GPA.pai_tracker.member_vars["last_switch"] = 0
1488    GPA.pai_tracker.member_vars["manual_train_switch"] = False
1489    
1490    # Reset switch history
1491    GPA.pai_tracker.member_vars["switch_epochs"] = []
1492    GPA.pai_tracker.member_vars["n_switch_epochs"] = []
1493    GPA.pai_tracker.member_vars["p_switch_epochs"] = []
1494    GPA.pai_tracker.member_vars["param_counts"] = []
1495    
1496    # Reset validation scores and tracking
1497    GPA.pai_tracker.member_vars["current_best_validation_score"] = 0
1498    GPA.pai_tracker.member_vars["global_best_validation_score"] = 0
1499    GPA.pai_tracker.member_vars["running_accuracy"] = 0
1500    
1501    # Clear accuracy/loss history arrays
1502    GPA.pai_tracker.member_vars["accuracies"] = []
1503    GPA.pai_tracker.member_vars["last_improved_accuracies"] = []
1504    GPA.pai_tracker.member_vars["test_accuracies"] = []
1505    GPA.pai_tracker.member_vars["n_accuracies"] = []
1506    GPA.pai_tracker.member_vars["p_accuracies"] = []
1507    GPA.pai_tracker.member_vars["running_accuracies"] = []
1508    GPA.pai_tracker.member_vars["training_loss"] = []
1509    GPA.pai_tracker.member_vars["training_learning_rates"] = []
1510    GPA.pai_tracker.member_vars["test_scores"] = []
1511    
1512    # Clear extra scores
1513    GPA.pai_tracker.member_vars["extra_scores"] = {}
1514    GPA.pai_tracker.member_vars["extra_scores_without_graphing"] = {}
1515    GPA.pai_tracker.member_vars["n_extra_scores"] = {}
1516    
1517    # Keep per-layer dendrite score buffers initialized by reset_module_vector.
1518    
1519    # Clear timing arrays
1520    GPA.pai_tracker.member_vars["n_epoch_times"] = []
1521    GPA.pai_tracker.member_vars["p_epoch_times"] = []
1522    GPA.pai_tracker.member_vars["n_train_times"] = []
1523    GPA.pai_tracker.member_vars["p_train_times"] = []
1524    GPA.pai_tracker.member_vars["n_val_times"] = []
1525    GPA.pai_tracker.member_vars["p_val_times"] = []
1526    
1527    # Clear overwritten tracking
1528    GPA.pai_tracker.member_vars["overwritten_extras"] = []
1529    GPA.pai_tracker.member_vars["overwritten_vals"] = []
1530    GPA.pai_tracker.member_vars["overwritten_epochs"] = 0
1531    
1532    # Reset learning rate search state
1533    GPA.pai_tracker.member_vars["initial_lr_test_epoch_count"] = -1
1534    GPA.pai_tracker.member_vars["current_n_learning_rate_initial_skip_steps"] = 0
1535    GPA.pai_tracker.member_vars["last_max_learning_rate_steps"] = 0
1536    GPA.pai_tracker.member_vars["last_max_learning_rate_value"] = -1
1537    GPA.pai_tracker.member_vars["current_cycle_lr_max_scores"] = []
1538    GPA.pai_tracker.member_vars["current_step_count"] = 0
1539    GPA.pai_tracker.member_vars["committed_to_initial_rate"] = True
1540    GPA.pai_tracker.member_vars["best_mean_score_improved_this_epoch"] = 0
1541    GPA.pai_tracker.member_vars["step_status"] = TPA.STEP_CLEARED
1542    
1543    # Reset saved time
1544    GPA.pai_tracker.start_time = time.time()
1545    GPA.pai_tracker.saved_time = 0
1546
1547    # Match tracker initialization behavior so first validation uses epoch 0.
1548    GPA.pai_tracker.start_epoch(internal_call=True)
1549    
1550    if GPA.pc.get_verbose():
1551        print(
1552            f"Tracker reset complete. Dendrites: {GPA.pai_tracker.member_vars['num_dendrites_integrated']}, "
1553            f"Mode: {GPA.pai_tracker.member_vars['mode']}"
1554        )
1555    
1556    # Optionally remove dendrite scaffolding
1557    if remove_dendrite_scaffolding:
1558        if GPA.pc.get_verbose():
1559            print("Removing dendrite scaffolding (no dendrite additions)...")
1560        
1561        from perforatedai import blockwise_perforatedai as BPA
1562        from perforatedai import clean_perforatedai as CPA
1563        
1564        net = BPA.blockwise_network(net)
1565        net = CPA.refresh_net(net)
1566        
1567        if GPA.pc.get_verbose():
1568            print("Dendrite scaffolding removed. Model ready for inference or finetuning.")
1569    
1570    return net

Load a pretrained perforated model and reset tracker for fresh training.

This function loads a pretrained model's weights and dendrite structure while resetting all tracker state (epochs, switch history, etc.) to start training from scratch on a new task. This is useful for transfer learning where you want pretrained weights but need fresh training dynamics.

Parameters
  • net (nn.Module): The network to load into.
  • folder (str): The folder containing the pretrained model.
  • name (str): The name of the checkpoint to load (e.g., 'best_model', 'beforeSwitch_0').
  • remove_dendrite_scaffolding (bool, optional): If True, removes dendrite scaffolding for inference or finetuning without adding more dendrites using blockwise_network and refresh_net. Default False.
Returns
  • nn.Module: The loaded network with reset tracker state.
Examples

Load pretrained weights for continued dendrite training:

>>> model = load_pretrained_model(model, "pretrained-prefc", "beforeSwitch_0")

Load pretrained weights for finetuning without adding more dendrites:

>>> model = load_pretrained_model(model, "pretrained-prefc", "best_model", 
...                               remove_dendrite_scaffolding=True)
Notes

This function:

  • Loads model weights and dendrite structure from checkpoint
  • Resets all epoch counters to -1 (will become 0 after first start_epoch)
  • Resets switch history and validation score tracking
  • Clears accuracy/loss history arrays
  • Optionally removes dendrite scaffolding (no more dendrite additions)

The tracker is reset to behave as if starting fresh training, while keeping the learned weights and dendrite structure from the pretrained model.

def save_model_with_weight_tying(model, filepath):
1579def save_model_with_weight_tying(model, filepath):
1580    """Save model with safetensors while handling weight tying automatically
1581
1582    Parameters
1583    ----------
1584    model : Any PyTorch Module.
1585    filepath : Path to filename.
1586
1587    Returns
1588    -------
1589    dict[str, str]
1590        Mapping from secondary parameter keys to their primary tied key.
1591    """
1592    state_dict = model.state_dict()
1593
1594    # Find all weight tied parameters
1595    tensor_to_keys = defaultdict(list)
1596    for key, tensor in state_dict.items():
1597        # Use tensor data pointer as unique identifier
1598        tensor_id = tensor.data_ptr()
1599        tensor_to_keys[tensor_id].append(key)
1600
1601    # Find tied weights (tensors referenced by multiple keys)
1602    tied_weights = {}
1603    keys_to_remove = set()
1604    for tensor_id, keys in tensor_to_keys.items():
1605        if len(keys) > 1 and not tensor_id == 0:
1606            # Multiple keys reference the same tensor - this is weight tying
1607            # Sort keys for deterministic ordering
1608            keys = sorted(keys)
1609            primary_key = keys[0]  # Keep the first key
1610            for secondary_key in keys[1:]:
1611                tied_weights[secondary_key] = primary_key
1612                keys_to_remove.add(secondary_key)
1613
1614    # Remove tied weights from state_dict (keep only primary references)
1615    filtered_state_dict = {
1616        k: v for k, v in state_dict.items() if k not in keys_to_remove
1617    }
1618
1619    # Create metadata for weight tying information
1620    metadata = {}
1621    if tied_weights:
1622        # Store weight tying info as JSON string in metadata
1623        metadata["weight_tying"] = json.dumps(tied_weights)
1624    save_file(filtered_state_dict, filepath, metadata=metadata)
1625    print(f"Saved model with {len(tied_weights)} weight tying relationships")
1626    return tied_weights

Save model with safetensors while handling weight tying automatically

Parameters
  • model (Any PyTorch Module.):

  • filepath (Path to filename.):

Returns
  • dict[str, str]: Mapping from secondary parameter keys to their primary tied key.
def load_model_with_weight_tying(model, filepath):
1629def load_model_with_weight_tying(model, filepath):
1630    """Load model from safetensors while restoring weight tying
1631
1632    Parameters
1633    ----------
1634    model : Any PyTorch module.
1635    filepath : Path to model file.
1636
1637    Returns
1638    -------
1639    Loaded model.
1640    """
1641    with safe_open(filepath, framework="pt") as f:
1642        metadata = f.metadata()
1643        state_dict = {key: f.get_tensor(key) for key in f.keys()}
1644
1645    # Restore weight tying if metadata exists
1646    tied_weights = {}
1647    if metadata and "weight_tying" in metadata:
1648        tied_weights = json.loads(metadata["weight_tying"])
1649        for secondary_key, primary_key in tied_weights.items():
1650            if primary_key in state_dict:
1651                # Restore the tied reference
1652                state_dict[secondary_key] = state_dict[primary_key]
1653                print(f"Restored weight tying: {secondary_key} -> {primary_key}")
1654
1655    # Handle tracker_string loading with flexible key matching
1656    tracker_key = None
1657    if "tracker_string" in state_dict:
1658        tracker_key = "tracker_string"
1659    else:
1660        # Search for keys containing "tracker_string"
1661        tracker_keys = [key for key in state_dict.keys() if "tracker_string" in key]
1662        if len(tracker_keys) == 1:
1663            tracker_key = tracker_keys[0]
1664        elif len(tracker_keys) > 1:
1665            print(f"Error: Multiple tracker_string keys found: {tracker_keys}")
1666            pdb.set_trace()
1667        else:
1668            print("Error: No tracker_string found in state_dict")
1669
1670    if tracker_key is not None and hasattr(model, "tracker_string"):
1671        model.tracker_string = state_dict[tracker_key]
1672
1673    model.load_state_dict(state_dict)
1674    return model

Load model from safetensors while restoring weight tying

Parameters
  • model (Any PyTorch module.):

  • filepath (Path to model file.):

Returns
  • Loaded model.
def save_net(net, folder, name):
1706def save_net(net, folder, name):
1707    """Save the network
1708
1709    This is called within save_system after the tracker has been
1710    turned into a single tensor to be saved as a part of the network
1711
1712    Parameters
1713    ----------
1714    net : nn.Module
1715        The network to save.
1716    folder : str
1717        The folder to save the network in.
1718    name : str
1719        The name to save the network under.
1720
1721    Returns
1722    -------
1723    None
1724
1725    """
1726    # If running a DDP only save with first thread
1727    if "RANK" in os.environ:
1728        if int(os.environ["RANK"]) != 0:
1729            return
1730    if not os.path.isdir(folder):
1731        os.makedirs(folder)
1732    save_point = folder + "/"
1733    if not os.path.isdir(save_point):
1734        os.mkdir(save_point)
1735    for param in net.parameters():
1736        param.data = param.data.contiguous()
1737    if GPA.pc.get_using_safe_tensors():
1738        # Strip the . so that the naming is the same for everywhere but it works with state_dict naming
1739        not_save = [ns.lstrip('.') for ns in GPA.pc.get_module_names_to_not_save()]
1740        state_dict = {k: v for k, v in net.state_dict().items()
1741                      if not any(k.startswith(ns) for ns in not_save)}
1742        _save_file_deduped(state_dict, save_point + name + ".pt")
1743    else:
1744        torch.save(net, save_point + name + ".pt")

Save the network

This is called within save_system after the tracker has been turned into a single tensor to be saved as a part of the network

Parameters
  • net (nn.Module): The network to save.
  • folder (str): The folder to save the network in.
  • name (str): The name to save the network under.
Returns
  • None
def save_pai_net(net, folder, name):
1788def save_pai_net(net, folder, name):
1789    """Save the final pai network
1790
1791    This can be called after training to save the final network
1792    with all scaffolding removed so only the refined weights remain
1793
1794    Parameters
1795    ----------
1796    net : nn.Module
1797        The network to save.
1798    folder : str
1799        The folder to save the network in.
1800    name : str
1801        The name to save the network under.
1802
1803    Returns
1804    -------
1805    None
1806
1807    """
1808    # if running a DDP only save with first thread
1809    if "RANK" in os.environ:
1810        if int(os.environ["RANK"]) != 0:
1811            return
1812
1813    # print('calling save: %s' % name)
1814    # GPA.pai_tracker.archive_layer()
1815    # These deep copys are required or the real model will also have its layers replaced
1816    net = prepare_final_model(net)
1817    if not os.path.isdir(folder):
1818        os.makedirs(folder)
1819    save_point = folder + "/"
1820    if not os.path.isdir(save_point):
1821        os.mkdir(save_point)
1822
1823    if GPA.pc.get_using_safe_tensors():
1824        _save_file_deduped(net.state_dict(), save_point + name + "_pai.pt")
1825    else:
1826        torch.save(net, save_point + name + "_pai.pt")

Save the final pai network

This can be called after training to save the final network with all scaffolding removed so only the refined weights remain

Parameters
  • net (nn.Module): The network to save.
  • folder (str): The folder to save the network in.
  • name (str): The name to save the network under.
Returns
  • None
def manual_load_state_dict(model, state_dict):
1829def manual_load_state_dict(model, state_dict):
1830    """Load a state dict into a model key-by-key with relaxed checks.
1831
1832    Parameters
1833    ----------
1834    model : nn.Module
1835        Model receiving parameters.
1836    state_dict : dict
1837        Source parameter dictionary.
1838
1839    Notes
1840    -----
1841    Keys configured in ``module_names_to_not_save`` are skipped.
1842
1843    Returns
1844    -------
1845    None
1846        This function does not return a value.
1847    """
1848    own_state = model.state_dict()
1849    not_save = [ns.lstrip('.') for ns in GPA.pc.get_module_names_to_not_save()]
1850    for name, param in state_dict.items():
1851        if any(name.startswith(ns) for ns in not_save):
1852            print("skipping loading %s based on module_names_to_not_save" % name)
1853            continue
1854        if name not in own_state:
1855            print(f"Warning: {name} not found in model state_dict")
1856            continue
1857        if isinstance(param, torch.nn.Parameter):
1858            # Backwards compatibility for serialized parameters
1859            param = param.data
1860        try:
1861            own_state[name].copy_(param)
1862        except Exception as e:
1863            print(f"Error loading {name}: {e}")
1864    print("Manual load complete")

Load a state dict into a model key-by-key with relaxed checks.

Parameters
  • model (nn.Module): Model receiving parameters.
  • state_dict (dict): Source parameter dictionary.
Notes

Keys configured in module_names_to_not_save are skipped.

Returns
  • None: This function does not return a value.
def load_net(net, folder, name):
1867def load_net(net, folder, name):
1868    """load the network
1869
1870    This is called within load_system after the tracker has been
1871    loaded
1872
1873    Parameters
1874    ----------
1875    net : nn.Module
1876        The network to save.
1877    folder : str
1878        The folder to save the network in.
1879    name : str
1880        The name to save the network under.
1881
1882    Returns
1883    -------
1884    nn.Module
1885        The loaded network.
1886
1887    """
1888    save_point = folder + "/"
1889    if GPA.pc.get_using_safe_tensors():
1890        model_path = save_point + name + ".pt"
1891        state_dict = load_file(model_path)
1892        try:
1893            with safe_open(model_path, framework="pt") as f:
1894                metadata = f.metadata()
1895            if metadata and "weight_tying" in metadata:
1896                tied_weights = json.loads(metadata["weight_tying"])
1897                for secondary_key, primary_key in tied_weights.items():
1898                    if primary_key in state_dict:
1899                        state_dict[secondary_key] = state_dict[primary_key]
1900        except Exception:
1901            pass
1902    else:
1903        # Try three different torch.load call signatures for compatibility across
1904        # different PyTorch versions.  All three are attempted before giving up so
1905        # the user can see every error at once and decide how to fix the file.
1906        error_weights_only_false = None
1907        error_no_weights_only    = None
1908        error_no_state_dict      = None
1909
1910        try:
1911            state_dict = torch.load(
1912                save_point + name + ".pt",
1913                map_location=torch.device("cpu"),
1914                weights_only=False,
1915            ).state_dict()
1916        except Exception as caught_error:
1917            error_weights_only_false = caught_error
1918
1919        if error_weights_only_false is not None:
1920            try:
1921                state_dict = torch.load(
1922                    save_point + name + ".pt",
1923                    map_location=torch.device("cpu"),
1924                ).state_dict()
1925            except Exception as caught_error:
1926                error_no_weights_only = caught_error
1927
1928        if error_no_weights_only is not None:
1929            try:
1930                state_dict = torch.load(
1931                    save_point + name + ".pt",
1932                    map_location=torch.device("cpu"),
1933                )
1934            except Exception as caught_error:
1935                error_no_state_dict = caught_error
1936
1937        if error_no_state_dict is not None:
1938            separator = "\n" + "=" * 60 + "\n"
1939            print(separator.join([
1940                "\nAll four load attempts failed for: " + save_point + name + ".pt",
1941                "Attempt 1 (weights_only=False, .state_dict()):\n"      + str(error_weights_only_false),
1942                "Attempt 2 (default weights_only, .state_dict()):\n"    + str(error_no_weights_only),
1943                "Attempt 3 (default weights_only, no .state_dict()):\n" + str(error_no_state_dict),
1944                "You must find a way to fix at least one of the above errors to load successfully.\n",
1945                "Suggested problems to look into:\n",
1946                "1 - Modules which have member variables that are methods, which cant be pickled.  See __setstate__ and __getstate__ functions to append."
1947            ]))
1948            raise error_no_state_dict
1949    return load_net_from_dict(net, state_dict)

load the network

This is called within load_system after the tracker has been loaded

Parameters
  • net (nn.Module): The network to save.
  • folder (str): The folder to save the network in.
  • name (str): The name to save the network under.
Returns
  • nn.Module: The loaded network.
def get_module_base_name(module):
1951def get_module_base_name(module):
1952    """Normalize a wrapped module name for state-dict key lookup.
1953
1954    Parameters
1955    ----------
1956    module : nn.Module
1957        Module containing a ``name`` attribute.
1958
1959    Returns
1960    -------
1961    str
1962        Base name with leading dot and optional ``module.`` prefix removed.
1963    """
1964    module_name = module.name
1965    # This should always be true
1966    if module_name[0] == ".":
1967        # strip "."
1968        module_name = module_name[1:]
1969    # If it was a dataparallel it will also have a module at the start
1970    # so strip that for loading
1971    if module_name[:6] == "module":
1972        module_name = module_name[7:]
1973    return module_name

Normalize a wrapped module name for state-dict key lookup.

Parameters
  • module (nn.Module): Module containing a name attribute.
Returns
  • str: Base name with leading dot and optional module. prefix removed.
def load_net_from_dict(net, state_dict):
1976def load_net_from_dict(net, state_dict):
1977    """load the network
1978
1979    This is called within load_net
1980
1981    Parameters
1982    ----------
1983    net : nn.Module
1984        The network to save.
1985    state_dict : dict
1986        The state dictionary to load.
1987
1988    Returns
1989    -------
1990    nn.Module
1991        The loaded network.
1992
1993    """
1994    if GPA.pc.get_verbose():
1995        print("loading net from dict")
1996    pai_modules = get_pai_modules(net, 0)
1997    if pai_modules == []:
1998        print(
1999            "PAI load_net and load_system uses a state_dict so it must be\n"
2000            "called with a net after perforate_model has been called"
2001        )
2002        print(
2003            "This is being flagged because you are attempting to load a model\n"
2004            "that does not have any pai_modules in it.  Confirm that you are calling\n"
2005            "perforate_model on the correct model, and the same model is the one\n"
2006            "being passed into add_validation_score"
2007        )
2008        import pdb # This needs to be here for cython for some reason.
2009        pdb.set_trace()
2010        sys.exit(-1)
2011    if GPA.pc.get_verbose():
2012        print(
2013            "setting up arrays and simulating cycles for %d pai modules"
2014            % len(pai_modules)
2015        )
2016    not_save = GPA.pc.get_module_names_to_not_save()
2017    for module in pai_modules:
2018        if any(module.name.startswith(ns) for ns in not_save):
2019            print("skipping loading %s based on module_names_to_not_save" % module.name)
2020            continue
2021        # Set up name to be what will be saved in the state dict
2022        module_name = get_module_base_name(module)
2023        module.clear_dendrites()
2024        for tracker in module.dendrite_module.dendrite_values:
2025            try:
2026                tracker.setup_arrays(
2027                    state_dict[
2028                        module_name + ".dendrite_module.dendrite_values.0.dendrite_storage_shape"
2029                    ].tolist()
2030                )
2031            except Exception as e:
2032                print(e)
2033                first_key = next(iter(state_dict.keys()))
2034                error_msg = f"""
2035This value is missing from the state dict.
2036When missing this value it typically means you converted a module but didn't
2037actually use it in your forward and backward pass.
2038
2039Module was: {module.name}
2040
2041There are many reasons this can happen:
2042
20431 - Check your model definition and forward function and ensure this module is 
2044    being used properly.
2045    
2046    With GPA.pc.set_verbose(True) you can confirm this is the case if you do not 
2047    see a "setting d shape for" this module at the first training batch.
2048    
2049    If this is the case, and it is correct to not be passing data through it,
2050    set it to be a tracked module with:
2051    GPA.pc.append_module_ids_to_track(["{module.name}"]) to leave it out
2052
20532 - This can happen if you adjusted your model definition after calling 
2054    perforate_model (for example with torch.compile). If the module name printed 
2055    above does not contain all modules leading to the main definition, this is 
2056    likely the case for your problem. Fix by calling perforate_model after all 
2057    other model initialization steps.
2058
20593 - This can happen if the model where you called perforate_model and the model 
2060    within add_validation_score are not the same. Check if the module above and 
2061    .{first_key} have the same prefix. If one starts with .model or .base etc 
2062    and the other does not, this is the problem.
2063
20644 - If you are using this module but then not actually including the correct 
2065    output tensor in the forward. For example if you are using an LSTM and 
2066    forwarding hidden instead of output but your processors are set up to work 
2067    with output.
2068
20695 - If you are not properly calling backward at all. If this is the first module 
2070    in your network it is more likely this is the problem. One check in these 
2071    cases is to make sure you do not call an initial validation score before the 
2072    first backward call. If you do this, while testing_dendrite_capacity is True, 
2073    this error will be triggered.
2074
20756 - You have converted a module that is in a frozen part of the network and thus 
2076    no gradients are flowing.
2077
20787 - You are running multiple experiments at once with the same save_name. When 
2079    running concurrent trials be sure to add save_name=<unique_name> to 
2080    perforate_model.
2081"""
2082                print(error_msg)
2083                import pdb # This needs to be here for cython for some reason.
2084                pdb.set_trace()
2085
2086        # Perform as many cycles as the state dict has
2087        num_cycles = int(state_dict[module_name + ".dendrite_module.num_cycles"].item())
2088        if num_cycles > 0:
2089            simulate_cycles(module, num_cycles, doing_pai=True)
2090    # Handle tracker_string loading with flexible key matching
2091    tracker_key = None
2092    if "tracker_string" in state_dict:
2093        tracker_key = "tracker_string"
2094    else:
2095        # Search for keys containing "tracker_string"
2096        tracker_keys = [key for key in state_dict.keys() if "tracker_string" in key]
2097        if len(tracker_keys) == 1:
2098            tracker_key = tracker_keys[0]
2099        elif len(tracker_keys) > 1:
2100            print(f"Error: Multiple tracker_string keys found: {tracker_keys}")
2101            import pdb # This needs to be here for cython for some reason.
2102            pdb.set_trace()
2103        else:
2104            print("Error: No tracker_string found in state_dict")
2105            import pdb # This needs to be here for cython for some reason.
2106            pdb.set_trace()
2107
2108    if hasattr(net, "tracker_string"):
2109        net.tracker_string = state_dict[tracker_key]
2110    else:
2111        net.register_buffer("tracker_string", state_dict[tracker_key])
2112    try:
2113        load_result = net.load_state_dict(state_dict, strict=False)
2114        not_save_state_names = [ns.lstrip('.') for ns in not_save]
2115
2116        def is_ignored_key(key):
2117            """Check whether a state-dict key should be ignored.
2118
2119            Parameters
2120            ----------
2121            key : str
2122                State-dict key to test.
2123
2124            Returns
2125            -------
2126            bool
2127                ``True`` when key belongs to a not-saved namespace.
2128            """
2129            return any(key.startswith(ns) for ns in not_save_state_names)
2130
2131        missing_keys = [key for key in load_result.missing_keys if not is_ignored_key(key)]
2132        unexpected_keys = [key for key in load_result.unexpected_keys if not is_ignored_key(key)]
2133
2134        if GPA.pc.get_strict_loading() and (missing_keys or unexpected_keys):
2135            raise RuntimeError(
2136                "Error(s) in loading state_dict for %s:\n\tMissing key(s) in state_dict: %s. \n\tUnexpected key(s) in state_dict: %s."
2137                % (type(net).__name__, missing_keys, unexpected_keys)
2138            )
2139    except Exception as e:
2140        """
2141        When modules have high depth to them (i.e. modules within modules not number of layers)
2142        PyTorch can have trouble loading state dicts even when they are correct.
2143        This is a workaround to manually load the state dict if this happens.
2144        """
2145        filtered_net_keys = {
2146            key
2147            for key in net.state_dict().keys()
2148            if not any(key.startswith(ns.lstrip('.')) for ns in not_save)
2149        }
2150        if filtered_net_keys == set(state_dict.keys()):
2151            print("Attempting manual loading of state_dict")
2152            manual_load_state_dict(net, state_dict)
2153        else:
2154            print(f"Error loading state_dict: {e}")
2155            print("If the error is due to missing keys (e.g., from code changes), you can try:")
2156            print("  GPA.pc.set_strict_loading(False)")
2157            print("  Do not change this unless you are certain the missing keys are not important to load and are expected due to code changes or arch changes.")
2158            print("\ntype 'c' to print full state dicts\n")
2159            import pdb # This needs to be here for cython for some reason.
2160            pdb.set_trace()
2161            print("net state dict is:")
2162            print(net.state_dict())
2163            print("loaded state dict is:")
2164            print(state_dict)
2165            print(
2166                "Try to check differences.  Likely is caused by a module not "
2167                "being converted that should be or vice versa"
2168            )
2169            pdb.set_trace()
2170    net.to(GPA.pc.get_device())
2171    return net

load the network

This is called within load_net

Parameters
  • net (nn.Module): The network to save.
  • state_dict (dict): The state dictionary to load.
Returns
  • nn.Module: The loaded network.
def pai_save_system(net, folder, name):
2174def pai_save_system(net, folder, name):
2175    """Save the entire system with scaffolding removed
2176
2177    This is used for the final network for inference after training
2178
2179    Parameters
2180    ----------
2181    net : nn.Module
2182        The network to save.
2183    folder : str
2184        The folder to save the network in.
2185    name : str
2186        The name to save the network under.
2187
2188    Returns
2189    -------
2190    None
2191
2192    """
2193    net.member_vars = {}
2194    for member_var in GPA.pai_tracker.member_vars:
2195        if member_var == "scheduler_instance" or member_var == "optimizer_instance":
2196            continue
2197        net.member_vars[member_var] = GPA.pai_tracker.member_vars[member_var]
2198    pai_save_net(net, folder, name)

Save the entire system with scaffolding removed

This is used for the final network for inference after training

Parameters
  • net (nn.Module): The network to save.
  • folder (str): The folder to save the network in.
  • name (str): The name to save the network under.
Returns
  • None
def deep_copy_pai(net):
2201def deep_copy_pai(net):
2202    """Deep copy a PAI network
2203
2204
2205    Parameters
2206    ----------
2207    net : nn.Module
2208        The network to copy.
2209
2210    Returns
2211    -------
2212    nn.Module
2213        The copied network.
2214
2215    Notes
2216    ----
2217    This is required because processors must be cleared before calling copy
2218
2219    """
2220    # Dont check this stuff if its before the perforate_model has been called and you're just copying a regular model
2221    if(GPA.pai_tracker != []):
2222        # Clear gradients before saving the model
2223        if ((GPA.pai_tracker.member_vars["optimizer_instance"]) is not None) and (
2224            GPA.pai_tracker.member_vars["optimizer_instance"] != []
2225        ):
2226            GPA.pai_tracker.member_vars["optimizer_instance"].zero_grad()
2227        GPA.pai_tracker.clear_all_processors()
2228    return copy.deepcopy(net)

Deep copy a PAI network

Parameters
  • net (nn.Module): The network to copy.
Returns
  • nn.Module: The copied network.
Notes

This is required because processors must be cleared before calling copy

def prepare_final_model(net):
2231def prepare_final_model(net):
2232    """Prepare model for final save by removing scaffolding.
2233
2234    This performs all cleanup steps to convert a PAI model with scaffolding
2235    into a clean final model ready for inference or distribution.
2236
2237    Parameters
2238    ----------
2239    net : nn.Module
2240        The network to prepare.
2241
2242    Returns
2243    -------
2244    nn.Module
2245        The cleaned model with scaffolding removed.
2246    """
2247    # Deep copy and clean the model (removes scaffolding)
2248    net = deep_copy_pai(net)
2249    net = BPA.blockwise_network(net)
2250    net = deep_copy_pai(net)
2251    net = CL.refresh_net(net)
2252
2253    # Remove tracker_string (not needed for final model)
2254    if hasattr(net, "tracker_string"):
2255        del net.tracker_string
2256
2257    # Make parameters contiguous
2258    for param in net.parameters():
2259        param.data = param.data.contiguous()
2260
2261    return net

Prepare model for final save by removing scaffolding.

This performs all cleanup steps to convert a PAI model with scaffolding into a clean final model ready for inference or distribution.

Parameters
  • net (nn.Module): The network to prepare.
Returns
  • nn.Module: The cleaned model with scaffolding removed.
def pai_save_net(net, folder, name):
2264def pai_save_net(net, folder, name):
2265    """Save the entire system with scaffolding removed
2266
2267    This is called within pai_save_system after the tracker has been
2268    turned into a single tensor to be saved as a part of the network
2269
2270
2271    Parameters
2272    ----------
2273    net : nn.Module
2274        The network to save.
2275    folder : str
2276        The folder to save the network in.
2277    name : str
2278        The name to save the network under.
2279
2280    Returns
2281    -------
2282    None
2283
2284    Notes
2285    ----
2286    For open source implementation this is not as important since
2287    minimal values are already being used.
2288
2289    """
2290
2291    if GPA.pc.get_perforated_backpropagation():
2292        UPB.pb_save_net(net, folder, name)
2293    else:
2294        return

Save the entire system with scaffolding removed

This is called within pai_save_system after the tracker has been turned into a single tensor to be saved as a part of the network

Parameters
  • net (nn.Module): The network to save.
  • folder (str): The folder to save the network in.
  • name (str): The name to save the network under.
Returns
  • None
Notes

For open source implementation this is not as important since minimal values are already being used.

def simulate_cycles(module, num_cycles, doing_pai):
2297def simulate_cycles(module, num_cycles, doing_pai):
2298    """Simulate dendrite addition cycles
2299
2300    Simulate the back and forth processes of adding dendrites to build a
2301    pretrained dendrite model before loading weights.  Required for loading
2302    dendrite save files from non dendrite initial models.
2303
2304    If calling this by hand to start off a network with dendrites added,
2305    make sure to pass a single datapoint forward and backward through the network
2306    so that array sizes are initialized.
2307
2308    Parameters
2309    ----------
2310    module : PA.PAINeuronModule
2311        The module to simulate cycles on.
2312    num_cycles : int
2313        The number of cycles to simulate.
2314    doing_pai : bool
2315        Whether to actually do the simulation.
2316
2317    Returns
2318    -------
2319    None
2320
2321    """
2322
2323    check_skipped = GPA.pc.get_checked_skipped_modules()
2324    if doing_pai is False:
2325        return
2326    GPA.pc.set_checked_skipped_modules(True)
2327    mode = "n"
2328    for i in range(num_cycles):
2329        if mode == "n":
2330            module.set_mode("p")
2331            module.create_new_dendrite_module()
2332            mode = "p"
2333        else:
2334            module.set_mode("n")
2335            mode = "n"
2336    GPA.pc.set_checked_skipped_modules(check_skipped)

Simulate dendrite addition cycles

Simulate the back and forth processes of adding dendrites to build a pretrained dendrite model before loading weights. Required for loading dendrite save files from non dendrite initial models.

If calling this by hand to start off a network with dendrites added, make sure to pass a single datapoint forward and backward through the network so that array sizes are initialized.

Parameters
  • module (PA.PAINeuronModule): The module to simulate cycles on.
  • num_cycles (int): The number of cycles to simulate.
  • doing_pai (bool): Whether to actually do the simulation.
Returns
  • None
def count_params(net):
2339def count_params(net):
2340    """Count the number of parameters in the network
2341
2342    If doing perforated backpropagation this calls the PB function
2343    which does not count scaffolding parameters since the final model
2344    will not have them.
2345
2346    Parameters
2347    ----------
2348    net : nn.Module
2349        The network to count parameters in.
2350
2351    Returns
2352    -------
2353    int
2354        The number of parameters in the network.
2355
2356    """
2357    if GPA.pc.get_perforated_backpropagation():
2358        return UPB.pb_count_params(net)
2359    parameters = net.named_parameters()
2360    unique_params = {
2361        p.data_ptr(): p for name, p in parameters if "parent_module" not in name
2362    }.values()
2363    return sum(p.numel() for p in unique_params)

Count the number of parameters in the network

If doing perforated backpropagation this calls the PB function which does not count scaffolding parameters since the final model will not have them.

Parameters
  • net (nn.Module): The network to count parameters in.
Returns
  • int: The number of parameters in the network.
def change_learning_modes(net, folder, name, doing_pai):
2366def change_learning_modes(net, folder, name, doing_pai):
2367    """Change between neuron and dendrite learning modes
2368
2369    High level steps for entire system to switch back and forth between
2370    neuron learning and dendrite learning
2371
2372    Parameters
2373    ----------
2374    net : nn.Module
2375        The network to change modes on.
2376    folder : str
2377        The folder to save/load the network in/from.
2378    name : str
2379        The name to save/load the network under.
2380    doing_pai : bool
2381        Whether to add dendrites when changing modes.
2382
2383    Returns
2384    -------
2385    int
2386        The number of parameters in the network.
2387
2388    Notes
2389    -----
2390    If doing_pai is False this just allows training to continue longer rather than early stopping
2391
2392    """
2393    # If not adding dendrites this just allows training to continue longer with flags
2394    # every time early stopping should be occurring
2395    if doing_pai is False:
2396        if GPA.pc.get_verbose():
2397            print(
2398                f'Not doing PAI, cycle {GPA.pai_tracker.member_vars["num_dendrites_added"] + 1} '
2399                f'of {GPA.pc.get_max_dendrites()}, resetting LR and continuing.'
2400            )
2401        GPA.pai_tracker.member_vars["num_dendrites_added"] += 1
2402        # Record the switch to p and straight back to n, like the open source n-p-n switch
2403        GPA.pai_tracker.member_vars["switch_epochs"].append(
2404            GPA.pai_tracker.member_vars["num_epochs_run"]
2405        )
2406        GPA.pai_tracker.member_vars["switch_epochs"].append(
2407            GPA.pai_tracker.member_vars["num_epochs_run"]
2408        )
2409        GPA.pai_tracker.member_vars["last_switch"] = GPA.pai_tracker.member_vars[
2410            "switch_epochs"
2411        ][-1]
2412        GPA.pai_tracker.reset_vals_for_score_reset()
2413        # Start a new LR search like set_dendrite_training and set_neuron_training do
2414        GPA.pai_tracker.member_vars["current_n_learning_rate_initial_skip_steps"] = 0
2415        GPA.pai_tracker.member_vars["last_max_learning_rate_steps"] = GPA.pai_tracker.member_vars[
2416            "current_step_count"
2417        ]
2418        if GPA.pc.get_find_best_lr():
2419            TPA._lr_search_initialize()
2420        return net
2421    if GPA.pai_tracker.member_vars["mode"] == "n":
2422        current_epoch = GPA.pai_tracker.member_vars["num_epochs_run"]
2423        overwritten_epochs = GPA.pai_tracker.member_vars["overwritten_epochs"]
2424        overwritten_extra = GPA.pai_tracker.member_vars["extra_scores"]
2425        if GPA.pc.get_drawing_pai():
2426            overwritten_val = GPA.pai_tracker.member_vars["accuracies"]
2427        else:
2428            overwritten_val = GPA.pai_tracker.member_vars["neuron_accuracies"]
2429        """
2430        If true don't load the best system
2431        because it will delete dendrites if the previous best was better than
2432        the current best
2433        """
2434        if not GPA.pc.get_silent():
2435            print("Importing best Model for switch to PA...")
2436        net = load_system(net, folder, name, switch_call=True)
2437        GPA.pai_tracker.set_dendrite_training()
2438        GPA.pai_tracker.member_vars["overwritten_epochs"] = overwritten_epochs
2439        GPA.pai_tracker.member_vars["overwritten_epochs"] += (
2440            current_epoch - GPA.pai_tracker.member_vars["num_epochs_run"]
2441        )
2442        GPA.pai_tracker.member_vars["total_epochs_run"] = (
2443            GPA.pai_tracker.member_vars["num_epochs_run"]
2444            + GPA.pai_tracker.member_vars["overwritten_epochs"]
2445        )
2446
2447        if GPA.pc.get_save_old_graph_scores():
2448            GPA.pai_tracker.member_vars["overwritten_extras"].append(overwritten_extra)
2449            GPA.pai_tracker.member_vars["overwritten_vals"].append(overwritten_val)
2450        else:
2451            GPA.pai_tracker.member_vars["overwritten_extras"] = [overwritten_extra]
2452            GPA.pai_tracker.member_vars["overwritten_vals"] = [overwritten_val]
2453        if GPA.pc.get_drawing_pai():
2454            GPA.pai_tracker.member_vars["n_switch_epochs"].append(
2455                GPA.pai_tracker.member_vars["num_epochs_run"]
2456            )
2457        else:
2458            if len(GPA.pai_tracker.member_vars["switch_epochs"]) == 0:
2459                GPA.pai_tracker.member_vars["n_switch_epochs"].append(
2460                    GPA.pai_tracker.member_vars["num_epochs_run"]
2461                )
2462            else:
2463                GPA.pai_tracker.member_vars["n_switch_epochs"].append(
2464                    GPA.pai_tracker.member_vars["n_switch_epochs"][-1]
2465                    + (
2466                        (GPA.pai_tracker.member_vars["num_epochs_run"])
2467                        - (GPA.pai_tracker.member_vars["switch_epochs"][-1])
2468                    )
2469                )
2470
2471        GPA.pai_tracker.member_vars["switch_epochs"].append(
2472            GPA.pai_tracker.member_vars["num_epochs_run"]
2473        )
2474        GPA.pai_tracker.member_vars["last_switch"] = GPA.pai_tracker.member_vars[
2475            "switch_epochs"
2476        ][-1]
2477
2478        # Because open source version is only doing neuron training for
2479        # gradient descent dendrites, switch back to n mode right away
2480        if (
2481            not GPA.pc.get_perforated_backpropagation()
2482        ) or GPA.pc.get_no_extra_n_modes():
2483            net = change_learning_modes(net, folder, name, doing_pai)
2484    else:
2485        if not GPA.pc.get_silent():
2486            print("Switching back to N...")
2487        set_best = GPA.pai_tracker.member_vars["current_n_set_global_best"]
2488        GPA.pai_tracker.set_neuron_training()
2489        if len(GPA.pai_tracker.member_vars["p_switch_epochs"]) == 0:
2490            GPA.pai_tracker.member_vars["p_switch_epochs"].append(
2491                (
2492                    (GPA.pai_tracker.member_vars["num_epochs_run"] - 1)
2493                    - (GPA.pai_tracker.member_vars["switch_epochs"][-1])
2494                )
2495            )
2496        else:
2497            GPA.pai_tracker.member_vars["p_switch_epochs"].append(
2498                GPA.pai_tracker.member_vars["p_switch_epochs"][-1]
2499                + (
2500                    (GPA.pai_tracker.member_vars["num_epochs_run"])
2501                    - (GPA.pai_tracker.member_vars["switch_epochs"][-1])
2502                )
2503            )
2504        GPA.pai_tracker.member_vars["switch_epochs"].append(
2505            GPA.pai_tracker.member_vars["num_epochs_run"]
2506        )
2507        GPA.pai_tracker.member_vars["last_switch"] = GPA.pai_tracker.member_vars[
2508            "switch_epochs"
2509        ][-1]
2510        # Will be false for open source implementation
2511        if GPA.pc.get_retain_all_dendrites() or (
2512            GPA.pc.get_learn_dendrites_live() and set_best
2513        ):
2514            if not GPA.pc.get_silent():
2515                print(
2516                    "Saving model before starting normal training to "
2517                    "retain PBNodes regardless of next N Phase results"
2518                )
2519            save_system(net, folder, name)
2520        # if its just doing P for learn PAI live then switch back immediately
2521        if GPA.pc.get_perforated_backpropagation() and GPA.pc.get_no_extra_n_modes():
2522            net = change_learning_modes(net, folder, name, doing_pai)
2523
2524    GPA.pai_tracker.member_vars["param_counts"].append(count_params(net))
2525
2526    return net

Change between neuron and dendrite learning modes

High level steps for entire system to switch back and forth between neuron learning and dendrite learning

Parameters
  • net (nn.Module): The network to change modes on.
  • folder (str): The folder to save/load the network in/from.
  • name (str): The name to save/load the network under.
  • doing_pai (bool): Whether to add dendrites when changing modes.
Returns
  • int: The number of parameters in the network.
Notes

If doing_pai is False this just allows training to continue longer rather than early stopping

def find_param_name_by_id(model, param_id):
2529def find_param_name_by_id(model, param_id):
2530    """
2531    This is only used for debugging.
2532    Return the fully-qualified parameter name (e.g. "layer1.conv.weight")
2533    for the parameter whose id matches param_id. Returns None if not found.
2534
2535    This uses model.named_parameters(), which already recurses through submodules.
2536
2537    Parameters
2538    ----------
2539    model : Model to look for param id.
2540    param_id : pointer to a parameter.
2541
2542    Returns
2543    -------
2544    String representing the module within the model or None if not found.
2545    """
2546    for name, p in model.named_parameters(recurse=True):
2547        if id(p) == param_id:
2548            return "." + name
2549    return None

This is only used for debugging. Return the fully-qualified parameter name (e.g. "layer1.conv.weight") for the parameter whose id matches param_id. Returns None if not found.

This uses model.named_parameters(), which already recurses through submodules.

Parameters
  • model (Model to look for param id.):

  • param_id (pointer to a parameter.):

Returns
  • String representing the module within the model or None if not found.
def add_method_delegation_to_module(wrapper_module, method_name):
2552def add_method_delegation_to_module(wrapper_module, method_name):
2553    """Add delegating methods to a wrapper module that has a main_module attribute.
2554
2555    This adds the specified methods to the wrapper module instance so they
2556    properly delegate to the wrapped main_module. Works for any wrapper module
2557    (TrackedNeuronModule, PAINeuronModule, etc.) that has a main_module attribute.
2558
2559    Args:
2560        wrapper_module: A wrapper module instance with a main_module attribute
2561        method_name: The method name to delegate (e.g., '_gradient_checkpointing_func')
2562
2563    Parameters
2564    ----------
2565    wrapper_module : PyTorch Module that contains a sub module.
2566    method_name : Name of method to wrap.
2567
2568    Returns
2569    -------
2570    None
2571    """
2572    import types
2573
2574    if hasattr(wrapper_module.main_module, method_name):
2575        # Create a delegating method that forwards to main_module
2576        def make_delegated_method(name):
2577            """Create a bound delegation function for a given attribute name.
2578
2579            Parameters
2580            ----------
2581            name : str
2582                Attribute name to forward to ``main_module``.
2583
2584            Returns
2585            -------
2586            callable
2587                Function that delegates access or invocation.
2588            """
2589            def delegated_method(self, *args, **kwargs):
2590                """Delegate attribute access or method call to ``main_module``.
2591
2592                Parameters
2593                ----------
2594                *args : tuple
2595                    Positional arguments forwarded to delegated callables.
2596                **kwargs : dict
2597                    Keyword arguments forwarded to delegated callables.
2598
2599                Returns
2600                -------
2601                Any
2602                    Delegated attribute value or method result.
2603                """
2604                main_module_attr = getattr(self.main_module, name, None)
2605                if main_module_attr is None:
2606                    raise AttributeError(
2607                        f"'{type(self.main_module).__name__}' object has no attribute '{name}'"
2608                    )
2609                if callable(main_module_attr):
2610                    return main_module_attr(*args, **kwargs)
2611                return main_module_attr
2612
2613            return delegated_method
2614
2615        # Bind it to this specific instance
2616        setattr(
2617            wrapper_module,
2618            method_name,
2619            types.MethodType(make_delegated_method(method_name), wrapper_module),
2620        )

Add delegating methods to a wrapper module that has a main_module attribute.

This adds the specified methods to the wrapper module instance so they properly delegate to the wrapped main_module. Works for any wrapper module (TrackedNeuronModule, PAINeuronModule, etc.) that has a main_module attribute.

Args: wrapper_module: A wrapper module instance with a main_module attribute method_name: The method name to delegate (e.g., '_gradient_checkpointing_func')

Parameters
  • wrapper_module (PyTorch Module that contains a sub module.):

  • method_name (Name of method to wrap.):

Returns
  • None
def apply_method_delegation_to_model(model, method_name, main_module_type):
2623def apply_method_delegation_to_model(model, method_name, main_module_type):
2624    """Recursively apply method delegation to all wrapper modules with main_module in a model.
2625
2626    This traverses the entire model and adds method delegation for any module that has
2627    a main_module attribute and optionally matches specified types.
2628
2629    Args:
2630        model: The PyTorch model to traverse
2631        method_name: The method name to delegate (e.g., '_gradient_checkpointing_func')
2632        main_module_type: main_module type name to filter by.
2633                          Example: 'Qwen2DecoderLayer'
2634
2635    Example:
2636        # Apply gradient checkpointing delegation to all decoder layers
2637        apply_method_delegation_to_model(
2638            model,
2639            '_gradient_checkpointing_func',
2640            main_module_type='Qwen2DecoderLayer'
2641        )
2642
2643    Parameters
2644    ----------
2645    model : PyTorch model.
2646    method_name : method to delegate.
2647    main_module_type : type of module that has this method.
2648
2649    Returns
2650    -------
2651    None
2652        This function does not return a value.
2653    """
2654    count = 0
2655    for name, module in model.named_modules():
2656        # Check if module has main_module attribute (it's a wrapper)
2657        if hasattr(module, "main_module"):
2658            # Check if we should apply based on main_module type
2659            should_apply = True
2660            if main_module_type is not None:
2661                main_module_type_name = type(module.main_module).__name__
2662                should_apply = main_module_type_name == main_module_type
2663
2664            if should_apply:
2665                add_method_delegation_to_module(module, method_name)
2666                count += 1
2667
2668    print(f"[PAI] Applied method delegation to {count} wrapper module instances")

Recursively apply method delegation to all wrapper modules with main_module in a model.

This traverses the entire model and adds method delegation for any module that has a main_module attribute and optionally matches specified types.

Args: model: The PyTorch model to traverse method_name: The method name to delegate (e.g., '_gradient_checkpointing_func') main_module_type: main_module type name to filter by. Example: 'Qwen2DecoderLayer'

Example: # Apply gradient checkpointing delegation to all decoder layers apply_method_delegation_to_model( model, '_gradient_checkpointing_func', main_module_type='Qwen2DecoderLayer' )

Parameters
  • model (PyTorch model.):

  • method_name (method to delegate.):

  • main_module_type (type of module that has this method.):

Returns
  • None: This function does not return a value.
def make_json_serializable(obj):
2671def make_json_serializable(obj):
2672    """Recursively convert non-JSON-serializable objects to strings.
2673
2674    Parameters
2675    ----------
2676    obj : any
2677        The object to convert
2678
2679    Returns
2680    -------
2681    Any
2682        JSON-serializable version of the object
2683    """
2684    if isinstance(obj, (str, int, float, bool, type(None))):
2685        return obj
2686    elif isinstance(obj, dict):
2687        return {k: make_json_serializable(v) for k, v in obj.items()}
2688    elif isinstance(obj, (list, tuple)):
2689        return [make_json_serializable(item) for item in obj]
2690    else:
2691        # Convert non-serializable types to string
2692        return str(obj)

Recursively convert non-JSON-serializable objects to strings.

Parameters
  • obj (any): The object to convert
Returns
  • Any: JSON-serializable version of the object
def extract_gpa_config():
2695def extract_gpa_config():
2696    """Extract all configuration from GPA.pc by calling all get_* methods.
2697
2698    Returns
2699    -------
2700    dict[str, Any]
2701        Dictionary with all GPA.pc configuration values and type metadata
2702
2703    Examples
2704    --------
2705    >>> config = extract_gpa_config()
2706    >>> # Returns: {'max_dendrites': 10, 'device': 'cuda', '_types': {...}}
2707
2708    Parameters
2709    ----------
2710    None
2711
2712    """
2713    config = {}
2714    config_types = {}
2715
2716    # Get all attributes from GPA.pc
2717    for attr_name in dir(GPA.pc):
2718        # Check if it starts with 'get_'
2719        if attr_name.startswith("get_"):
2720            try:
2721                # Get the method
2722                method = getattr(GPA.pc, attr_name)
2723
2724                # Check if it's callable
2725                if callable(method):
2726                    # Call it and store result with key as name without 'get_'
2727                    key = attr_name[4:]  # Remove 'get_' prefix
2728                    value = method()
2729
2730                    # Check if this is an array (has corresponding append_ method)
2731                    append_method_name = f"append_{key}"
2732                    is_array = hasattr(GPA.pc, append_method_name)
2733
2734                    if is_array and isinstance(value, (list, tuple)):
2735                        # Store array element type
2736                        if len(value) > 0:
2737                            element_type = type(value[0]).__name__
2738                        else:
2739                            element_type = None  # empty array, no conversion needed
2740                        config_types[key] = {
2741                            "is_array": True,
2742                            "element_type": element_type,
2743                        }
2744                    else:
2745                        # Store value type
2746                        config_types[key] = {
2747                            "is_array": False,
2748                            "type": type(value).__name__,
2749                        }
2750
2751                    # Make sure value is JSON serializable
2752                    config[key] = make_json_serializable(value)
2753            except Exception as e:
2754                # Skip if method fails
2755                if GPA.pc.get_verbose():
2756                    print(f"Skipping {attr_name}: {e}")
2757                continue
2758
2759    # Add types metadata to config
2760    config["_types"] = config_types
2761
2762    return config

Extract all configuration from GPA.pc by calling all get_* methods.

Returns
  • dict[str, Any]: Dictionary with all GPA.pc configuration values and type metadata
Examples
>>> config = extract_gpa_config()
>>> # Returns: {'max_dendrites': 10, 'device': 'cuda', '_types': {...}}
Parameters
  • None
def convert_to_type(value, type_name):
2765def convert_to_type(value, type_name):
2766    """Convert a value to the specified type.
2767
2768    Parameters
2769    ----------
2770    value : any
2771        The value to convert
2772    type_name : str
2773        The target type name
2774
2775    Returns
2776    -------
2777    Any
2778        The converted value
2779    """
2780    if type_name == "NoneType" or value is None:
2781        return None
2782    elif type_name == "bool":
2783        if isinstance(value, str):
2784            return value.lower() in ("true", "1", "yes")
2785        return bool(value)
2786    elif type_name == "int":
2787        return int(value)
2788    elif type_name == "float":
2789        return float(value)
2790    elif type_name == "str":
2791        return str(value)
2792    elif type_name == "list":
2793        if not isinstance(value, list):
2794            return [value]
2795        return value
2796    elif type_name == "dict":
2797        if not isinstance(value, dict):
2798            return {}
2799        return value
2800    elif type_name == "type":
2801        # Handle type objects - convert string representation back to type
2802        if isinstance(value, str):
2803            # Try to evaluate the type string (e.g., "<class 'torch.nn.Linear'>")
2804            # Extract the class path from the string
2805            if value.startswith("<class '") and value.endswith("'>"):
2806                class_path = value[
2807                    8:-2
2808                ]  # Extract 'torch.nn.Linear' from "<class 'torch.nn.Linear'>"
2809                parts = class_path.split(".")
2810                # Try to import and get the type
2811                try:
2812                    module_name = ".".join(parts[:-1])
2813                    class_name = parts[-1]
2814                    module = __import__(module_name, fromlist=[class_name])
2815                    return getattr(module, class_name)
2816                except Exception as e:
2817                    print(
2818                        f"Warning: Could not convert type string '{value}' to actual type: {e}"
2819                    )
2820                    return value
2821            return value
2822        return value
2823    elif type_name == "dtype":
2824        # Handle torch dtype objects
2825        if isinstance(value, str):
2826            # Convert string like "torch.float32" to actual dtype
2827            import torch
2828
2829            try:
2830                # Try to get the dtype from torch module
2831                if value.startswith("torch."):
2832                    dtype_name = value.split(".")[
2833                        1
2834                    ]  # Get 'float32' from 'torch.float32'
2835                    return getattr(torch, dtype_name)
2836                else:
2837                    return getattr(torch, value)
2838            except Exception as e:
2839                print(
2840                    f"Warning: Could not convert dtype string '{value}' to actual dtype: {e}"
2841                )
2842                return value
2843        return value
2844    elif type_name == "device":
2845        # Handle torch device objects
2846        if isinstance(value, str):
2847            # Convert string like "cuda" or "cpu" to torch.device
2848            import torch
2849
2850            try:
2851                return torch.device(value)
2852            except Exception as e:
2853                print(
2854                    f"Warning: Could not convert device string '{value}' to actual device: {e}"
2855                )
2856                return value
2857        return value
2858    elif type_name == "builtin_function_or_method":
2859        # Handle torch functions like torch.sigmoid, torch.relu, etc.
2860        if isinstance(value, str):
2861            # Parse string like "<built-in method sigmoid of type object at 0x...>"
2862            # to extract the function name
2863            import torch
2864
2865            try:
2866                if "<built-in method " in value and " of type object" in value:
2867                    # Extract function name between '<built-in method ' and ' of type object'
2868                    start = value.find("<built-in method ") + len("<built-in method ")
2869                    end = value.find(" of type object")
2870                    func_name = value[start:end]
2871                    # Try to get the function from torch module
2872                    if hasattr(torch, func_name):
2873                        return getattr(torch, func_name)
2874                    else:
2875                        print(f"Warning: torch.{func_name} not found")
2876                        return value
2877                else:
2878                    return value
2879            except Exception as e:
2880                print(
2881                    f"Warning: Could not convert builtin function string '{value}': {e}"
2882                )
2883                return value
2884        return value
2885    else:
2886        # Unknown type - error and debug
2887        print(f"ERROR: Unknown type '{type_name}' for value: {value}")
2888        print(f"Type of value is: {type(value).__name__}")
2889        pdb.set_trace()
2890        return value

Convert a value to the specified type.

Parameters
  • value (any): The value to convert
  • type_name (str): The target type name
Returns
  • Any: The converted value
def convert_to_type_array(value, element_type):
2893def convert_to_type_array(value, element_type):
2894    """Convert an array's elements to the specified type.
2895
2896    Parameters
2897    ----------
2898    value : list or tuple
2899        The array to convert
2900    element_type : str or None
2901        The target type name for elements, None if array was empty
2902
2903    Returns
2904    -------
2905    list
2906        The array with converted elements
2907    """
2908    if not isinstance(value, (list, tuple)):
2909        return value
2910    # If element_type is None (empty array), no conversion needed
2911    if element_type is None:
2912        return list(value) if isinstance(value, tuple) else value
2913    return [convert_to_type(item, element_type) for item in value]

Convert an array's elements to the specified type.

Parameters
  • value (list or tuple): The array to convert
  • element_type (str or None): The target type name for elements, None if array was empty
Returns
  • list: The array with converted elements
def set_gpa_config(config):
2916def set_gpa_config(config):
2917    """Set GPA.pc configuration by calling all set_* methods.
2918
2919    This is the reverse of extract_gpa_config(). It takes a configuration
2920    dictionary and calls the corresponding set_* methods on GPA.pc.
2921    Uses type metadata to ensure values are converted to the correct type.
2922
2923    Parameters
2924    ----------
2925    config : dict
2926        Dictionary with configuration values (keys without 'set_' prefix)
2927        and optional '_types' metadata
2928
2929    Examples
2930    --------
2931    >>> config = {'verbose': True, 'device': 'cuda'}
2932    >>> set_gpa_config(config)
2933    # Calls GPA.pc.set_verbose(True), GPA.pc.set_device('cuda'), etc.
2934
2935    Returns
2936    -------
2937    Count of parameters that were set
2938    """
2939    set_count = 0
2940    skip_count = 0
2941
2942    # Extract type information
2943    config_types = config.get("_types", {})
2944
2945    for key, value in config.items():
2946        # Skip the types metadata
2947        if key == "_types":
2948            continue
2949
2950        # Construct the set method name
2951        set_method_name = f"set_{key}"
2952
2953        # Check if the set method exists
2954        if hasattr(GPA.pc, set_method_name):
2955            try:
2956                method = getattr(GPA.pc, set_method_name)
2957                if callable(method):
2958                    # Convert value to correct type if we have type info
2959                    if key in config_types:
2960                        type_info = config_types[key]
2961                        if type_info.get("is_array", False):
2962                            # Convert array elements to correct type
2963                            element_type = type_info.get("element_type", "str")
2964                            value = convert_to_type_array(value, element_type)
2965                        else:
2966                            # Convert single value to correct type
2967                            value_type = type_info.get("type", "str")
2968                            value = convert_to_type(value, value_type)
2969
2970                    method(value)
2971                    set_count += 1
2972                    if GPA.pc.get_verbose():
2973                        print(f"Set {key} = {value}")
2974            except Exception as e:
2975                skip_count += 1
2976                if GPA.pc.get_verbose():
2977                    print(f"Failed to set {key}: {e}")
2978        else:
2979            skip_count += 1
2980            if GPA.pc.get_verbose():
2981                print(f"No setter found for {key} (looking for {set_method_name})")
2982
2983    if GPA.pc.get_verbose():
2984        print(f"Applied {set_count} PAI configuration settings ({skip_count} skipped)")
2985
2986    return set_count

Set GPA.pc configuration by calling all set_* methods.

This is the reverse of extract_gpa_config(). It takes a configuration dictionary and calls the corresponding set_* methods on GPA.pc. Uses type metadata to ensure values are converted to the correct type.

Parameters
  • config (dict): Dictionary with configuration values (keys without 'set_' prefix) and optional '_types' metadata
Examples
>>> config = {'verbose': True, 'device': 'cuda'}
>>> set_gpa_config(config)
<h1 id="calls-gpapcset_verbosetrue-gpapcset_devicecuda-etc">Calls GPA.pc.set_verbose(True), GPA.pc.set_device('cuda'), etc.</h1>
Returns
  • Count of parameters that were set
def upload_to_huggingface(*args, **kwargs):
3196    def upload_to_huggingface(*args, **kwargs):
3197        """Raise an informative error when HuggingFace dependencies are missing.
3198
3199        Parameters
3200        ----------
3201        *args : tuple[Any, ...]
3202            Positional arguments accepted for API compatibility.
3203        **kwargs : dict[str, Any]
3204            Keyword arguments accepted for API compatibility.
3205
3206        Returns
3207        -------
3208        None
3209            Always raises ``ImportError``.
3210        """
3211        raise ImportError(
3212            "huggingface_hub is required for upload_to_huggingface. "
3213            "Install it with: pip install huggingface_hub"
3214        )

Raise an informative error when HuggingFace dependencies are missing.

Parameters
  • *args (tuple[Any, ...]): Positional arguments accepted for API compatibility.
  • **kwargs (dict[str, Any]): Keyword arguments accepted for API compatibility.
Returns
  • None: Always raises ImportError.
def from_hf_pretrained(*args, **kwargs):
3216    def from_hf_pretrained(*args, **kwargs):
3217        """Raise an informative error when HuggingFace dependencies are missing.
3218
3219        Parameters
3220        ----------
3221        *args : tuple[Any, ...]
3222            Positional arguments accepted for API compatibility.
3223        **kwargs : dict[str, Any]
3224            Keyword arguments accepted for API compatibility.
3225
3226        Returns
3227        -------
3228        None
3229            Always raises ``ImportError``.
3230        """
3231        raise ImportError(
3232            "huggingface_hub is required for from_hf_pretrained. "
3233            "Install it with: pip install huggingface_hub"
3234        )

Raise an informative error when HuggingFace dependencies are missing.

Parameters
  • *args (tuple[Any, ...]): Positional arguments accepted for API compatibility.
  • **kwargs (dict[str, Any]): Keyword arguments accepted for API compatibility.
Returns
  • None: Always raises ImportError.