perforatedai.modules_perforatedai
1# Copyright (c) 2025 Perforated AI 2 3import copy 4import math 5import os 6import pdb 7import sys 8import time 9from datetime import datetime 10 11import numpy as np 12import torch 13import torch.nn as nn 14import traceback 15 16from perforatedai import globals_perforatedai as GPA 17from perforatedai import utils_perforatedai as UPA 18 19try: 20 from perforatedbp import modules_pbp as MPB 21 from perforatedbp.dendrite_losses.improved_covariance_loss import ImprovedCovarianceDendriteLoss 22except ModuleNotFoundError as e: 23 # Only pass if perforatedbp package itself is missing 24 if e.name == "perforatedbp": 25 pass 26 else: 27 # perforatedbp exists but is missing a dependency 28 raise 29 30 31# Every parameter PAI manages gets a parameter_type attribute saying when it trains: 32# "neuron" - weights of the original modules. Train in neuron mode. 33# "tree" - dendrites_to_top, the output weights connecting dendrites to their 34# neurons. Train in neuron mode. 35# "dendrite" - weights of added dendrites (layers and dendrites_to_dendrites). 36# Train in neuron mode unless dendrite_update_mode is False. 37# "candidate" - candidate dendrites and their inputs from existing dendrites. 38# Train in dendrite mode with perforated backpropagation. 39# "ignored" - reference copies of modules that never train. 40# The types are set where the parameters are created, so they survive reloading a 41# saved model, which recreates the dendrites by simulating the cycles that added them. 42DENDRITE_PARAMETER_TYPES = ("dendrite", "tree") 43 44 45def set_parameter_type(module, parameter_type): 46 """Set the parameter_type of all parameters of a module. 47 48 Parameters 49 ---------- 50 module : nn.Module 51 Module whose parameters to tag, including all its submodules. 52 parameter_type : str 53 One of "neuron", "tree", "dendrite", "candidate" or "ignored". 54 55 Returns 56 ------- 57 None 58 """ 59 for param in module.parameters(): 60 param.parameter_type = parameter_type 61 62 63def set_main_parameters(module): 64 """Set the parameters registered directly on a module, not on its submodules, to "neuron". 65 66 Parameters 67 ---------- 68 module : nn.Module 69 Module whose own parameters to tag. 70 71 Returns 72 ------- 73 None 74 """ 75 for param in module.parameters(recurse=False): 76 param.parameter_type = "neuron" 77 78 79def is_dendrite_parameter(param): 80 """Return whether a parameter belongs to a dendrite ("dendrite" or "tree" parameter_type). 81 82 Parameters 83 ---------- 84 param : torch.Tensor 85 The parameter to check. 86 87 Returns 88 ------- 89 bool 90 True for dendrite weights and dendrite output weights. 91 """ 92 return getattr(param, "parameter_type", None) in DENDRITE_PARAMETER_TYPES 93 94 95# Values for Dendrite training, minimally used in open source version 96_DENDRITE_TENSOR_VALUES_BASE = [ 97 "shape" 98] # Shape is tensor of same shape as total neurons in module 99_DENDRITE_SINGLE_VALUES_BASE = [] 100 101DENDRITE_INIT_VALUES = ["initialized", "current_d_init"] 102 103_VALUE_TRACKER_ARRAYS_BASE = ["dendrite_outs"] 104 105# Cached values to avoid recomputation (each tracks its own state) 106# The tensor/single caches also track the selected loss class, because their contents 107# come from methods on that class; the loss-class companion fields let the guard rebuild 108# when the class changes, not only when Perforated Backpropagation is toggled. 109_cached_dendrite_tensor_values = None 110_cached_dendrite_tensor_pb_state = None 111_cached_dendrite_tensor_loss_class = None 112_cached_dendrite_single_values = None 113_cached_dendrite_single_pb_state = None 114_cached_dendrite_single_loss_class = None 115_cached_value_tracker_arrays = None 116_cached_value_tracker_pb_state = None 117 118 119def get_DENDRITE_TENSOR_VALUES(): 120 """Get DENDRITE_TENSOR_VALUES, updating from MPB if perforated_backpropagation is enabled. 121 122 Parameters 123 ---------- 124 None 125 126 Returns 127 ------- 128 list[str] 129 Names of tensor attributes used for dendrite state handling. 130 """ 131 global _cached_dendrite_tensor_values, _cached_dendrite_tensor_pb_state, _cached_dendrite_tensor_loss_class 132 current_pb_state = GPA.pc.get_perforated_backpropagation() 133 # The loss class is only relevant, and only readable, when PB is enabled. Read it 134 # through the accessor (single-writer invariant); it is a class object, so the guard 135 # compares it by identity below. 136 current_loss_class = MPB.get_global_dendrite_loss_class() if current_pb_state else None 137 138 if ( 139 _cached_dendrite_tensor_values is None 140 or _cached_dendrite_tensor_pb_state != current_pb_state 141 or _cached_dendrite_tensor_loss_class is not current_loss_class 142 ): 143 _cached_dendrite_tensor_pb_state = current_pb_state 144 _cached_dendrite_tensor_loss_class = current_loss_class 145 if current_pb_state: 146 _cached_dendrite_tensor_values = MPB.update_dendrite_tensor_values( 147 _DENDRITE_TENSOR_VALUES_BASE.copy() 148 ) 149 else: 150 _cached_dendrite_tensor_values = _DENDRITE_TENSOR_VALUES_BASE.copy() 151 152 return _cached_dendrite_tensor_values 153 154 155def get_DENDRITE_SINGLE_VALUES(): 156 """Get DENDRITE_SINGLE_VALUES, updating from MPB if perforated_backpropagation is enabled. 157 158 Parameters 159 ---------- 160 None 161 162 Returns 163 ------- 164 list[str] 165 Names of scalar attributes used for dendrite state handling. 166 """ 167 global _cached_dendrite_single_values, _cached_dendrite_single_pb_state, _cached_dendrite_single_loss_class 168 current_pb_state = GPA.pc.get_perforated_backpropagation() 169 # The loss class is only relevant, and only readable, when PB is enabled. Read it 170 # through the accessor (single-writer invariant); it is a class object, so the guard 171 # compares it by identity below. 172 current_loss_class = MPB.get_global_dendrite_loss_class() if current_pb_state else None 173 174 if ( 175 _cached_dendrite_single_values is None 176 or _cached_dendrite_single_pb_state != current_pb_state 177 or _cached_dendrite_single_loss_class is not current_loss_class 178 ): 179 _cached_dendrite_single_pb_state = current_pb_state 180 _cached_dendrite_single_loss_class = current_loss_class 181 if current_pb_state: 182 _cached_dendrite_single_values = MPB.update_dendrite_single_values( 183 _DENDRITE_SINGLE_VALUES_BASE.copy() 184 ) 185 else: 186 _cached_dendrite_single_values = _DENDRITE_SINGLE_VALUES_BASE.copy() 187 188 return _cached_dendrite_single_values 189 190 191def get_VALUE_TRACKER_ARRAYS(): 192 """Get VALUE_TRACKER_ARRAYS, updating from MPB if perforated_backpropagation is enabled. 193 194 Parameters 195 ---------- 196 None 197 198 Returns 199 ------- 200 list[str] 201 Names of array-valued fields tracked in ``DendriteValueTracker``. 202 """ 203 global _cached_value_tracker_arrays, _cached_value_tracker_pb_state 204 current_pb_state = GPA.pc.get_perforated_backpropagation() 205 206 if ( 207 _cached_value_tracker_arrays is None 208 or _cached_value_tracker_pb_state != current_pb_state 209 ): 210 _cached_value_tracker_pb_state = current_pb_state 211 if current_pb_state: 212 _cached_value_tracker_arrays = MPB.update_value_tracker_arrays( 213 _VALUE_TRACKER_ARRAYS_BASE.copy() 214 ) 215 else: 216 _cached_value_tracker_arrays = _VALUE_TRACKER_ARRAYS_BASE.copy() 217 218 return _cached_value_tracker_arrays 219 220 221def get_DENDRITE_REINIT_VALUES(): 222 """Get DENDRITE_REINIT_VALUES. 223 224 Parameters 225 ---------- 226 None 227 228 Returns 229 ------- 230 list[str] 231 Combined list of attribute names that must be reinitialized. 232 """ 233 return get_DENDRITE_TENSOR_VALUES() + get_DENDRITE_SINGLE_VALUES() 234 235 236def get_DENDRITE_SAVE_VALUES(): 237 """Get DENDRITE_SAVE_VALUES. 238 239 Parameters 240 ---------- 241 None 242 243 Returns 244 ------- 245 list[str] 246 Combined list of attribute names persisted for save/load. 247 """ 248 return ( 249 get_DENDRITE_TENSOR_VALUES() 250 + get_DENDRITE_SINGLE_VALUES() 251 + DENDRITE_INIT_VALUES 252 ) 253 254 255def filter_backward(grad_out, values, module=None): 256 """Filter backward pass for gradient processing. 257 258 This function processes gradients during the backward pass, 259 ensuring correct input dimensions,and applying perforated backpropagation if enabled. 260 261 Parameters 262 ---------- 263 grad_out : torch.Tensor 264 The gradient output tensor from the backward pass. 265 values : DendriteValueTracker 266 A DendriteValueTracker instance containing values associated with the module being processed. 267 module : PAINeuronModule, optional 268 The owning PAINeuronModule instance. When provided and PBP is disabled, 269 the hook deregisters itself after the one-time initialization completes, 270 eliminating per-batch Python overhead on all subsequent backward passes. 271 272 Returns 273 ------- 274 None 275 """ 276 if GPA.pc.get_extra_verbose(): 277 print(f"{values[0].layer_name} calling backward") 278 279 with torch.no_grad(): 280 val = grad_out.detach() 281 # Fast path: Python bool set after first backward in this process. 282 # Fallback: current_d_init is a saved buffer — survives checkpoint reload 283 # even when _fb_init_done resets to False in a fresh process. 284 already_init = (module is not None and module._fb_init_done) or \ 285 values[0].current_d_init.item() 286 if not already_init: 287 # If input dimensions and gradient don't have same shape trigger error and quit 288 if len(values[0].this_output_dimensions) != len(grad_out.shape): 289 print( 290 "The following module has not properly set this_output_dimensions" 291 ) 292 print(values[0].layer_name) 293 print("it is expecting:") 294 print(values[0].this_output_dimensions) 295 print("but received") 296 print(grad_out.shape) 297 print( 298 "to check these all at once set GPA.pc.set_debugging_output_dimensions(1)" 299 ) 300 print( 301 f"Call MODEL_VARIABLE{values[0].layer_name}.set_this_output_dimensions([...]) on this module after perforate_model" 302 ) 303 print( 304 "where the ... is replaced with the correct vector as described in section 4 of customization.md" 305 ) 306 if not GPA.pc.get_debugging_output_dimensions(): 307 sys.exit(0) 308 else: 309 GPA.pc.set_debugging_output_dimensions(2) 310 return 311 # Make sure that the input dimensions are correct 312 for i in range(len(values[0].this_output_dimensions)): 313 if values[0].this_output_dimensions[i] == GPA.NODE_AXIS: 314 continue 315 # Make sure all input dimensions are either REDUCE_AXIS (reduce), 316 # NOT_REDUCE_OR_NODE_AXIS (retain), or exact values (old format) 317 if ( 318 not (grad_out.shape[i] == values[0].this_output_dimensions[i]) 319 and not values[0].this_output_dimensions[i] == GPA.REDUCE_AXIS 320 and not values[0].this_output_dimensions[i] == GPA.NOT_REDUCE_OR_NODE_AXIS 321 ): 322 print( 323 "The following module has not properly set this_output_dimensions with this incorrect shape" 324 ) 325 print(values[0].layer_name) 326 print("it is expecting:") 327 print(values[0].this_output_dimensions) 328 print("but received") 329 print(grad_out.shape) 330 print( 331 "to check these all at once set GPA.pc.set_debugging_output_dimensions(1)" 332 ) 333 if not GPA.pc.get_debugging_output_dimensions(): 334 sys.exit(0) 335 else: 336 GPA.pc.set_debugging_output_dimensions(2) 337 return 338 # Setup the arrays with the now known shape 339 with torch.no_grad(): 340 if GPA.pc.get_verbose(): 341 print("setting d shape for") 342 print(values[0].layer_name) 343 print(val.size()) 344 345 values[0].set_out_channels(val.size()) 346 ndim = len(values[0].this_output_dimensions) 347 storage_shape = [1] * ndim 348 for _i in range(ndim): 349 if values[0].this_output_dimensions[_i] == GPA.NOT_REDUCE_OR_NODE_AXIS: 350 storage_shape[_i] = val.shape[_i] 351 storage_shape[values[0].this_node_index.item()] = values[0].out_channels 352 values[0].setup_arrays(storage_shape) 353 # Flag that it has been setup (both the GPU tensor and the fast Python bool) 354 values[0].current_d_init[0] = 1 355 if module is not None: 356 module._fb_init_done = True 357 # When PBP is disabled this hook has no further work to do. 358 # Deregister it so it never fires again, eliminating per-batch 359 # Python overhead on all subsequent backward passes. 360 if not GPA.pc.get_perforated_backpropagation() and module._fb_hook_handle is not None: 361 module._fb_hook_handle.remove() 362 module._fb_hook_handle = None 363 if GPA.pc.get_perforated_backpropagation(): 364 MPB.filter_backward_pb(val, values) 365 366 367def set_wrapped_params(model): 368 """Set parameters as wrapped with dendrites. 369 370 Parameters 371 ---------- 372 model : torch.nn.Module 373 The model whose parameters are to be marked as wrapped. 374 375 Returns 376 ------- 377 None 378 379 """ 380 for param in model.parameters(): 381 param.wrapped = True 382 383 384def set_tracked_params(model): 385 """Set parameters as tracked without dendrites. 386 387 Parameters 388 ---------- 389 model : torch.nn.Module 390 The model whose parameters are to be marked as tracked. 391 392 Returns 393 ------- 394 None 395 """ 396 for param in model.parameters(): 397 param.tracked = True 398 399 400class PAINeuronModule(nn.Module): 401 """Wrapper to set a module as one that will have dendritic copies.""" 402 403 def __init__(self, start_module, name): 404 """Initialize PAINeuronModule. 405 406 This function sets up the neuron module to wrap the start_module 407 and manage its dendritic connections. 408 409 Parameters 410 ---------- 411 start_module : nn.Module 412 The module to wrap. 413 name : str 414 The name of the neuron module. 415 """ 416 super(PAINeuronModule, self).__init__() 417 418 if isinstance(start_module, nn.Module): 419 self.main_module = start_module 420 else: 421 print("start_module must be nn.Module: %s" % name) 422 print(type(start_module)) 423 print(start_module) 424 sys.exit(-1) 425 self.name = name 426 # Per-module config: loads custom settings from {save_name}_config.json if present. 427 # Passes both the instance name (id) and the module type so load_config can 428 # fall back to type-level settings when no name-specific entry exists. 429 _module_type_name = type(start_module).__name__ 430 self.module_config = GPA.PAIConfig( 431 module_name=self.name, module_type=_module_type_name 432 ) 433 434 set_wrapped_params(self.main_module) 435 if self.module_config.get_verbose(): 436 print( 437 f"initing a module {self.name} with main type {type(self.main_module)}" 438 ) 439 print(start_module) 440 441 # If this main_module is one that requires processing set the processor 442 if type(self.main_module) in self.module_config.get_modules_with_processing(): 443 module_index = self.module_config.get_modules_with_processing().index( 444 type(self.main_module) 445 ) 446 self.processor = self.module_config.get_modules_processing_classes()[ 447 module_index 448 ]() 449 if self.module_config.get_verbose(): 450 print("with processor") 451 print(self.processor) 452 elif ( 453 type(self.main_module).__name__ 454 in self.module_config.get_module_names_with_processing() 455 ): 456 module_index = self.module_config.get_module_names_with_processing().index( 457 type(self.main_module).__name__ 458 ) 459 self.processor = self.module_config.get_module_by_name_processing_classes()[ 460 module_index 461 ]() 462 if self.module_config.get_verbose(): 463 print("with processor") 464 print(self.processor) 465 else: 466 self.processor = None 467 468 # Field that can be filled in if your activation function requires a parameter 469 self.activation_function_value = -1 470 self.type = "neuron_module" 471 472 # On the wrapped layer's device: DDP's forward_sync_buffers broadcasts every 473 # buffer when wrapping, and NCCL can't send CPU tensors 474 device = next((p.device for p in self.main_module.parameters()), None) 475 self.register_buffer( 476 "this_output_dimensions", 477 (torch.tensor(self.module_config.get_output_dimensions(), device=device)), 478 ) 479 if (self.this_output_dimensions == GPA.NODE_AXIS).sum() != 1: 480 print(f"5 Need exactly one 0 in the input dimensions: {self.name}") 481 print(self.this_output_dimensions) 482 sys.exit(-1) 483 self.register_buffer( 484 "this_node_index", 485 torch.tensor( 486 self.module_config.get_output_dimensions().index(GPA.NODE_AXIS), 487 device=device, 488 ), 489 ) 490 self.dendrite_modules_added = 0 491 492 # Values for dendrite to neuron weights 493 self.dendrites_to_top = nn.ParameterList() 494 self.register_parameter("newest_dendrite_to_top", None) 495 self.candidate_to_top = nn.ParameterList() 496 self.register_parameter("current_candidate_to_top", None) 497 # Create the dendrite module 498 self.dendrite_module = PAIDendriteModule( 499 self.main_module, 500 activation_function_value=self.activation_function_value, 501 name=self.name, 502 output_dimensions=self.this_output_dimensions, 503 ) 504 # If it is linear and default has convolutional dimensions, automatically set to just be batch size and neuron indexes 505 if ( 506 issubclass(type(start_module), nn.Linear) 507 or ( 508 issubclass(type(start_module), GPA.PAISequential) 509 and issubclass(type(start_module.model[0]), nn.Linear) 510 ) 511 ) and ( 512 self.this_output_dimensions[2:] != GPA.NODE_AXIS 513 ).all(): # Everything past 2 is not the node axis 514 self.set_this_output_dimensions(self.this_output_dimensions[0:2]) 515 if ( 516 issubclass(type(start_module), nn.Conv1d) 517 or ( 518 issubclass(type(start_module), GPA.PAISequential) 519 and issubclass(type(start_module.model[0]), nn.Conv1d) 520 ) 521 ) and ( 522 self.this_output_dimensions[3:] != GPA.NODE_AXIS 523 ).all(): # Everything past 3 is not the node axis 524 self.set_this_output_dimensions(self.this_output_dimensions[0:3]) 525 # Apply per-module output_dimensions override from config if present 526 _custom_dims = self.module_config.__dict__.get("_output_dimensions") 527 if _custom_dims is not None: 528 self.set_this_output_dimensions(torch.tensor(_custom_dims)) 529 GPA.pai_tracker.add_pai_neuron_module(self) 530 set_parameter_type(self.main_module, "neuron") 531 532 # Track filter_backward initialization state as a 533 # plain Python bool (avoids a GPU .item() sync on every backward pass). 534 # _fb_hook_handle stores the registered hook handle so it can be 535 # removed after initialization completes when PBP is disabled. 536 self._fb_init_done = False 537 self._fb_hook_handle = None 538 539 def __getattr__(self, name): 540 """Get member variables from the main module. 541 542 Parameters 543 ---------- 544 name : str 545 The name of the variable to retrieve. 546 Returns 547 ------- 548 The requested variable. 549 550 Notes 551 ----- 552 This method first attempts to retrieve the attribute from the PAINeuronModule instance. 553 If it fails, it tries to get the attribute from the wrapped main_module. 554 This allows seamless access to the main module's attributes without modifying original code. 555 """ 556 try: 557 return super().__getattr__(name) 558 except AttributeError: 559 return getattr(self.main_module, name) 560 561 def __getitem__(self, index): 562 """Support indexing operations on the main module. 563 564 Parameters 565 ---------- 566 index : int or slice 567 The index or slice to retrieve. 568 569 Returns 570 ------- 571 The indexed item from the main module. 572 """ 573 return self.main_module[index] 574 575 def apply_pb_grads(self): 576 """Apply perforated backpropagation gradients if enabled. 577 578 Parameters 579 ---------- 580 None 581 582 Returns 583 ------- 584 None 585 This function does not return a value. 586 """ 587 self.dendrite_module.apply_pb_grads() 588 589 def apply_pb_zero(self): 590 """Clear leftover saved tensors if there are any. 591 592 Parameters 593 ---------- 594 None 595 596 Returns 597 ------- 598 None 599 This function does not return a value. 600 """ 601 self.dendrite_module.apply_pb_zero() 602 603 def clear_processors(self): 604 """Clear processors if they save values for DeepCopy and save. 605 606 Parameters 607 ---------- 608 None 609 610 Returns 611 ------- 612 None 613 """ 614 615 if not self.processor: 616 return 617 else: 618 self.processor.clear_processor() 619 self.dendrite_module.clear_processors() 620 621 def clear_dendrites(self): 622 """Clear and reset dendrites before loading from a state dict. 623 624 Parameters 625 ---------- 626 None 627 628 Returns 629 ------- 630 None 631 632 """ 633 # Loading a saved state reconstructs PAIDendriteModule before simulating 634 # its saved cycles. Preserve a registered variant factory so candidate 635 # creation does not silently fall back to deep-copying the parent module. 636 create_dendrite_fn = self.dendrite_module._create_dendrite_fn 637 self.dendrite_modules_added = 0 638 self.dendrites_to_top = nn.ParameterList() 639 self.candidate_to_top = nn.ParameterList() 640 self.dendrite_module = PAIDendriteModule( 641 self.main_module, 642 activation_function_value=self.activation_function_value, 643 name=self.name, 644 output_dimensions=self.this_output_dimensions, 645 ) 646 if create_dendrite_fn is not None: 647 self.dendrite_module.set_create_dendrite(create_dendrite_fn) 648 649 def __str__(self): 650 """String representation of the module. 651 652 Parameters 653 ---------- 654 None 655 656 Returns 657 ------- 658 str 659 String representation of the module. 660 661 Notes 662 ----- 663 Setting for verbose changes level of details in the string output. 664 """ 665 # If verbose print the whole module otherwise just print the module type as a PAIModule 666 if self.module_config.get_verbose(): 667 total_string = self.main_module.__str__() 668 total_string = "PAIModule(" + total_string + ")" 669 return total_string + self.dendrite_module.__str__() 670 else: 671 total_string = self.main_module.__str__() 672 total_string = "PAIModule(" + total_string + ")" 673 return total_string 674 675 def __repr__(self): 676 """Representation of the module.""" 677 return self.__str__() 678 679 def set_this_output_dimensions(self, new_output_dimensions): 680 """Set the input dimensions for the neuron and dendrite blocks. 681 682 Signals to this NeuronModule that its input dimensions are different 683 than the global default. 684 685 Parameters 686 ---------- 687 new_output_dimensions : list 688 A list or tensor specifying the new input dimensions. 689 Returns 690 ------- 691 None 692 693 """ 694 if type(new_output_dimensions) is list: 695 new_output_dimensions = torch.tensor(new_output_dimensions) 696 device = self.this_output_dimensions.device 697 delattr(self, "this_output_dimensions") 698 self.register_buffer( 699 "this_output_dimensions", new_output_dimensions.detach().clone().to(device) 700 ) 701 if (new_output_dimensions == GPA.NODE_AXIS).sum() != 1: 702 print(f"6 need exactly one 0 in the input dimensions: {self.name}") 703 print(new_output_dimensions) 704 self.this_node_index.copy_( 705 (new_output_dimensions == GPA.NODE_AXIS).nonzero(as_tuple=True)[0][0] 706 ) 707 self.dendrite_module.set_this_output_dimensions(new_output_dimensions) 708 709 def set_create_dendrite(self, fn): 710 """Set a custom function for creating dendrite modules. 711 712 Override how dendrite copies are created from the parent module. By default 713 the parent module is deep-copied. Pass any callable with the signature 714 ``fn(parent_module) -> nn.Module`` to replace that behaviour. 715 716 Parameters 717 ---------- 718 fn : callable 719 A function with signature ``fn(parent_module) -> nn.Module``. 720 721 Returns 722 ------- 723 None 724 """ 725 self.dendrite_module.set_create_dendrite(fn) 726 727 728 def set_mode(self, mode): 729 """Switch between neuron training and dendrite training. 730 731 Parameters 732 ---------- 733 mode : str 734 The mode to set. Either "n" for neuron training or "p" for pai-dendrite training. 735 736 Returns 737 ------- 738 bool 739 True if mode was set successfully, False otherwise. 740 741 Notes 742 ----- 743 If False is returned, the mode was not changed due to an error. 744 This is a problem that should not be ignored, but it can be ignored 745 by calling PGA.pc.set_checked_skipped_modules(True) 746 """ 747 748 if self.module_config.get_verbose(): 749 print(f"{self.name} calling set mode {mode}") 750 # If returning to neuron training 751 if mode == "n": 752 self.dendrite_module.set_mode(mode) 753 # Initialize the dendrite to neuron connections 754 if self.dendrite_modules_added > 0: 755 if self.module_config.get_learn_dendrites_live(): 756 values = torch.cat( 757 ( 758 self.dendrites_to_top[self.dendrite_modules_added - 1], 759 nn.Parameter( 760 self.candidate_to_top.detach() 761 .clone() 762 .to(dtype=self.module_config.get_d_type()) 763 ), 764 ), 765 0, 766 ) 767 else: 768 values = torch.cat( 769 ( 770 self.dendrites_to_top[self.dendrite_modules_added - 1], 771 nn.Parameter( 772 torch.zeros( 773 (1, self.out_channels), 774 device=self.dendrites_to_top[ 775 self.dendrite_modules_added - 1 776 ].device, 777 dtype=self.module_config.get_d_type(), 778 ) 779 ), 780 ), 781 0, 782 ) 783 # Freeze the previous dendrites_to_top entry 784 # so the optimizer no longer updates stale entries. Only the 785 # most recently appended entry is ever used in the forward pass. 786 if len(self.dendrites_to_top) > 0: 787 self.dendrites_to_top[-1].requires_grad_(False) 788 self.dendrites_to_top.append( 789 nn.Parameter( 790 values.detach() 791 .clone() 792 .to( 793 device=self.module_config.get_device(), 794 dtype=self.module_config.get_d_type(), 795 ), 796 requires_grad=True, 797 ) 798 ) 799 else: 800 if self.module_config.get_learn_dendrites_live(): 801 # Freeze previous entry before appending new one. 802 if len(self.dendrites_to_top) > 0: 803 self.dendrites_to_top[-1].requires_grad_(False) 804 self.dendrites_to_top.append( 805 nn.Parameter( 806 self.candidate_to_top.detach() 807 .clone() 808 .to(dtype=self.module_config.get_d_type()), 809 requires_grad=True, 810 ) 811 ) 812 else: 813 # Freeze previous entry before appending new one. 814 if len(self.dendrites_to_top) > 0: 815 self.dendrites_to_top[-1].requires_grad_(False) 816 self.dendrites_to_top.append( 817 nn.Parameter( 818 torch.zeros( 819 (1, self.out_channels), 820 device=self.module_config.get_device(), 821 dtype=self.module_config.get_d_type(), 822 ) 823 .detach() 824 .clone(), 825 requires_grad=True, 826 ) 827 ) 828 self.dendrite_modules_added += 1 829 if self.module_config.get_perforated_backpropagation(): 830 MPB.set_module_n_pb(self) 831 set_parameter_type(self.dendrites_to_top, "tree") 832 833 # If starting dendrite training 834 else: 835 try: 836 # Save the values that were calculated in filter_backward 837 self.out_channels = self.dendrite_module.dendrite_values[0].out_channels 838 self.dendrite_module.out_channels = ( 839 self.dendrite_module.dendrite_values[0].out_channels 840 ) 841 except Exception as e: 842 print(e) 843 print( 844 f"this occurred in module: {self.dendrite_module.dendrite_values[0].layer_name}" 845 ) 846 print( 847 "Module should be added to module_names_to_track so it doesn't have dendrites added" 848 ) 849 print("If you are getting here but out_channels has not been set") 850 print( 851 "A common reason is that this module never had gradients flow through it." 852 ) 853 print("I have seen this happen because:") 854 print("-The weights were frozen (requires_grad = False)") 855 print( 856 "-A model is added but not used so it was converted to a perforated module initialized" 857 ) 858 print( 859 "-A module was converted that doesn't have weights that get modified so backward doesn't flow through it" 860 ) 861 print( 862 "If this is normal behavior set GPA.pc.set_checked_skipped_modules(True) in the main to ignore" 863 ) 864 print( 865 "You can also set right now in this pdb terminal to have this not happen more after checking all modules this cycle." 866 ) 867 if not self.module_config.get_checked_skipped_modules(): 868 pdb.set_trace() 869 return False 870 # Only change mode if it makes it past the above exception 871 self.dendrite_module.set_mode(mode) 872 if self.module_config.get_perforated_backpropagation(): 873 MPB.set_module_p_pb(self) 874 return True 875 876 def create_new_dendrite_module(self): 877 """Add an additional dendrite module. 878 879 Parameters 880 ---------- 881 None 882 883 Returns 884 ------- 885 None 886 """ 887 self.dendrite_module.create_new_dendrite_module(self.main_module) 888 889 def forward(self, *args, **kwargs): 890 """Forward pass through the neuron module. 891 892 Parameters 893 ---------- 894 *args : tuple 895 Positional arguments for the forward pass. 896 **kwargs : dict 897 Keyword arguments for the forward pass. 898 899 Returns 900 ------- 901 Any 902 The output of the module after processing through the neuron and dendrite modules. 903 904 Notes 905 ----- 906 The output of this forward function will have the same format as the output 907 of the original module 908 """ 909 910 # If debugging all input dimensions, quit program on first forward call 911 if self.module_config.get_debugging_output_dimensions() == 2: 912 print("all input dim problems now printed") 913 sys.exit(0) 914 if self.module_config.get_extra_verbose(): 915 print(f"{self.name} calling forward") 916 # Call the main modules forward 917 out = self.main_module(*args, **kwargs) 918 # Filter with the processor if required 919 if self.processor is not None: 920 try: 921 out = self.processor.post_n1(out) 922 except Exception as e: 923 traceback.print_exc(limit=None, chain=True) 924 print(f"Your post_n1 processor for {self.name} caused this error") 925 print( 926 f"You must check how this is defined and ensure that it is properly" 927 ) 928 print(f"accepting outputs from the neuron module and returning the") 929 print(f"single tensor to be combined with the dendrites output tensor") 930 sys.exit() 931 # Call the forwards for all of the Dendrites 932 ( 933 dendrite_outs, 934 candidate_outs, 935 candidate_nonlinear_outs, 936 candidate_outs_non_zeroed, 937 ) = self.dendrite_module(*args, **kwargs) 938 # If there are dendrites add all of their outputs to the neurons output 939 if self.dendrite_modules_added > 0: 940 for i in range(0, self.dendrite_modules_added): 941 to_top = self.dendrites_to_top[self.dendrite_modules_added - 1][i, :] 942 for dim in range(len(dendrite_outs[i].shape)): 943 if dim == self.this_node_index: 944 continue 945 to_top = to_top.unsqueeze(dim) 946 if self.module_config.get_confirm_correct_sizes(): 947 to_top = to_top.expand( 948 list(dendrite_outs[i].size())[0 : self.this_node_index] 949 + [self.out_channels] 950 + list(dendrite_outs[i].size())[self.this_node_index + 1 :] 951 ) 952 out = out + (dendrite_outs[i].to(out.device) * to_top.to(out.device)) 953 954 # If learning live, add the candidate's output to the neuron's output via the live weight 955 if self.module_config.get_perforated_backpropagation(): 956 out = MPB.apply_live_candidate_to_output( 957 self, out, candidate_nonlinear_outs 958 ) 959 960 # Catch if processors are required 961 if type(out) is tuple: 962 print(self) 963 print( 964 f"The output of the above module {self.name} is a tuple when it must be a single tensor" 965 ) 966 print( 967 "This must be fixed to enable the dendrite and neuron output to be combined" 968 ) 969 print( 970 "Look in the API customization.md at section 2.2 regarding processors to fix this." 971 ) 972 pdb.set_trace() 973 974 # Call filter backward to ensure the neuron index is setup correctly. 975 # Register only when not yet initialized (PBP=False) or always when PBP 976 # is enabled. Store the handle so the hook can deregister itself after 977 # the one-time initialization completes (PBP=False path). 978 if out.requires_grad and (not self._fb_init_done or GPA.pc.get_perforated_backpropagation()): 979 self._fb_hook_handle = out.register_hook( 980 lambda grad: filter_backward(grad, self.dendrite_module.dendrite_values, self) 981 ) 982 983 # If there is a processor apply the second neuron stage 984 if self.processor is not None: 985 try: 986 out = self.processor.post_n2(out) 987 except Exception as e: 988 traceback.print_exc(limit=None, chain=True) 989 print(f"Your post_n2 processor for {self.name} caused this error") 990 print( 991 f"You must check how this is defined and ensure that it is properly" 992 ) 993 print( 994 f"accepting the output tensor after combining the neuron's output " 995 ) 996 print(f"with the dendrite's output and returning something that is the") 997 print(f"same format as your original module's return") 998 sys.exit() 999 return out 1000 1001 1002class TrackedNeuronModule(nn.Module): 1003 """Wrapper for modules you don't want to add dendrites to. Ensures all modules are accounted for.""" 1004 1005 def __init__(self, start_module, name): 1006 """Initialize TrackedNeuronModule. 1007 1008 This function sets up the tracked neuron module to wrap the start_module 1009 without adding dendrites. 1010 1011 Parameters 1012 ---------- 1013 start_module : nn.Module 1014 The module to wrap. 1015 name : str 1016 The name of the neuron module. 1017 """ 1018 super(TrackedNeuronModule, self).__init__() 1019 1020 if isinstance(start_module, nn.Module): 1021 self.main_module = start_module 1022 else: 1023 print("start_module must be nn.Module: %s" % name) 1024 print(type(start_module)) 1025 print(start_module) 1026 sys.exit(-1) 1027 self.name = name 1028 1029 self.type = "tracked_module" 1030 set_tracked_params(self.main_module) 1031 if GPA.pc.get_verbose(): 1032 print( 1033 f"tracking a module {self.name} with main type {type(self.main_module)}" 1034 ) 1035 print(start_module) 1036 GPA.pai_tracker.add_tracked_neuron_module(self) 1037 set_parameter_type(self.main_module, "neuron") 1038 1039 def __getattr__(self, name): 1040 """Get member variables from the main module. 1041 1042 Parameters 1043 ---------- 1044 name : str 1045 The name of the variable to retrieve. 1046 Returns 1047 ------- 1048 The requested variable. 1049 1050 Notes 1051 ----- 1052 This method first attempts to retrieve the attribute from the PAINeuronModule instance. 1053 If it fails, it tries to get the attribute from the wrapped main_module. 1054 This allows seamless access to the main module's attributes without modifying original code. 1055 """ 1056 try: 1057 return super().__getattr__(name) 1058 except AttributeError: 1059 return getattr(self.main_module, name) 1060 1061 def __getitem__(self, index): 1062 """Support indexing operations on the main module. 1063 1064 Parameters 1065 ---------- 1066 index : int or slice 1067 The index or slice to retrieve. 1068 1069 Returns 1070 ------- 1071 The indexed item from the main module. 1072 """ 1073 return self.main_module[index] 1074 1075 def set_mode(self, mode): 1076 """Set mode for tracked module. 1077 1078 Parameters 1079 ---------- 1080 mode : str 1081 The mode to set. Either "n" for neuron training or "p" for pai-dendrite training. 1082 1083 Returns 1084 ------- 1085 bool 1086 True. 1087 1088 Notes 1089 ----- 1090 This function does not change any behavior since this is a tracked module. 1091 """ 1092 1093 if GPA.pc.get_verbose(): 1094 print(f"{self.name} calling set mode {mode}") 1095 return True 1096 1097 def forward(self, *args, **kwargs): 1098 """Forward pass for tracked module. 1099 1100 Parameters 1101 ---------- 1102 *args : tuple 1103 Positional arguments for the forward pass. 1104 **kwargs : dict 1105 Keyword arguments for the forward pass. 1106 1107 Returns 1108 ------- 1109 Any 1110 The output of the module 1111 1112 Notes 1113 ----- 1114 The output of this forward function will have the same format as the output 1115 of the original module 1116 """ 1117 return self.main_module(*args, **kwargs) 1118 1119 def __str__(self): 1120 """String representation of the module. 1121 1122 Parameters 1123 ---------- 1124 None 1125 1126 Returns 1127 ------- 1128 str 1129 String representation of the module. 1130 1131 Notes 1132 ----- 1133 Setting for verbose changes level of details in the string output. 1134 """ 1135 1136 if GPA.pc.get_verbose(): 1137 total_string = self.main_module.__str__() 1138 total_string = "PAITrackedModule(" + total_string + ")" 1139 return total_string 1140 else: 1141 total_string = self.main_module.__str__() 1142 total_string = "PAITrackedModule(" + total_string + ")" 1143 return total_string 1144 1145 def __repr__(self): 1146 """Representation of the module.""" 1147 return self.__str__() 1148 1149 1150def init_params(module, neuron_main_module): 1151 """Randomize weights after duplicating the main module for the next set of dendrites. 1152 1153 Parameters 1154 ---------- 1155 module : nn.Module 1156 The new dendrite module to initialize. 1157 neuron_main_module : nn.Module 1158 The main module of the neuron for potential weight scaling. 1159 1160 1161 Returns 1162 ------- 1163 None 1164 This function does not return a value. 1165 """ 1166 for param in module.parameters(): 1167 if param.dtype == torch.uint8: 1168 param.data = torch.randint(0, 256, param.size(), dtype=torch.uint8) 1169 else: 1170 # If factoring in the main modules weights multiply the randn() 1171 # by the average abs value of the main modules weights 1172 if GPA.pc.get_candidate_weight_init_by_main(): 1173 main_module_abs = 0 1174 total_main_params = 0 1175 for main_param in neuron_main_module.parameters(): 1176 main_module_abs += main_param.abs().sum().item() 1177 total_main_params += main_param.numel() 1178 if total_main_params > 0: 1179 main_module_abs /= total_main_params 1180 else: 1181 main_module_abs = 1.0 1182 multiplier = main_module_abs 1183 else: 1184 multiplier = 1.0 1185 param.data = ( 1186 torch.randn(param.size(), dtype=param.dtype) 1187 * GPA.pc.get_candidate_weight_initialization_multiplier() 1188 * multiplier 1189 ) 1190 1191 1192class PAIDendriteModule(nn.Module): 1193 """Module containing all dendrites modules added to the neuron module.""" 1194 1195 def __init__( 1196 self, 1197 initial_module, 1198 activation_function_value=0.3, 1199 name="no_name_given", 1200 output_dimensions=None, 1201 ): 1202 """Initialize PAINeuronModule. 1203 1204 This function sets up the dendrite module to create candidate and permanent 1205 dendrite modules based on the initial_module provided. 1206 1207 Parameters 1208 ---------- 1209 initial_module : nn.Module 1210 The module to copy. 1211 activation_function_value : float, optional 1212 A value associated with the activation function, by default 0.3. 1213 name : str 1214 The name of the neuron module. 1215 output_dimensions : vector, optional 1216 The dimensions of the input vector 1217 """ 1218 super(PAIDendriteModule, self).__init__() 1219 1220 if output_dimensions is None: 1221 output_dimensions = [] 1222 1223 self.layers = nn.ModuleList([]) 1224 self.processors = [] 1225 self.candidate_processors = [] 1226 self.num_dendrites = 0 1227 self._create_dendrite_fn = None 1228 # Number of dendrite cycles performed 1229 self.register_buffer( 1230 "num_cycles", 1231 torch.zeros(1, device=GPA.pc.get_device(), dtype=GPA.pc.get_d_type()), 1232 ) 1233 self.mode = "n" 1234 self.name = name 1235 # Create a copy of the parent module so you don't have a pointer to the real one which causes save errors 1236 self.parent_module = UPA.deep_copy_pai(initial_module) 1237 self.parent_module.requires_grad_(False) 1238 set_parameter_type(self.parent_module, "ignored") 1239 # Setup the input dimensions and node index for combining dendrite outputs 1240 if GPA.pc.get_perforated_backpropagation(): 1241 MPB.create_extra_tensors(self) 1242 device = next((p.device for p in initial_module.parameters()), None) 1243 if output_dimensions == []: 1244 self.register_buffer( 1245 "this_output_dimensions", torch.tensor(GPA.pc.get_output_dimensions(), device=device) 1246 ) 1247 else: 1248 self.register_buffer( 1249 "this_output_dimensions", output_dimensions.detach().clone() 1250 ) 1251 if (self.this_output_dimensions == GPA.NODE_AXIS).sum() != 1: 1252 print(f"1 need exactly one 0 in the input dimensions: {self.name}") 1253 print(self.this_output_dimensions) 1254 sys.exit(-1) 1255 self.register_buffer( 1256 "this_node_index", 1257 torch.tensor( 1258 GPA.pc.get_output_dimensions().index(GPA.NODE_AXIS), device=device 1259 ), 1260 ) 1261 1262 # Initialize dendrite to dendrite connections 1263 self.dendrites_to_candidates = nn.ParameterList() 1264 self.dendrites_to_dendrites = nn.ParameterList() 1265 1266 # Store an activation function value if required 1267 self.activation_function_value = activation_function_value 1268 self.dendrite_values = nn.ModuleList([]) 1269 for j in range(0, GPA.pc.get_global_candidates()): 1270 if GPA.pc.get_verbose(): 1271 print(f"creating dendrite Values for {self.name}") 1272 self.dendrite_values.append( 1273 DendriteValueTracker( 1274 False, 1275 self.activation_function_value, 1276 self.name, 1277 self.this_output_dimensions, 1278 ) 1279 ) 1280 if GPA.pc.get_perforated_backpropagation(): 1281 self.dendrite_loss = self.set_dendrite_loss_class() 1282 self.apply_pb_grads = MPB.apply_pb_grads.__get__(self, type(self)) 1283 self.apply_pb_zero = MPB.apply_pb_zero.__get__(self, type(self)) 1284 1285 def set_dendrite_loss_class(self) -> 'DendriteLoss': 1286 # TODO currently every PAIDendriteModule has the same loss class, should instead have more customizability 1287 loss_class = MPB.get_global_dendrite_loss_class() 1288 return loss_class() 1289 1290 def __getstate__(self): 1291 """Tell pickle what to save when this object is serialized (e.g. torch.save). 1292 1293 apply_pb_grads and apply_pb_zero are bound methods of functions defined 1294 in modules_pbp and cannot be pickled. Strip them out; __setstate__ will 1295 re-attach them after loading. 1296 """ 1297 import types 1298 1299 pickle_safe_state = {} 1300 for attr_name, attr_value in self.__dict__.items(): 1301 if not isinstance(attr_value, types.MethodType): 1302 pickle_safe_state[attr_name] = attr_value 1303 1304 return pickle_safe_state 1305 1306 def __setstate__(self, saved_state): 1307 """Restore this object from a pickled state (e.g. torch.load). 1308 1309 Restores all normal attributes, then re-attaches apply_pb_grads and 1310 apply_pb_zero if perforated backpropagation is enabled. 1311 """ 1312 self.__dict__.update(saved_state) 1313 1314 # Re-attach the PBP bound methods that were stripped by __getstate__. 1315 # dendrite_loss being present on the saved state means PBP was active 1316 # when the checkpoint was saved. 1317 if "dendrite_loss" in saved_state: 1318 import perforatedbp.modules_pbp as MPB 1319 self.apply_pb_grads = MPB.apply_pb_grads.__get__(self, type(self)) 1320 self.apply_pb_zero = MPB.apply_pb_zero.__get__(self, type(self)) 1321 1322 def create_dendrite(self, parent_module): 1323 """Create a dendrite module from the parent module. 1324 1325 Override this function via set_create_dendrite to control how the dendrite 1326 module is created (e.g. to avoid a deep copy). 1327 1328 Parameters 1329 ---------- 1330 parent_module : nn.Module 1331 The module to create a dendrite from. 1332 1333 Returns 1334 ------- 1335 nn.Module 1336 The new dendrite module. 1337 """ 1338 if self._create_dendrite_fn is not None: 1339 return self._create_dendrite_fn(parent_module) 1340 return UPA.deep_copy_pai(parent_module) 1341 1342 def set_create_dendrite(self, fn): 1343 """Set a custom function for creating dendrite modules. 1344 1345 Call this on a PAIDendriteModule instance to override how dendrites are 1346 created from the parent module. The function receives the parent module 1347 and must return a new nn.Module. 1348 1349 Parameters 1350 ---------- 1351 fn : callable 1352 A function with signature ``fn(parent_module) -> nn.Module``. 1353 1354 Returns 1355 ------- 1356 None 1357 """ 1358 self._create_dendrite_fn = fn 1359 1360 1361 def set_this_output_dimensions(self, new_output_dimensions): 1362 """Set input dimensions for dendrite module. 1363 1364 Signals to this DendriteModule that its input dimensions are different 1365 than the global default. 1366 1367 Parameters 1368 ---------- 1369 new_output_dimensions : list 1370 A list or tensor specifying the new input dimensions. 1371 Returns 1372 ------- 1373 None 1374 1375 """ 1376 1377 if type(new_output_dimensions) is list: 1378 new_output_dimensions = torch.tensor(new_output_dimensions) 1379 device = self.this_output_dimensions.device 1380 delattr(self, "this_output_dimensions") 1381 self.register_buffer( 1382 "this_output_dimensions", new_output_dimensions.detach().clone().to(device) 1383 ) 1384 if (new_output_dimensions == GPA.NODE_AXIS).sum() != 1: 1385 print(f"2 Need exactly one 0 in the input dimensions: {self.name}") 1386 print(new_output_dimensions) 1387 sys.exit(-1) 1388 self.this_node_index.copy_( 1389 (new_output_dimensions == GPA.NODE_AXIS).nonzero(as_tuple=True)[0][0] 1390 ) 1391 for j in range(0, GPA.pc.get_global_candidates()): 1392 self.dendrite_values[j].set_this_output_dimensions(new_output_dimensions) 1393 1394 def create_new_dendrite_module(self, neuron_main_module): 1395 """Add a new set of dendrites. 1396 1397 Parameters 1398 ---------- 1399 neuron_main_module : Any 1400 PyTorch module to be used for dendritic learning. 1401 Typically a copy of the original neuron module. 1402 1403 Returns 1404 ------- 1405 None 1406 This function does not return a value. 1407 """ 1408 # Candidate module 1409 self.candidate_module = nn.ModuleList([]) 1410 # Copy that is unused for open source version 1411 self.best_candidate_module = nn.ModuleList([]) 1412 if GPA.pc.get_verbose(): 1413 print(self.name) 1414 print("Setting candidate processors") 1415 self.candidate_processors = [] 1416 with torch.no_grad(): 1417 for i in range(0, GPA.pc.get_global_candidates()): 1418 1419 new_module = self.create_dendrite(self.parent_module) 1420 new_module.requires_grad_(True) 1421 init_params(new_module, neuron_main_module) 1422 self.candidate_module.append(new_module) 1423 best = self.create_dendrite(new_module) 1424 best.requires_grad_(False) 1425 self.best_candidate_module.append(best) 1426 if type(self.parent_module) in GPA.pc.get_modules_with_processing(): 1427 module_index = GPA.pc.get_modules_with_processing().index( 1428 type(self.parent_module) 1429 ) 1430 self.candidate_processors.append( 1431 GPA.pc.get_modules_processing_classes()[module_index]() 1432 ) 1433 elif ( 1434 type(self.parent_module).__name__ 1435 in GPA.pc.get_module_names_with_processing() 1436 ): 1437 module_index = GPA.pc.get_module_names_with_processing().index( 1438 type(self.parent_module).__name__ 1439 ) 1440 self.candidate_processors.append( 1441 GPA.pc.get_module_by_name_processing_classes()[module_index]() 1442 ) 1443 set_parameter_type(self.candidate_module[i], "candidate") 1444 set_parameter_type(self.best_candidate_module[i], "ignored") 1445 1446 for i in range(0, GPA.pc.get_global_candidates()): 1447 self.candidate_module[i].to(GPA.pc.get_device()) 1448 self.best_candidate_module[i].to(GPA.pc.get_device()) 1449 1450 # Reset the dendrite_values objects 1451 for j in range(0, GPA.pc.get_global_candidates()): 1452 self.dendrite_values[j].reinitialize_for_pai() 1453 1454 # If there are already dendrites initialize the dendrite to dendrite connections 1455 if self.num_dendrites > 0: 1456 self.dendrites_to_candidates = nn.ParameterList() 1457 for j in range(0, GPA.pc.get_global_candidates()): 1458 self.dendrites_to_candidates.append( 1459 nn.Parameter( 1460 torch.zeros( 1461 (self.num_dendrites, self.out_channels), 1462 device=GPA.pc.get_device(), 1463 dtype=GPA.pc.get_d_type(), 1464 ), 1465 requires_grad=True, 1466 ) 1467 ) 1468 if GPA.pc.get_perforated_backpropagation(): 1469 MPB.init_candidates(self, j) 1470 set_parameter_type(self.dendrites_to_candidates, "candidate") 1471 # Initialize best_dendrites_to_candidates_saved to snapshot peak-correlation weights at epoch boundaries 1472 self.best_dendrites_to_candidates_saved = [] 1473 for j in range(0, GPA.pc.get_global_candidates()): 1474 self.best_dendrites_to_candidates_saved.append( 1475 torch.zeros( 1476 (self.num_dendrites, self.out_channels), 1477 device=GPA.pc.get_device(), 1478 dtype=GPA.pc.get_d_type(), 1479 ) 1480 ) 1481 1482 def clear_processors(self): 1483 """Clear processors. 1484 1485 Parameters 1486 ---------- 1487 None 1488 1489 Returns 1490 ------- 1491 None 1492 This function does not return a value. 1493 """ 1494 for processor in self.processors: 1495 if not processor: 1496 continue 1497 else: 1498 processor.clear_processor() 1499 for processor in self.candidate_processors: 1500 if not processor: 1501 continue 1502 else: 1503 processor.clear_processor() 1504 1505 def set_mode(self, mode): 1506 """Perform actions when switching between neuron and dendrite training. 1507 1508 Parameters 1509 ---------- 1510 mode : str 1511 The mode to set. Either "n" for neuron training or "p" for pai-dendrite training. 1512 1513 Returns 1514 ------- 1515 None 1516 """ 1517 1518 self.mode = mode 1519 self.num_cycles += 1 1520 if GPA.pc.get_verbose(): 1521 print(f"Module {self.name} calling set mode {mode} : {self.num_cycles}") 1522 # When switching back to neuron training mode convert candidates modules into accepted modules 1523 if mode == "n": 1524 if GPA.pc.get_verbose(): 1525 print("So calling all the things to add to modules") 1526 # Copy weights/bias from correct candidates 1527 if self.num_dendrites == 1: 1528 self.dendrites_to_dendrites = nn.ParameterList() 1529 self.dendrites_to_dendrites.append(torch.tensor([])) 1530 if self.num_dendrites >= 1: 1531 self.dendrites_to_dendrites.append( 1532 torch.nn.Parameter( 1533 torch.zeros( 1534 [self.num_dendrites, self.out_channels], 1535 device=GPA.pc.get_device(), 1536 dtype=GPA.pc.get_d_type(), 1537 ), 1538 # Grad is true if not pb or if pb and dendrite_update_mode is true 1539 requires_grad=(not GPA.pc.get_perforated_backpropagation()) 1540 or GPA.pc.get_dendrite_update_mode(), 1541 ) 1542 ) 1543 with torch.no_grad(): 1544 if GPA.pc.get_global_candidates() > 1: 1545 print( 1546 "This was a flag that will be needed if using multiple candidates. " 1547 "It's not set up yet but nice work finding it." 1548 ) 1549 print( 1550 "Note: with multiple candidates, best-score ranking in new_best() uses " 1551 "unnormalized covariance (prev_dendrite_candidate_correlation) rather than " 1552 "the normalized correlation coefficient. Candidates with larger output " 1553 "magnitude will be favored regardless of true correlation quality. " 1554 "Fix by tracking running sigma_V and sigma_E and dividing in new_best()." 1555 ) 1556 pdb.set_trace() 1557 plane_max_index = 0 1558 self.layers.append( 1559 UPA.deep_copy_pai(self.best_candidate_module[plane_max_index]) 1560 ) 1561 self.layers[self.num_dendrites].to(GPA.pc.get_device()) 1562 # Set explicitly: best_candidate_module's requires_grad differs between a live 1563 # switch (deepcopy of a trainable candidate) and a checkpoint reload (frozen). 1564 self.layers[self.num_dendrites].requires_grad_( 1565 (not GPA.pc.get_perforated_backpropagation()) 1566 or GPA.pc.get_dendrite_update_mode() 1567 ) 1568 if self.num_dendrites > 0: 1569 self.dendrites_to_dendrites[self.num_dendrites].copy_( 1570 self.best_dendrites_to_candidates_saved[plane_max_index] 1571 ) 1572 if type(self.parent_module) in GPA.pc.get_modules_with_processing(): 1573 self.processors.append(self.candidate_processors[plane_max_index]) 1574 if ( 1575 type(self.parent_module).__name__ 1576 in GPA.pc.get_module_names_with_processing() 1577 ): 1578 self.processors.append(self.candidate_processors[plane_max_index]) 1579 if GPA.pc.get_perforated_backpropagation(): 1580 MPB.set_pb_mode(self, mode) 1581 del self.candidate_module, self.best_candidate_module 1582 1583 self.num_dendrites += 1 1584 set_parameter_type(self.dendrites_to_dendrites, "dendrite") 1585 set_parameter_type(self.layers, "dendrite") 1586 1587 def forward(self, *args, **kwargs): 1588 """Forward pass for dendrite module. 1589 1590 Parameters 1591 ---------- 1592 *args : tuple 1593 Positional arguments for the forward pass. 1594 **kwargs : dict 1595 Keyword arguments for the forward pass. 1596 1597 Returns 1598 ------- 1599 Any 1600 The output of the module after processing through the neuron and dendrite modules. 1601 Any 1602 Remaining outputs are only used for Perforated Backpropagation. 1603 Any 1604 Remaining outputs are only used for Perforated Backpropagation. 1605 Any 1606 Remaining outputs are only used for Perforated Backpropagation. 1607 1608 Notes 1609 ----- 1610 If using Perforated Backpropagation, the additional outputs will be moved around in 1611 this code but left unused and only passed into separate PB functions. 1612 """ 1613 1614 outs = {} 1615 1616 # For all modules apply processors, call the modules, then apply post processors 1617 args2, kwargs2 = args, kwargs 1618 for c in range(0, self.num_dendrites): 1619 if GPA.pc.get_perforated_backpropagation(): 1620 args2, kwargs2 = MPB.preprocess_pb(*args, **kwargs) 1621 if self.processors != []: 1622 try: 1623 args2, kwargs2 = self.processors[c].pre_d(*args2, **kwargs2) 1624 except Exception as e: 1625 traceback.print_exc(limit=None, chain=True) 1626 print(f"Your pre_d processor for {self.name} caused this error") 1627 print( 1628 f"You must check how this is defined and ensure that it is properly" 1629 ) 1630 print( 1631 f"accepting inputs to the PAIModule and returning what will then be" 1632 ) 1633 print(f"the input to the dendrite module") 1634 sys.exit() 1635 out_values = self.layers[c](*args2, **kwargs2) 1636 if self.processors != []: 1637 try: 1638 outs[c] = self.processors[c].post_d(out_values) 1639 except Exception as e: 1640 traceback.print_exc(limit=None, chain=True) 1641 print(f"Your post_d processor for {self.name} caused this error") 1642 print( 1643 f"You must check how this is defined and ensure that it is properly" 1644 ) 1645 print( 1646 f"accepting outputs from the dendrite module and returning the" 1647 ) 1648 print( 1649 f"single tensor to be combined with the neurons output tensor" 1650 ) 1651 sys.exit() 1652 else: 1653 outs[c] = out_values 1654 1655 # Create dendrite outputs 1656 # Each dendrite has input from previously created dendrites 1657 # So activation is added before the nonlinearity is called 1658 view_tuple = [] 1659 for out_index in range(0, self.num_dendrites): 1660 current_out = outs[out_index] 1661 view_tuple = [] 1662 for dim in range(len(current_out.shape)): 1663 if dim == self.this_node_index: 1664 view_tuple.append(-1) 1665 continue 1666 view_tuple.append(1) 1667 1668 for in_index in range(0, out_index): 1669 if view_tuple == [ 1670 1 1671 ]: # This is only the case when passing a single datapoint rather than a batch 1672 current_out = ( 1673 current_out 1674 + self.dendrites_to_dendrites[out_index][in_index, :].to( 1675 current_out.device 1676 ) 1677 * outs[in_index] 1678 ) 1679 else: 1680 current_out = ( 1681 current_out 1682 + self.dendrites_to_dendrites[out_index][in_index, :] 1683 .view(view_tuple) 1684 .to(current_out.device) 1685 * outs[in_index] 1686 ) 1687 outs[out_index] = GPA.pc.get_pai_forward_function()(current_out) 1688 # Return a dict which has all dendritic outputs after the activation functions were called 1689 if GPA.pc.get_perforated_backpropagation(): 1690 candidate_outs, candidate_nonlinear_outs, candidate_non_zeroed = ( 1691 MPB.forward_candidates(self, view_tuple, outs, *args2, **kwargs2) 1692 ) 1693 else: 1694 candidate_outs, candidate_nonlinear_outs, candidate_non_zeroed = ( 1695 {}, 1696 {}, 1697 {}, 1698 ) 1699 return outs, candidate_outs, candidate_nonlinear_outs, candidate_non_zeroed 1700 1701 1702class DendriteValueTracker(nn.Module): 1703 """Tracker object that maintains certain values for each set of dendrites.""" 1704 1705 def __init__( 1706 self, 1707 initialized, 1708 activation_function_value, 1709 name, 1710 output_dimensions, 1711 out_channels=-1, 1712 ): 1713 """Initialize DendriteValueTracker. 1714 1715 This function sets up the value tracker to maintain statistics and values 1716 for each set of dendrites. 1717 1718 Parameters 1719 ---------- 1720 initialized : int 1721 Whether the dendrite has been initialized (1) or not (0). 1722 activation_function_value : float 1723 A value associated with the activation function. 1724 name : str 1725 The name of the associated neuron module. 1726 output_dimensions : vector 1727 The dimensions of the input vector. 1728 out_channels : int 1729 The number of output channels 1730 """ 1731 super(DendriteValueTracker, self).__init__() 1732 1733 self.layer_name = name 1734 for val_name in DENDRITE_INIT_VALUES: 1735 self.register_buffer( 1736 val_name, 1737 torch.zeros(1, device=GPA.pc.get_device(), dtype=GPA.pc.get_d_type()), 1738 ) 1739 self.initialized[0] = initialized 1740 self.activation_function_value = activation_function_value 1741 self.register_buffer( 1742 "this_output_dimensions", output_dimensions.clone().detach() 1743 ) 1744 if (self.this_output_dimensions == GPA.NODE_AXIS).sum() != 1: 1745 print(f"3 need exactly one 0 in the input dimensions: {self.layer_name}") 1746 print(self.this_output_dimensions) 1747 sys.exit(-1) 1748 self.register_buffer( 1749 "this_node_index", 1750 (output_dimensions == GPA.NODE_AXIS).nonzero(as_tuple=True)[0], 1751 ) 1752 if out_channels != -1: 1753 ndim = len(output_dimensions) 1754 init_shape = [1] * ndim 1755 init_shape[(output_dimensions == GPA.NODE_AXIS).nonzero(as_tuple=True)[0].item()] = out_channels 1756 self.setup_arrays(init_shape) 1757 else: 1758 self.out_channels = -1 1759 1760 def print(self): 1761 """Print value tracker information. 1762 1763 Parameters 1764 ---------- 1765 None 1766 1767 Returns 1768 ------- 1769 None 1770 This function does not return a value. 1771 """ 1772 total_string = "Value Tracker:" 1773 for val_name in DENDRITE_INIT_VALUES: 1774 total_string += f"\t{val_name}:\n\t\t" 1775 total_string += getattr(self, val_name).__repr__() 1776 total_string += "\n" 1777 for val_name in get_DENDRITE_TENSOR_VALUES(): 1778 if getattr(self, val_name, None) is not None: 1779 total_string += f"\t{val_name}:\n\t\t" 1780 total_string += getattr(self, val_name).__repr__() 1781 total_string += "\n" 1782 print(total_string) 1783 1784 def set_this_output_dimensions(self, new_output_dimensions): 1785 """Set input dimensions for value tracker 1786 1787 Signals to this DendriteValueTracker that its input dimensions are different 1788 than the global default. 1789 1790 Parameters 1791 ---------- 1792 new_output_dimensions : list 1793 A list or tensor specifying the new input dimensions. 1794 Returns 1795 ------- 1796 None 1797 1798 """ 1799 if type(new_output_dimensions) is list: 1800 new_output_dimensions = torch.tensor(new_output_dimensions) 1801 device = self.this_output_dimensions.device 1802 delattr(self, "this_output_dimensions") 1803 self.register_buffer( 1804 "this_output_dimensions", new_output_dimensions.detach().clone().to(device) 1805 ) 1806 if (new_output_dimensions == GPA.NODE_AXIS).sum() != 1: 1807 print(f"4 need exactly one 0 in the input dimensions: {self.layer_name}") 1808 print(new_output_dimensions) 1809 sys.exit(-1) 1810 self.this_node_index.copy_( 1811 (new_output_dimensions == GPA.NODE_AXIS).nonzero(as_tuple=True)[0][0] 1812 ) 1813 1814 def set_out_channels(self, shape_values): 1815 """Set output channels based on shape values and saved node index 1816 1817 Parameters 1818 ---------- 1819 shape_values : list or torch.Size 1820 A list or tensor specifying the shape values. 1821 1822 Returns 1823 ------- 1824 None 1825 """ 1826 # DESIGN ASSUMPTION (spatially resolved covariance): each target layer is 1827 # assumed to emit a fixed H x W on every batch. The spatially resolved 1828 # covariance buffers (shape N x H x W) are sized once, from the H and W read 1829 # off this same shape_values at setup time, and are never resized afterward. 1830 # A layer whose spatial size varies across batches would therefore fail to 1831 # broadcast against these fixed-size buffers; supporting variable spatial 1832 # sizes would require a mismatch policy here and in setup_arrays. 1833 if type(shape_values) == torch.Size: 1834 self.out_channels = int(shape_values[self.this_node_index]) 1835 else: 1836 self.out_channels = int(shape_values[self.this_node_index].item()) 1837 1838 def setup_arrays(self, storage_shape): 1839 """Setup arrays for value tracker. 1840 1841 Parameters 1842 ---------- 1843 storage_shape : list 1844 Shape for the tracking tensors: 1 at every dim except the channel 1845 dim (this_node_index), which holds out_channels. E.g. [1, 5] for 1846 a linear layer with 5 outputs. 1847 Returns 1848 ------- 1849 None 1850 1851 """ 1852 # storage_shape is a list with 1 at every dim except the channel dim. 1853 # Passed in directly from filter_backward so it is always derived from 1854 # the live gradient — not from out_channels, which is not saved/loaded. 1855 self.out_channels = storage_shape[self.this_node_index.item()] 1856 self.register_buffer( 1857 "dendrite_storage_shape", 1858 torch.tensor(storage_shape, dtype=torch.long, device=GPA.pc.get_device()), 1859 ) 1860 for val_name in get_DENDRITE_TENSOR_VALUES(): 1861 self.register_buffer( 1862 val_name, 1863 torch.zeros( 1864 storage_shape, device=GPA.pc.get_device(), dtype=GPA.pc.get_d_type() 1865 ), 1866 ) 1867 1868 for name in get_VALUE_TRACKER_ARRAYS(): 1869 setattr(self, name, {}) 1870 count = 1 1871 if torch.cuda.device_count() > count: 1872 count = torch.cuda.device_count() 1873 for i in range(count): 1874 getattr(self, name)[i] = [] 1875 for val_name in get_DENDRITE_SINGLE_VALUES(): 1876 self.register_buffer( 1877 val_name, 1878 torch.zeros(1, device=GPA.pc.get_device(), dtype=GPA.pc.get_d_type()), 1879 ) 1880 1881 def reinitialize_for_pai(self): 1882 """Reinitialize value tracker to add the next set of dendrites 1883 1884 Parameters 1885 ---------- 1886 None 1887 1888 Returns 1889 ------- 1890 None 1891 This function does not return a value. 1892 """ 1893 1894 if self.out_channels == -1: 1895 print("You have a perforated module that was never initialized") 1896 print("This likely means it is not being added to the autograd graph") 1897 print("Check your forward function that it is actually being used") 1898 print("If its not you should really delete it, but you can also add") 1899 print(self.layer_name) 1900 print("with:") 1901 print("GPA.pc.append_module_ids_to_track(['" + self.layer_name + "'])") 1902 print("This can also happen while testing_dendrite_capacity if you") 1903 print( 1904 "run a validation cycle and try to add Dendrites before doing any training.\n" 1905 ) 1906 pdb.set_trace() 1907 1908 self.initialized[0] = 0 1909 if GPA.pc.get_perforated_backpropagation(): 1910 MPB.reinitialize_for_pb(self) 1911 else: 1912 for val_name in get_DENDRITE_REINIT_VALUES(): 1913 setattr(self, val_name, getattr(self, val_name) * 0)
46def set_parameter_type(module, parameter_type): 47 """Set the parameter_type of all parameters of a module. 48 49 Parameters 50 ---------- 51 module : nn.Module 52 Module whose parameters to tag, including all its submodules. 53 parameter_type : str 54 One of "neuron", "tree", "dendrite", "candidate" or "ignored". 55 56 Returns 57 ------- 58 None 59 """ 60 for param in module.parameters(): 61 param.parameter_type = parameter_type
Set the parameter_type of all parameters of a module.
Parameters
- module (nn.Module): Module whose parameters to tag, including all its submodules.
- parameter_type (str): One of "neuron", "tree", "dendrite", "candidate" or "ignored".
Returns
- None
64def set_main_parameters(module): 65 """Set the parameters registered directly on a module, not on its submodules, to "neuron". 66 67 Parameters 68 ---------- 69 module : nn.Module 70 Module whose own parameters to tag. 71 72 Returns 73 ------- 74 None 75 """ 76 for param in module.parameters(recurse=False): 77 param.parameter_type = "neuron"
Set the parameters registered directly on a module, not on its submodules, to "neuron".
Parameters
- module (nn.Module): Module whose own parameters to tag.
Returns
- None
80def is_dendrite_parameter(param): 81 """Return whether a parameter belongs to a dendrite ("dendrite" or "tree" parameter_type). 82 83 Parameters 84 ---------- 85 param : torch.Tensor 86 The parameter to check. 87 88 Returns 89 ------- 90 bool 91 True for dendrite weights and dendrite output weights. 92 """ 93 return getattr(param, "parameter_type", None) in DENDRITE_PARAMETER_TYPES
Return whether a parameter belongs to a dendrite ("dendrite" or "tree" parameter_type).
Parameters
- param (torch.Tensor): The parameter to check.
Returns
- bool: True for dendrite weights and dendrite output weights.
120def get_DENDRITE_TENSOR_VALUES(): 121 """Get DENDRITE_TENSOR_VALUES, updating from MPB if perforated_backpropagation is enabled. 122 123 Parameters 124 ---------- 125 None 126 127 Returns 128 ------- 129 list[str] 130 Names of tensor attributes used for dendrite state handling. 131 """ 132 global _cached_dendrite_tensor_values, _cached_dendrite_tensor_pb_state, _cached_dendrite_tensor_loss_class 133 current_pb_state = GPA.pc.get_perforated_backpropagation() 134 # The loss class is only relevant, and only readable, when PB is enabled. Read it 135 # through the accessor (single-writer invariant); it is a class object, so the guard 136 # compares it by identity below. 137 current_loss_class = MPB.get_global_dendrite_loss_class() if current_pb_state else None 138 139 if ( 140 _cached_dendrite_tensor_values is None 141 or _cached_dendrite_tensor_pb_state != current_pb_state 142 or _cached_dendrite_tensor_loss_class is not current_loss_class 143 ): 144 _cached_dendrite_tensor_pb_state = current_pb_state 145 _cached_dendrite_tensor_loss_class = current_loss_class 146 if current_pb_state: 147 _cached_dendrite_tensor_values = MPB.update_dendrite_tensor_values( 148 _DENDRITE_TENSOR_VALUES_BASE.copy() 149 ) 150 else: 151 _cached_dendrite_tensor_values = _DENDRITE_TENSOR_VALUES_BASE.copy() 152 153 return _cached_dendrite_tensor_values
Get DENDRITE_TENSOR_VALUES, updating from MPB if perforated_backpropagation is enabled.
Parameters
- None
Returns
- list[str]: Names of tensor attributes used for dendrite state handling.
156def get_DENDRITE_SINGLE_VALUES(): 157 """Get DENDRITE_SINGLE_VALUES, updating from MPB if perforated_backpropagation is enabled. 158 159 Parameters 160 ---------- 161 None 162 163 Returns 164 ------- 165 list[str] 166 Names of scalar attributes used for dendrite state handling. 167 """ 168 global _cached_dendrite_single_values, _cached_dendrite_single_pb_state, _cached_dendrite_single_loss_class 169 current_pb_state = GPA.pc.get_perforated_backpropagation() 170 # The loss class is only relevant, and only readable, when PB is enabled. Read it 171 # through the accessor (single-writer invariant); it is a class object, so the guard 172 # compares it by identity below. 173 current_loss_class = MPB.get_global_dendrite_loss_class() if current_pb_state else None 174 175 if ( 176 _cached_dendrite_single_values is None 177 or _cached_dendrite_single_pb_state != current_pb_state 178 or _cached_dendrite_single_loss_class is not current_loss_class 179 ): 180 _cached_dendrite_single_pb_state = current_pb_state 181 _cached_dendrite_single_loss_class = current_loss_class 182 if current_pb_state: 183 _cached_dendrite_single_values = MPB.update_dendrite_single_values( 184 _DENDRITE_SINGLE_VALUES_BASE.copy() 185 ) 186 else: 187 _cached_dendrite_single_values = _DENDRITE_SINGLE_VALUES_BASE.copy() 188 189 return _cached_dendrite_single_values
Get DENDRITE_SINGLE_VALUES, updating from MPB if perforated_backpropagation is enabled.
Parameters
- None
Returns
- list[str]: Names of scalar attributes used for dendrite state handling.
192def get_VALUE_TRACKER_ARRAYS(): 193 """Get VALUE_TRACKER_ARRAYS, updating from MPB if perforated_backpropagation is enabled. 194 195 Parameters 196 ---------- 197 None 198 199 Returns 200 ------- 201 list[str] 202 Names of array-valued fields tracked in ``DendriteValueTracker``. 203 """ 204 global _cached_value_tracker_arrays, _cached_value_tracker_pb_state 205 current_pb_state = GPA.pc.get_perforated_backpropagation() 206 207 if ( 208 _cached_value_tracker_arrays is None 209 or _cached_value_tracker_pb_state != current_pb_state 210 ): 211 _cached_value_tracker_pb_state = current_pb_state 212 if current_pb_state: 213 _cached_value_tracker_arrays = MPB.update_value_tracker_arrays( 214 _VALUE_TRACKER_ARRAYS_BASE.copy() 215 ) 216 else: 217 _cached_value_tracker_arrays = _VALUE_TRACKER_ARRAYS_BASE.copy() 218 219 return _cached_value_tracker_arrays
Get VALUE_TRACKER_ARRAYS, updating from MPB if perforated_backpropagation is enabled.
Parameters
- None
Returns
- list[str]: Names of array-valued fields tracked in
DendriteValueTracker.
222def get_DENDRITE_REINIT_VALUES(): 223 """Get DENDRITE_REINIT_VALUES. 224 225 Parameters 226 ---------- 227 None 228 229 Returns 230 ------- 231 list[str] 232 Combined list of attribute names that must be reinitialized. 233 """ 234 return get_DENDRITE_TENSOR_VALUES() + get_DENDRITE_SINGLE_VALUES()
Get DENDRITE_REINIT_VALUES.
Parameters
- None
Returns
- list[str]: Combined list of attribute names that must be reinitialized.
237def get_DENDRITE_SAVE_VALUES(): 238 """Get DENDRITE_SAVE_VALUES. 239 240 Parameters 241 ---------- 242 None 243 244 Returns 245 ------- 246 list[str] 247 Combined list of attribute names persisted for save/load. 248 """ 249 return ( 250 get_DENDRITE_TENSOR_VALUES() 251 + get_DENDRITE_SINGLE_VALUES() 252 + DENDRITE_INIT_VALUES 253 )
Get DENDRITE_SAVE_VALUES.
Parameters
- None
Returns
- list[str]: Combined list of attribute names persisted for save/load.
256def filter_backward(grad_out, values, module=None): 257 """Filter backward pass for gradient processing. 258 259 This function processes gradients during the backward pass, 260 ensuring correct input dimensions,and applying perforated backpropagation if enabled. 261 262 Parameters 263 ---------- 264 grad_out : torch.Tensor 265 The gradient output tensor from the backward pass. 266 values : DendriteValueTracker 267 A DendriteValueTracker instance containing values associated with the module being processed. 268 module : PAINeuronModule, optional 269 The owning PAINeuronModule instance. When provided and PBP is disabled, 270 the hook deregisters itself after the one-time initialization completes, 271 eliminating per-batch Python overhead on all subsequent backward passes. 272 273 Returns 274 ------- 275 None 276 """ 277 if GPA.pc.get_extra_verbose(): 278 print(f"{values[0].layer_name} calling backward") 279 280 with torch.no_grad(): 281 val = grad_out.detach() 282 # Fast path: Python bool set after first backward in this process. 283 # Fallback: current_d_init is a saved buffer — survives checkpoint reload 284 # even when _fb_init_done resets to False in a fresh process. 285 already_init = (module is not None and module._fb_init_done) or \ 286 values[0].current_d_init.item() 287 if not already_init: 288 # If input dimensions and gradient don't have same shape trigger error and quit 289 if len(values[0].this_output_dimensions) != len(grad_out.shape): 290 print( 291 "The following module has not properly set this_output_dimensions" 292 ) 293 print(values[0].layer_name) 294 print("it is expecting:") 295 print(values[0].this_output_dimensions) 296 print("but received") 297 print(grad_out.shape) 298 print( 299 "to check these all at once set GPA.pc.set_debugging_output_dimensions(1)" 300 ) 301 print( 302 f"Call MODEL_VARIABLE{values[0].layer_name}.set_this_output_dimensions([...]) on this module after perforate_model" 303 ) 304 print( 305 "where the ... is replaced with the correct vector as described in section 4 of customization.md" 306 ) 307 if not GPA.pc.get_debugging_output_dimensions(): 308 sys.exit(0) 309 else: 310 GPA.pc.set_debugging_output_dimensions(2) 311 return 312 # Make sure that the input dimensions are correct 313 for i in range(len(values[0].this_output_dimensions)): 314 if values[0].this_output_dimensions[i] == GPA.NODE_AXIS: 315 continue 316 # Make sure all input dimensions are either REDUCE_AXIS (reduce), 317 # NOT_REDUCE_OR_NODE_AXIS (retain), or exact values (old format) 318 if ( 319 not (grad_out.shape[i] == values[0].this_output_dimensions[i]) 320 and not values[0].this_output_dimensions[i] == GPA.REDUCE_AXIS 321 and not values[0].this_output_dimensions[i] == GPA.NOT_REDUCE_OR_NODE_AXIS 322 ): 323 print( 324 "The following module has not properly set this_output_dimensions with this incorrect shape" 325 ) 326 print(values[0].layer_name) 327 print("it is expecting:") 328 print(values[0].this_output_dimensions) 329 print("but received") 330 print(grad_out.shape) 331 print( 332 "to check these all at once set GPA.pc.set_debugging_output_dimensions(1)" 333 ) 334 if not GPA.pc.get_debugging_output_dimensions(): 335 sys.exit(0) 336 else: 337 GPA.pc.set_debugging_output_dimensions(2) 338 return 339 # Setup the arrays with the now known shape 340 with torch.no_grad(): 341 if GPA.pc.get_verbose(): 342 print("setting d shape for") 343 print(values[0].layer_name) 344 print(val.size()) 345 346 values[0].set_out_channels(val.size()) 347 ndim = len(values[0].this_output_dimensions) 348 storage_shape = [1] * ndim 349 for _i in range(ndim): 350 if values[0].this_output_dimensions[_i] == GPA.NOT_REDUCE_OR_NODE_AXIS: 351 storage_shape[_i] = val.shape[_i] 352 storage_shape[values[0].this_node_index.item()] = values[0].out_channels 353 values[0].setup_arrays(storage_shape) 354 # Flag that it has been setup (both the GPU tensor and the fast Python bool) 355 values[0].current_d_init[0] = 1 356 if module is not None: 357 module._fb_init_done = True 358 # When PBP is disabled this hook has no further work to do. 359 # Deregister it so it never fires again, eliminating per-batch 360 # Python overhead on all subsequent backward passes. 361 if not GPA.pc.get_perforated_backpropagation() and module._fb_hook_handle is not None: 362 module._fb_hook_handle.remove() 363 module._fb_hook_handle = None 364 if GPA.pc.get_perforated_backpropagation(): 365 MPB.filter_backward_pb(val, values)
Filter backward pass for gradient processing.
This function processes gradients during the backward pass, ensuring correct input dimensions,and applying perforated backpropagation if enabled.
Parameters
- grad_out (torch.Tensor): The gradient output tensor from the backward pass.
- values (DendriteValueTracker): A DendriteValueTracker instance containing values associated with the module being processed.
- module (PAINeuronModule, optional): The owning PAINeuronModule instance. When provided and PBP is disabled, the hook deregisters itself after the one-time initialization completes, eliminating per-batch Python overhead on all subsequent backward passes.
Returns
- None
368def set_wrapped_params(model): 369 """Set parameters as wrapped with dendrites. 370 371 Parameters 372 ---------- 373 model : torch.nn.Module 374 The model whose parameters are to be marked as wrapped. 375 376 Returns 377 ------- 378 None 379 380 """ 381 for param in model.parameters(): 382 param.wrapped = True
Set parameters as wrapped with dendrites.
Parameters
- model (torch.nn.Module): The model whose parameters are to be marked as wrapped.
Returns
- None
385def set_tracked_params(model): 386 """Set parameters as tracked without dendrites. 387 388 Parameters 389 ---------- 390 model : torch.nn.Module 391 The model whose parameters are to be marked as tracked. 392 393 Returns 394 ------- 395 None 396 """ 397 for param in model.parameters(): 398 param.tracked = True
Set parameters as tracked without dendrites.
Parameters
- model (torch.nn.Module): The model whose parameters are to be marked as tracked.
Returns
- None
401class PAINeuronModule(nn.Module): 402 """Wrapper to set a module as one that will have dendritic copies.""" 403 404 def __init__(self, start_module, name): 405 """Initialize PAINeuronModule. 406 407 This function sets up the neuron module to wrap the start_module 408 and manage its dendritic connections. 409 410 Parameters 411 ---------- 412 start_module : nn.Module 413 The module to wrap. 414 name : str 415 The name of the neuron module. 416 """ 417 super(PAINeuronModule, self).__init__() 418 419 if isinstance(start_module, nn.Module): 420 self.main_module = start_module 421 else: 422 print("start_module must be nn.Module: %s" % name) 423 print(type(start_module)) 424 print(start_module) 425 sys.exit(-1) 426 self.name = name 427 # Per-module config: loads custom settings from {save_name}_config.json if present. 428 # Passes both the instance name (id) and the module type so load_config can 429 # fall back to type-level settings when no name-specific entry exists. 430 _module_type_name = type(start_module).__name__ 431 self.module_config = GPA.PAIConfig( 432 module_name=self.name, module_type=_module_type_name 433 ) 434 435 set_wrapped_params(self.main_module) 436 if self.module_config.get_verbose(): 437 print( 438 f"initing a module {self.name} with main type {type(self.main_module)}" 439 ) 440 print(start_module) 441 442 # If this main_module is one that requires processing set the processor 443 if type(self.main_module) in self.module_config.get_modules_with_processing(): 444 module_index = self.module_config.get_modules_with_processing().index( 445 type(self.main_module) 446 ) 447 self.processor = self.module_config.get_modules_processing_classes()[ 448 module_index 449 ]() 450 if self.module_config.get_verbose(): 451 print("with processor") 452 print(self.processor) 453 elif ( 454 type(self.main_module).__name__ 455 in self.module_config.get_module_names_with_processing() 456 ): 457 module_index = self.module_config.get_module_names_with_processing().index( 458 type(self.main_module).__name__ 459 ) 460 self.processor = self.module_config.get_module_by_name_processing_classes()[ 461 module_index 462 ]() 463 if self.module_config.get_verbose(): 464 print("with processor") 465 print(self.processor) 466 else: 467 self.processor = None 468 469 # Field that can be filled in if your activation function requires a parameter 470 self.activation_function_value = -1 471 self.type = "neuron_module" 472 473 # On the wrapped layer's device: DDP's forward_sync_buffers broadcasts every 474 # buffer when wrapping, and NCCL can't send CPU tensors 475 device = next((p.device for p in self.main_module.parameters()), None) 476 self.register_buffer( 477 "this_output_dimensions", 478 (torch.tensor(self.module_config.get_output_dimensions(), device=device)), 479 ) 480 if (self.this_output_dimensions == GPA.NODE_AXIS).sum() != 1: 481 print(f"5 Need exactly one 0 in the input dimensions: {self.name}") 482 print(self.this_output_dimensions) 483 sys.exit(-1) 484 self.register_buffer( 485 "this_node_index", 486 torch.tensor( 487 self.module_config.get_output_dimensions().index(GPA.NODE_AXIS), 488 device=device, 489 ), 490 ) 491 self.dendrite_modules_added = 0 492 493 # Values for dendrite to neuron weights 494 self.dendrites_to_top = nn.ParameterList() 495 self.register_parameter("newest_dendrite_to_top", None) 496 self.candidate_to_top = nn.ParameterList() 497 self.register_parameter("current_candidate_to_top", None) 498 # Create the dendrite module 499 self.dendrite_module = PAIDendriteModule( 500 self.main_module, 501 activation_function_value=self.activation_function_value, 502 name=self.name, 503 output_dimensions=self.this_output_dimensions, 504 ) 505 # If it is linear and default has convolutional dimensions, automatically set to just be batch size and neuron indexes 506 if ( 507 issubclass(type(start_module), nn.Linear) 508 or ( 509 issubclass(type(start_module), GPA.PAISequential) 510 and issubclass(type(start_module.model[0]), nn.Linear) 511 ) 512 ) and ( 513 self.this_output_dimensions[2:] != GPA.NODE_AXIS 514 ).all(): # Everything past 2 is not the node axis 515 self.set_this_output_dimensions(self.this_output_dimensions[0:2]) 516 if ( 517 issubclass(type(start_module), nn.Conv1d) 518 or ( 519 issubclass(type(start_module), GPA.PAISequential) 520 and issubclass(type(start_module.model[0]), nn.Conv1d) 521 ) 522 ) and ( 523 self.this_output_dimensions[3:] != GPA.NODE_AXIS 524 ).all(): # Everything past 3 is not the node axis 525 self.set_this_output_dimensions(self.this_output_dimensions[0:3]) 526 # Apply per-module output_dimensions override from config if present 527 _custom_dims = self.module_config.__dict__.get("_output_dimensions") 528 if _custom_dims is not None: 529 self.set_this_output_dimensions(torch.tensor(_custom_dims)) 530 GPA.pai_tracker.add_pai_neuron_module(self) 531 set_parameter_type(self.main_module, "neuron") 532 533 # Track filter_backward initialization state as a 534 # plain Python bool (avoids a GPU .item() sync on every backward pass). 535 # _fb_hook_handle stores the registered hook handle so it can be 536 # removed after initialization completes when PBP is disabled. 537 self._fb_init_done = False 538 self._fb_hook_handle = None 539 540 def __getattr__(self, name): 541 """Get member variables from the main module. 542 543 Parameters 544 ---------- 545 name : str 546 The name of the variable to retrieve. 547 Returns 548 ------- 549 The requested variable. 550 551 Notes 552 ----- 553 This method first attempts to retrieve the attribute from the PAINeuronModule instance. 554 If it fails, it tries to get the attribute from the wrapped main_module. 555 This allows seamless access to the main module's attributes without modifying original code. 556 """ 557 try: 558 return super().__getattr__(name) 559 except AttributeError: 560 return getattr(self.main_module, name) 561 562 def __getitem__(self, index): 563 """Support indexing operations on the main module. 564 565 Parameters 566 ---------- 567 index : int or slice 568 The index or slice to retrieve. 569 570 Returns 571 ------- 572 The indexed item from the main module. 573 """ 574 return self.main_module[index] 575 576 def apply_pb_grads(self): 577 """Apply perforated backpropagation gradients if enabled. 578 579 Parameters 580 ---------- 581 None 582 583 Returns 584 ------- 585 None 586 This function does not return a value. 587 """ 588 self.dendrite_module.apply_pb_grads() 589 590 def apply_pb_zero(self): 591 """Clear leftover saved tensors if there are any. 592 593 Parameters 594 ---------- 595 None 596 597 Returns 598 ------- 599 None 600 This function does not return a value. 601 """ 602 self.dendrite_module.apply_pb_zero() 603 604 def clear_processors(self): 605 """Clear processors if they save values for DeepCopy and save. 606 607 Parameters 608 ---------- 609 None 610 611 Returns 612 ------- 613 None 614 """ 615 616 if not self.processor: 617 return 618 else: 619 self.processor.clear_processor() 620 self.dendrite_module.clear_processors() 621 622 def clear_dendrites(self): 623 """Clear and reset dendrites before loading from a state dict. 624 625 Parameters 626 ---------- 627 None 628 629 Returns 630 ------- 631 None 632 633 """ 634 # Loading a saved state reconstructs PAIDendriteModule before simulating 635 # its saved cycles. Preserve a registered variant factory so candidate 636 # creation does not silently fall back to deep-copying the parent module. 637 create_dendrite_fn = self.dendrite_module._create_dendrite_fn 638 self.dendrite_modules_added = 0 639 self.dendrites_to_top = nn.ParameterList() 640 self.candidate_to_top = nn.ParameterList() 641 self.dendrite_module = PAIDendriteModule( 642 self.main_module, 643 activation_function_value=self.activation_function_value, 644 name=self.name, 645 output_dimensions=self.this_output_dimensions, 646 ) 647 if create_dendrite_fn is not None: 648 self.dendrite_module.set_create_dendrite(create_dendrite_fn) 649 650 def __str__(self): 651 """String representation of the module. 652 653 Parameters 654 ---------- 655 None 656 657 Returns 658 ------- 659 str 660 String representation of the module. 661 662 Notes 663 ----- 664 Setting for verbose changes level of details in the string output. 665 """ 666 # If verbose print the whole module otherwise just print the module type as a PAIModule 667 if self.module_config.get_verbose(): 668 total_string = self.main_module.__str__() 669 total_string = "PAIModule(" + total_string + ")" 670 return total_string + self.dendrite_module.__str__() 671 else: 672 total_string = self.main_module.__str__() 673 total_string = "PAIModule(" + total_string + ")" 674 return total_string 675 676 def __repr__(self): 677 """Representation of the module.""" 678 return self.__str__() 679 680 def set_this_output_dimensions(self, new_output_dimensions): 681 """Set the input dimensions for the neuron and dendrite blocks. 682 683 Signals to this NeuronModule that its input dimensions are different 684 than the global default. 685 686 Parameters 687 ---------- 688 new_output_dimensions : list 689 A list or tensor specifying the new input dimensions. 690 Returns 691 ------- 692 None 693 694 """ 695 if type(new_output_dimensions) is list: 696 new_output_dimensions = torch.tensor(new_output_dimensions) 697 device = self.this_output_dimensions.device 698 delattr(self, "this_output_dimensions") 699 self.register_buffer( 700 "this_output_dimensions", new_output_dimensions.detach().clone().to(device) 701 ) 702 if (new_output_dimensions == GPA.NODE_AXIS).sum() != 1: 703 print(f"6 need exactly one 0 in the input dimensions: {self.name}") 704 print(new_output_dimensions) 705 self.this_node_index.copy_( 706 (new_output_dimensions == GPA.NODE_AXIS).nonzero(as_tuple=True)[0][0] 707 ) 708 self.dendrite_module.set_this_output_dimensions(new_output_dimensions) 709 710 def set_create_dendrite(self, fn): 711 """Set a custom function for creating dendrite modules. 712 713 Override how dendrite copies are created from the parent module. By default 714 the parent module is deep-copied. Pass any callable with the signature 715 ``fn(parent_module) -> nn.Module`` to replace that behaviour. 716 717 Parameters 718 ---------- 719 fn : callable 720 A function with signature ``fn(parent_module) -> nn.Module``. 721 722 Returns 723 ------- 724 None 725 """ 726 self.dendrite_module.set_create_dendrite(fn) 727 728 729 def set_mode(self, mode): 730 """Switch between neuron training and dendrite training. 731 732 Parameters 733 ---------- 734 mode : str 735 The mode to set. Either "n" for neuron training or "p" for pai-dendrite training. 736 737 Returns 738 ------- 739 bool 740 True if mode was set successfully, False otherwise. 741 742 Notes 743 ----- 744 If False is returned, the mode was not changed due to an error. 745 This is a problem that should not be ignored, but it can be ignored 746 by calling PGA.pc.set_checked_skipped_modules(True) 747 """ 748 749 if self.module_config.get_verbose(): 750 print(f"{self.name} calling set mode {mode}") 751 # If returning to neuron training 752 if mode == "n": 753 self.dendrite_module.set_mode(mode) 754 # Initialize the dendrite to neuron connections 755 if self.dendrite_modules_added > 0: 756 if self.module_config.get_learn_dendrites_live(): 757 values = torch.cat( 758 ( 759 self.dendrites_to_top[self.dendrite_modules_added - 1], 760 nn.Parameter( 761 self.candidate_to_top.detach() 762 .clone() 763 .to(dtype=self.module_config.get_d_type()) 764 ), 765 ), 766 0, 767 ) 768 else: 769 values = torch.cat( 770 ( 771 self.dendrites_to_top[self.dendrite_modules_added - 1], 772 nn.Parameter( 773 torch.zeros( 774 (1, self.out_channels), 775 device=self.dendrites_to_top[ 776 self.dendrite_modules_added - 1 777 ].device, 778 dtype=self.module_config.get_d_type(), 779 ) 780 ), 781 ), 782 0, 783 ) 784 # Freeze the previous dendrites_to_top entry 785 # so the optimizer no longer updates stale entries. Only the 786 # most recently appended entry is ever used in the forward pass. 787 if len(self.dendrites_to_top) > 0: 788 self.dendrites_to_top[-1].requires_grad_(False) 789 self.dendrites_to_top.append( 790 nn.Parameter( 791 values.detach() 792 .clone() 793 .to( 794 device=self.module_config.get_device(), 795 dtype=self.module_config.get_d_type(), 796 ), 797 requires_grad=True, 798 ) 799 ) 800 else: 801 if self.module_config.get_learn_dendrites_live(): 802 # Freeze previous entry before appending new one. 803 if len(self.dendrites_to_top) > 0: 804 self.dendrites_to_top[-1].requires_grad_(False) 805 self.dendrites_to_top.append( 806 nn.Parameter( 807 self.candidate_to_top.detach() 808 .clone() 809 .to(dtype=self.module_config.get_d_type()), 810 requires_grad=True, 811 ) 812 ) 813 else: 814 # Freeze previous entry before appending new one. 815 if len(self.dendrites_to_top) > 0: 816 self.dendrites_to_top[-1].requires_grad_(False) 817 self.dendrites_to_top.append( 818 nn.Parameter( 819 torch.zeros( 820 (1, self.out_channels), 821 device=self.module_config.get_device(), 822 dtype=self.module_config.get_d_type(), 823 ) 824 .detach() 825 .clone(), 826 requires_grad=True, 827 ) 828 ) 829 self.dendrite_modules_added += 1 830 if self.module_config.get_perforated_backpropagation(): 831 MPB.set_module_n_pb(self) 832 set_parameter_type(self.dendrites_to_top, "tree") 833 834 # If starting dendrite training 835 else: 836 try: 837 # Save the values that were calculated in filter_backward 838 self.out_channels = self.dendrite_module.dendrite_values[0].out_channels 839 self.dendrite_module.out_channels = ( 840 self.dendrite_module.dendrite_values[0].out_channels 841 ) 842 except Exception as e: 843 print(e) 844 print( 845 f"this occurred in module: {self.dendrite_module.dendrite_values[0].layer_name}" 846 ) 847 print( 848 "Module should be added to module_names_to_track so it doesn't have dendrites added" 849 ) 850 print("If you are getting here but out_channels has not been set") 851 print( 852 "A common reason is that this module never had gradients flow through it." 853 ) 854 print("I have seen this happen because:") 855 print("-The weights were frozen (requires_grad = False)") 856 print( 857 "-A model is added but not used so it was converted to a perforated module initialized" 858 ) 859 print( 860 "-A module was converted that doesn't have weights that get modified so backward doesn't flow through it" 861 ) 862 print( 863 "If this is normal behavior set GPA.pc.set_checked_skipped_modules(True) in the main to ignore" 864 ) 865 print( 866 "You can also set right now in this pdb terminal to have this not happen more after checking all modules this cycle." 867 ) 868 if not self.module_config.get_checked_skipped_modules(): 869 pdb.set_trace() 870 return False 871 # Only change mode if it makes it past the above exception 872 self.dendrite_module.set_mode(mode) 873 if self.module_config.get_perforated_backpropagation(): 874 MPB.set_module_p_pb(self) 875 return True 876 877 def create_new_dendrite_module(self): 878 """Add an additional dendrite module. 879 880 Parameters 881 ---------- 882 None 883 884 Returns 885 ------- 886 None 887 """ 888 self.dendrite_module.create_new_dendrite_module(self.main_module) 889 890 def forward(self, *args, **kwargs): 891 """Forward pass through the neuron module. 892 893 Parameters 894 ---------- 895 *args : tuple 896 Positional arguments for the forward pass. 897 **kwargs : dict 898 Keyword arguments for the forward pass. 899 900 Returns 901 ------- 902 Any 903 The output of the module after processing through the neuron and dendrite modules. 904 905 Notes 906 ----- 907 The output of this forward function will have the same format as the output 908 of the original module 909 """ 910 911 # If debugging all input dimensions, quit program on first forward call 912 if self.module_config.get_debugging_output_dimensions() == 2: 913 print("all input dim problems now printed") 914 sys.exit(0) 915 if self.module_config.get_extra_verbose(): 916 print(f"{self.name} calling forward") 917 # Call the main modules forward 918 out = self.main_module(*args, **kwargs) 919 # Filter with the processor if required 920 if self.processor is not None: 921 try: 922 out = self.processor.post_n1(out) 923 except Exception as e: 924 traceback.print_exc(limit=None, chain=True) 925 print(f"Your post_n1 processor for {self.name} caused this error") 926 print( 927 f"You must check how this is defined and ensure that it is properly" 928 ) 929 print(f"accepting outputs from the neuron module and returning the") 930 print(f"single tensor to be combined with the dendrites output tensor") 931 sys.exit() 932 # Call the forwards for all of the Dendrites 933 ( 934 dendrite_outs, 935 candidate_outs, 936 candidate_nonlinear_outs, 937 candidate_outs_non_zeroed, 938 ) = self.dendrite_module(*args, **kwargs) 939 # If there are dendrites add all of their outputs to the neurons output 940 if self.dendrite_modules_added > 0: 941 for i in range(0, self.dendrite_modules_added): 942 to_top = self.dendrites_to_top[self.dendrite_modules_added - 1][i, :] 943 for dim in range(len(dendrite_outs[i].shape)): 944 if dim == self.this_node_index: 945 continue 946 to_top = to_top.unsqueeze(dim) 947 if self.module_config.get_confirm_correct_sizes(): 948 to_top = to_top.expand( 949 list(dendrite_outs[i].size())[0 : self.this_node_index] 950 + [self.out_channels] 951 + list(dendrite_outs[i].size())[self.this_node_index + 1 :] 952 ) 953 out = out + (dendrite_outs[i].to(out.device) * to_top.to(out.device)) 954 955 # If learning live, add the candidate's output to the neuron's output via the live weight 956 if self.module_config.get_perforated_backpropagation(): 957 out = MPB.apply_live_candidate_to_output( 958 self, out, candidate_nonlinear_outs 959 ) 960 961 # Catch if processors are required 962 if type(out) is tuple: 963 print(self) 964 print( 965 f"The output of the above module {self.name} is a tuple when it must be a single tensor" 966 ) 967 print( 968 "This must be fixed to enable the dendrite and neuron output to be combined" 969 ) 970 print( 971 "Look in the API customization.md at section 2.2 regarding processors to fix this." 972 ) 973 pdb.set_trace() 974 975 # Call filter backward to ensure the neuron index is setup correctly. 976 # Register only when not yet initialized (PBP=False) or always when PBP 977 # is enabled. Store the handle so the hook can deregister itself after 978 # the one-time initialization completes (PBP=False path). 979 if out.requires_grad and (not self._fb_init_done or GPA.pc.get_perforated_backpropagation()): 980 self._fb_hook_handle = out.register_hook( 981 lambda grad: filter_backward(grad, self.dendrite_module.dendrite_values, self) 982 ) 983 984 # If there is a processor apply the second neuron stage 985 if self.processor is not None: 986 try: 987 out = self.processor.post_n2(out) 988 except Exception as e: 989 traceback.print_exc(limit=None, chain=True) 990 print(f"Your post_n2 processor for {self.name} caused this error") 991 print( 992 f"You must check how this is defined and ensure that it is properly" 993 ) 994 print( 995 f"accepting the output tensor after combining the neuron's output " 996 ) 997 print(f"with the dendrite's output and returning something that is the") 998 print(f"same format as your original module's return") 999 sys.exit() 1000 return out
Wrapper to set a module as one that will have dendritic copies.
404 def __init__(self, start_module, name): 405 """Initialize PAINeuronModule. 406 407 This function sets up the neuron module to wrap the start_module 408 and manage its dendritic connections. 409 410 Parameters 411 ---------- 412 start_module : nn.Module 413 The module to wrap. 414 name : str 415 The name of the neuron module. 416 """ 417 super(PAINeuronModule, self).__init__() 418 419 if isinstance(start_module, nn.Module): 420 self.main_module = start_module 421 else: 422 print("start_module must be nn.Module: %s" % name) 423 print(type(start_module)) 424 print(start_module) 425 sys.exit(-1) 426 self.name = name 427 # Per-module config: loads custom settings from {save_name}_config.json if present. 428 # Passes both the instance name (id) and the module type so load_config can 429 # fall back to type-level settings when no name-specific entry exists. 430 _module_type_name = type(start_module).__name__ 431 self.module_config = GPA.PAIConfig( 432 module_name=self.name, module_type=_module_type_name 433 ) 434 435 set_wrapped_params(self.main_module) 436 if self.module_config.get_verbose(): 437 print( 438 f"initing a module {self.name} with main type {type(self.main_module)}" 439 ) 440 print(start_module) 441 442 # If this main_module is one that requires processing set the processor 443 if type(self.main_module) in self.module_config.get_modules_with_processing(): 444 module_index = self.module_config.get_modules_with_processing().index( 445 type(self.main_module) 446 ) 447 self.processor = self.module_config.get_modules_processing_classes()[ 448 module_index 449 ]() 450 if self.module_config.get_verbose(): 451 print("with processor") 452 print(self.processor) 453 elif ( 454 type(self.main_module).__name__ 455 in self.module_config.get_module_names_with_processing() 456 ): 457 module_index = self.module_config.get_module_names_with_processing().index( 458 type(self.main_module).__name__ 459 ) 460 self.processor = self.module_config.get_module_by_name_processing_classes()[ 461 module_index 462 ]() 463 if self.module_config.get_verbose(): 464 print("with processor") 465 print(self.processor) 466 else: 467 self.processor = None 468 469 # Field that can be filled in if your activation function requires a parameter 470 self.activation_function_value = -1 471 self.type = "neuron_module" 472 473 # On the wrapped layer's device: DDP's forward_sync_buffers broadcasts every 474 # buffer when wrapping, and NCCL can't send CPU tensors 475 device = next((p.device for p in self.main_module.parameters()), None) 476 self.register_buffer( 477 "this_output_dimensions", 478 (torch.tensor(self.module_config.get_output_dimensions(), device=device)), 479 ) 480 if (self.this_output_dimensions == GPA.NODE_AXIS).sum() != 1: 481 print(f"5 Need exactly one 0 in the input dimensions: {self.name}") 482 print(self.this_output_dimensions) 483 sys.exit(-1) 484 self.register_buffer( 485 "this_node_index", 486 torch.tensor( 487 self.module_config.get_output_dimensions().index(GPA.NODE_AXIS), 488 device=device, 489 ), 490 ) 491 self.dendrite_modules_added = 0 492 493 # Values for dendrite to neuron weights 494 self.dendrites_to_top = nn.ParameterList() 495 self.register_parameter("newest_dendrite_to_top", None) 496 self.candidate_to_top = nn.ParameterList() 497 self.register_parameter("current_candidate_to_top", None) 498 # Create the dendrite module 499 self.dendrite_module = PAIDendriteModule( 500 self.main_module, 501 activation_function_value=self.activation_function_value, 502 name=self.name, 503 output_dimensions=self.this_output_dimensions, 504 ) 505 # If it is linear and default has convolutional dimensions, automatically set to just be batch size and neuron indexes 506 if ( 507 issubclass(type(start_module), nn.Linear) 508 or ( 509 issubclass(type(start_module), GPA.PAISequential) 510 and issubclass(type(start_module.model[0]), nn.Linear) 511 ) 512 ) and ( 513 self.this_output_dimensions[2:] != GPA.NODE_AXIS 514 ).all(): # Everything past 2 is not the node axis 515 self.set_this_output_dimensions(self.this_output_dimensions[0:2]) 516 if ( 517 issubclass(type(start_module), nn.Conv1d) 518 or ( 519 issubclass(type(start_module), GPA.PAISequential) 520 and issubclass(type(start_module.model[0]), nn.Conv1d) 521 ) 522 ) and ( 523 self.this_output_dimensions[3:] != GPA.NODE_AXIS 524 ).all(): # Everything past 3 is not the node axis 525 self.set_this_output_dimensions(self.this_output_dimensions[0:3]) 526 # Apply per-module output_dimensions override from config if present 527 _custom_dims = self.module_config.__dict__.get("_output_dimensions") 528 if _custom_dims is not None: 529 self.set_this_output_dimensions(torch.tensor(_custom_dims)) 530 GPA.pai_tracker.add_pai_neuron_module(self) 531 set_parameter_type(self.main_module, "neuron") 532 533 # Track filter_backward initialization state as a 534 # plain Python bool (avoids a GPU .item() sync on every backward pass). 535 # _fb_hook_handle stores the registered hook handle so it can be 536 # removed after initialization completes when PBP is disabled. 537 self._fb_init_done = False 538 self._fb_hook_handle = None
Initialize PAINeuronModule.
This function sets up the neuron module to wrap the start_module and manage its dendritic connections.
Parameters
- start_module (nn.Module): The module to wrap.
- name (str): The name of the neuron module.
1169 def type(self, dst_type: dtype | str) -> Self: 1170 r"""Casts all parameters and buffers to :attr:`dst_type`. 1171 1172 .. note:: 1173 This method modifies the module in-place. 1174 1175 Args: 1176 dst_type (type or string): the desired type 1177 1178 Returns: 1179 Module: self 1180 """ 1181 return self._apply(lambda t: t.type(dst_type))
Casts all parameters and buffers to dst_type.
This method modifies the module in-place.
Args: dst_type (type or string): the desired type
Returns: Module: self
576 def apply_pb_grads(self): 577 """Apply perforated backpropagation gradients if enabled. 578 579 Parameters 580 ---------- 581 None 582 583 Returns 584 ------- 585 None 586 This function does not return a value. 587 """ 588 self.dendrite_module.apply_pb_grads()
Apply perforated backpropagation gradients if enabled.
Parameters
- None
Returns
- None: This function does not return a value.
590 def apply_pb_zero(self): 591 """Clear leftover saved tensors if there are any. 592 593 Parameters 594 ---------- 595 None 596 597 Returns 598 ------- 599 None 600 This function does not return a value. 601 """ 602 self.dendrite_module.apply_pb_zero()
Clear leftover saved tensors if there are any.
Parameters
- None
Returns
- None: This function does not return a value.
604 def clear_processors(self): 605 """Clear processors if they save values for DeepCopy and save. 606 607 Parameters 608 ---------- 609 None 610 611 Returns 612 ------- 613 None 614 """ 615 616 if not self.processor: 617 return 618 else: 619 self.processor.clear_processor() 620 self.dendrite_module.clear_processors()
Clear processors if they save values for DeepCopy and save.
Parameters
- None
Returns
- None
622 def clear_dendrites(self): 623 """Clear and reset dendrites before loading from a state dict. 624 625 Parameters 626 ---------- 627 None 628 629 Returns 630 ------- 631 None 632 633 """ 634 # Loading a saved state reconstructs PAIDendriteModule before simulating 635 # its saved cycles. Preserve a registered variant factory so candidate 636 # creation does not silently fall back to deep-copying the parent module. 637 create_dendrite_fn = self.dendrite_module._create_dendrite_fn 638 self.dendrite_modules_added = 0 639 self.dendrites_to_top = nn.ParameterList() 640 self.candidate_to_top = nn.ParameterList() 641 self.dendrite_module = PAIDendriteModule( 642 self.main_module, 643 activation_function_value=self.activation_function_value, 644 name=self.name, 645 output_dimensions=self.this_output_dimensions, 646 ) 647 if create_dendrite_fn is not None: 648 self.dendrite_module.set_create_dendrite(create_dendrite_fn)
Clear and reset dendrites before loading from a state dict.
Parameters
- None
Returns
- None
680 def set_this_output_dimensions(self, new_output_dimensions): 681 """Set the input dimensions for the neuron and dendrite blocks. 682 683 Signals to this NeuronModule that its input dimensions are different 684 than the global default. 685 686 Parameters 687 ---------- 688 new_output_dimensions : list 689 A list or tensor specifying the new input dimensions. 690 Returns 691 ------- 692 None 693 694 """ 695 if type(new_output_dimensions) is list: 696 new_output_dimensions = torch.tensor(new_output_dimensions) 697 device = self.this_output_dimensions.device 698 delattr(self, "this_output_dimensions") 699 self.register_buffer( 700 "this_output_dimensions", new_output_dimensions.detach().clone().to(device) 701 ) 702 if (new_output_dimensions == GPA.NODE_AXIS).sum() != 1: 703 print(f"6 need exactly one 0 in the input dimensions: {self.name}") 704 print(new_output_dimensions) 705 self.this_node_index.copy_( 706 (new_output_dimensions == GPA.NODE_AXIS).nonzero(as_tuple=True)[0][0] 707 ) 708 self.dendrite_module.set_this_output_dimensions(new_output_dimensions)
Set the input dimensions for the neuron and dendrite blocks.
Signals to this NeuronModule that its input dimensions are different than the global default.
Parameters
- new_output_dimensions (list): A list or tensor specifying the new input dimensions.
Returns
- None
710 def set_create_dendrite(self, fn): 711 """Set a custom function for creating dendrite modules. 712 713 Override how dendrite copies are created from the parent module. By default 714 the parent module is deep-copied. Pass any callable with the signature 715 ``fn(parent_module) -> nn.Module`` to replace that behaviour. 716 717 Parameters 718 ---------- 719 fn : callable 720 A function with signature ``fn(parent_module) -> nn.Module``. 721 722 Returns 723 ------- 724 None 725 """ 726 self.dendrite_module.set_create_dendrite(fn)
Set a custom function for creating dendrite modules.
Override how dendrite copies are created from the parent module. By default
the parent module is deep-copied. Pass any callable with the signature
fn(parent_module) -> nn.Module to replace that behaviour.
Parameters
- fn (callable):
A function with signature
fn(parent_module) -> nn.Module.
Returns
- None
729 def set_mode(self, mode): 730 """Switch between neuron training and dendrite training. 731 732 Parameters 733 ---------- 734 mode : str 735 The mode to set. Either "n" for neuron training or "p" for pai-dendrite training. 736 737 Returns 738 ------- 739 bool 740 True if mode was set successfully, False otherwise. 741 742 Notes 743 ----- 744 If False is returned, the mode was not changed due to an error. 745 This is a problem that should not be ignored, but it can be ignored 746 by calling PGA.pc.set_checked_skipped_modules(True) 747 """ 748 749 if self.module_config.get_verbose(): 750 print(f"{self.name} calling set mode {mode}") 751 # If returning to neuron training 752 if mode == "n": 753 self.dendrite_module.set_mode(mode) 754 # Initialize the dendrite to neuron connections 755 if self.dendrite_modules_added > 0: 756 if self.module_config.get_learn_dendrites_live(): 757 values = torch.cat( 758 ( 759 self.dendrites_to_top[self.dendrite_modules_added - 1], 760 nn.Parameter( 761 self.candidate_to_top.detach() 762 .clone() 763 .to(dtype=self.module_config.get_d_type()) 764 ), 765 ), 766 0, 767 ) 768 else: 769 values = torch.cat( 770 ( 771 self.dendrites_to_top[self.dendrite_modules_added - 1], 772 nn.Parameter( 773 torch.zeros( 774 (1, self.out_channels), 775 device=self.dendrites_to_top[ 776 self.dendrite_modules_added - 1 777 ].device, 778 dtype=self.module_config.get_d_type(), 779 ) 780 ), 781 ), 782 0, 783 ) 784 # Freeze the previous dendrites_to_top entry 785 # so the optimizer no longer updates stale entries. Only the 786 # most recently appended entry is ever used in the forward pass. 787 if len(self.dendrites_to_top) > 0: 788 self.dendrites_to_top[-1].requires_grad_(False) 789 self.dendrites_to_top.append( 790 nn.Parameter( 791 values.detach() 792 .clone() 793 .to( 794 device=self.module_config.get_device(), 795 dtype=self.module_config.get_d_type(), 796 ), 797 requires_grad=True, 798 ) 799 ) 800 else: 801 if self.module_config.get_learn_dendrites_live(): 802 # Freeze previous entry before appending new one. 803 if len(self.dendrites_to_top) > 0: 804 self.dendrites_to_top[-1].requires_grad_(False) 805 self.dendrites_to_top.append( 806 nn.Parameter( 807 self.candidate_to_top.detach() 808 .clone() 809 .to(dtype=self.module_config.get_d_type()), 810 requires_grad=True, 811 ) 812 ) 813 else: 814 # Freeze previous entry before appending new one. 815 if len(self.dendrites_to_top) > 0: 816 self.dendrites_to_top[-1].requires_grad_(False) 817 self.dendrites_to_top.append( 818 nn.Parameter( 819 torch.zeros( 820 (1, self.out_channels), 821 device=self.module_config.get_device(), 822 dtype=self.module_config.get_d_type(), 823 ) 824 .detach() 825 .clone(), 826 requires_grad=True, 827 ) 828 ) 829 self.dendrite_modules_added += 1 830 if self.module_config.get_perforated_backpropagation(): 831 MPB.set_module_n_pb(self) 832 set_parameter_type(self.dendrites_to_top, "tree") 833 834 # If starting dendrite training 835 else: 836 try: 837 # Save the values that were calculated in filter_backward 838 self.out_channels = self.dendrite_module.dendrite_values[0].out_channels 839 self.dendrite_module.out_channels = ( 840 self.dendrite_module.dendrite_values[0].out_channels 841 ) 842 except Exception as e: 843 print(e) 844 print( 845 f"this occurred in module: {self.dendrite_module.dendrite_values[0].layer_name}" 846 ) 847 print( 848 "Module should be added to module_names_to_track so it doesn't have dendrites added" 849 ) 850 print("If you are getting here but out_channels has not been set") 851 print( 852 "A common reason is that this module never had gradients flow through it." 853 ) 854 print("I have seen this happen because:") 855 print("-The weights were frozen (requires_grad = False)") 856 print( 857 "-A model is added but not used so it was converted to a perforated module initialized" 858 ) 859 print( 860 "-A module was converted that doesn't have weights that get modified so backward doesn't flow through it" 861 ) 862 print( 863 "If this is normal behavior set GPA.pc.set_checked_skipped_modules(True) in the main to ignore" 864 ) 865 print( 866 "You can also set right now in this pdb terminal to have this not happen more after checking all modules this cycle." 867 ) 868 if not self.module_config.get_checked_skipped_modules(): 869 pdb.set_trace() 870 return False 871 # Only change mode if it makes it past the above exception 872 self.dendrite_module.set_mode(mode) 873 if self.module_config.get_perforated_backpropagation(): 874 MPB.set_module_p_pb(self) 875 return True
Switch between neuron training and dendrite training.
Parameters
- mode (str): The mode to set. Either "n" for neuron training or "p" for pai-dendrite training.
Returns
- bool: True if mode was set successfully, False otherwise.
Notes
If False is returned, the mode was not changed due to an error. This is a problem that should not be ignored, but it can be ignored by calling PGA.pc.set_checked_skipped_modules(True)
877 def create_new_dendrite_module(self): 878 """Add an additional dendrite module. 879 880 Parameters 881 ---------- 882 None 883 884 Returns 885 ------- 886 None 887 """ 888 self.dendrite_module.create_new_dendrite_module(self.main_module)
Add an additional dendrite module.
Parameters
- None
Returns
- None
890 def forward(self, *args, **kwargs): 891 """Forward pass through the neuron module. 892 893 Parameters 894 ---------- 895 *args : tuple 896 Positional arguments for the forward pass. 897 **kwargs : dict 898 Keyword arguments for the forward pass. 899 900 Returns 901 ------- 902 Any 903 The output of the module after processing through the neuron and dendrite modules. 904 905 Notes 906 ----- 907 The output of this forward function will have the same format as the output 908 of the original module 909 """ 910 911 # If debugging all input dimensions, quit program on first forward call 912 if self.module_config.get_debugging_output_dimensions() == 2: 913 print("all input dim problems now printed") 914 sys.exit(0) 915 if self.module_config.get_extra_verbose(): 916 print(f"{self.name} calling forward") 917 # Call the main modules forward 918 out = self.main_module(*args, **kwargs) 919 # Filter with the processor if required 920 if self.processor is not None: 921 try: 922 out = self.processor.post_n1(out) 923 except Exception as e: 924 traceback.print_exc(limit=None, chain=True) 925 print(f"Your post_n1 processor for {self.name} caused this error") 926 print( 927 f"You must check how this is defined and ensure that it is properly" 928 ) 929 print(f"accepting outputs from the neuron module and returning the") 930 print(f"single tensor to be combined with the dendrites output tensor") 931 sys.exit() 932 # Call the forwards for all of the Dendrites 933 ( 934 dendrite_outs, 935 candidate_outs, 936 candidate_nonlinear_outs, 937 candidate_outs_non_zeroed, 938 ) = self.dendrite_module(*args, **kwargs) 939 # If there are dendrites add all of their outputs to the neurons output 940 if self.dendrite_modules_added > 0: 941 for i in range(0, self.dendrite_modules_added): 942 to_top = self.dendrites_to_top[self.dendrite_modules_added - 1][i, :] 943 for dim in range(len(dendrite_outs[i].shape)): 944 if dim == self.this_node_index: 945 continue 946 to_top = to_top.unsqueeze(dim) 947 if self.module_config.get_confirm_correct_sizes(): 948 to_top = to_top.expand( 949 list(dendrite_outs[i].size())[0 : self.this_node_index] 950 + [self.out_channels] 951 + list(dendrite_outs[i].size())[self.this_node_index + 1 :] 952 ) 953 out = out + (dendrite_outs[i].to(out.device) * to_top.to(out.device)) 954 955 # If learning live, add the candidate's output to the neuron's output via the live weight 956 if self.module_config.get_perforated_backpropagation(): 957 out = MPB.apply_live_candidate_to_output( 958 self, out, candidate_nonlinear_outs 959 ) 960 961 # Catch if processors are required 962 if type(out) is tuple: 963 print(self) 964 print( 965 f"The output of the above module {self.name} is a tuple when it must be a single tensor" 966 ) 967 print( 968 "This must be fixed to enable the dendrite and neuron output to be combined" 969 ) 970 print( 971 "Look in the API customization.md at section 2.2 regarding processors to fix this." 972 ) 973 pdb.set_trace() 974 975 # Call filter backward to ensure the neuron index is setup correctly. 976 # Register only when not yet initialized (PBP=False) or always when PBP 977 # is enabled. Store the handle so the hook can deregister itself after 978 # the one-time initialization completes (PBP=False path). 979 if out.requires_grad and (not self._fb_init_done or GPA.pc.get_perforated_backpropagation()): 980 self._fb_hook_handle = out.register_hook( 981 lambda grad: filter_backward(grad, self.dendrite_module.dendrite_values, self) 982 ) 983 984 # If there is a processor apply the second neuron stage 985 if self.processor is not None: 986 try: 987 out = self.processor.post_n2(out) 988 except Exception as e: 989 traceback.print_exc(limit=None, chain=True) 990 print(f"Your post_n2 processor for {self.name} caused this error") 991 print( 992 f"You must check how this is defined and ensure that it is properly" 993 ) 994 print( 995 f"accepting the output tensor after combining the neuron's output " 996 ) 997 print(f"with the dendrite's output and returning something that is the") 998 print(f"same format as your original module's return") 999 sys.exit() 1000 return out
Forward pass through the neuron module.
Parameters
- *args (tuple): Positional arguments for the forward pass.
- **kwargs (dict): Keyword arguments for the forward pass.
Returns
- Any: The output of the module after processing through the neuron and dendrite modules.
Notes
The output of this forward function will have the same format as the output of the original module
1003class TrackedNeuronModule(nn.Module): 1004 """Wrapper for modules you don't want to add dendrites to. Ensures all modules are accounted for.""" 1005 1006 def __init__(self, start_module, name): 1007 """Initialize TrackedNeuronModule. 1008 1009 This function sets up the tracked neuron module to wrap the start_module 1010 without adding dendrites. 1011 1012 Parameters 1013 ---------- 1014 start_module : nn.Module 1015 The module to wrap. 1016 name : str 1017 The name of the neuron module. 1018 """ 1019 super(TrackedNeuronModule, self).__init__() 1020 1021 if isinstance(start_module, nn.Module): 1022 self.main_module = start_module 1023 else: 1024 print("start_module must be nn.Module: %s" % name) 1025 print(type(start_module)) 1026 print(start_module) 1027 sys.exit(-1) 1028 self.name = name 1029 1030 self.type = "tracked_module" 1031 set_tracked_params(self.main_module) 1032 if GPA.pc.get_verbose(): 1033 print( 1034 f"tracking a module {self.name} with main type {type(self.main_module)}" 1035 ) 1036 print(start_module) 1037 GPA.pai_tracker.add_tracked_neuron_module(self) 1038 set_parameter_type(self.main_module, "neuron") 1039 1040 def __getattr__(self, name): 1041 """Get member variables from the main module. 1042 1043 Parameters 1044 ---------- 1045 name : str 1046 The name of the variable to retrieve. 1047 Returns 1048 ------- 1049 The requested variable. 1050 1051 Notes 1052 ----- 1053 This method first attempts to retrieve the attribute from the PAINeuronModule instance. 1054 If it fails, it tries to get the attribute from the wrapped main_module. 1055 This allows seamless access to the main module's attributes without modifying original code. 1056 """ 1057 try: 1058 return super().__getattr__(name) 1059 except AttributeError: 1060 return getattr(self.main_module, name) 1061 1062 def __getitem__(self, index): 1063 """Support indexing operations on the main module. 1064 1065 Parameters 1066 ---------- 1067 index : int or slice 1068 The index or slice to retrieve. 1069 1070 Returns 1071 ------- 1072 The indexed item from the main module. 1073 """ 1074 return self.main_module[index] 1075 1076 def set_mode(self, mode): 1077 """Set mode for tracked module. 1078 1079 Parameters 1080 ---------- 1081 mode : str 1082 The mode to set. Either "n" for neuron training or "p" for pai-dendrite training. 1083 1084 Returns 1085 ------- 1086 bool 1087 True. 1088 1089 Notes 1090 ----- 1091 This function does not change any behavior since this is a tracked module. 1092 """ 1093 1094 if GPA.pc.get_verbose(): 1095 print(f"{self.name} calling set mode {mode}") 1096 return True 1097 1098 def forward(self, *args, **kwargs): 1099 """Forward pass for tracked module. 1100 1101 Parameters 1102 ---------- 1103 *args : tuple 1104 Positional arguments for the forward pass. 1105 **kwargs : dict 1106 Keyword arguments for the forward pass. 1107 1108 Returns 1109 ------- 1110 Any 1111 The output of the module 1112 1113 Notes 1114 ----- 1115 The output of this forward function will have the same format as the output 1116 of the original module 1117 """ 1118 return self.main_module(*args, **kwargs) 1119 1120 def __str__(self): 1121 """String representation of the module. 1122 1123 Parameters 1124 ---------- 1125 None 1126 1127 Returns 1128 ------- 1129 str 1130 String representation of the module. 1131 1132 Notes 1133 ----- 1134 Setting for verbose changes level of details in the string output. 1135 """ 1136 1137 if GPA.pc.get_verbose(): 1138 total_string = self.main_module.__str__() 1139 total_string = "PAITrackedModule(" + total_string + ")" 1140 return total_string 1141 else: 1142 total_string = self.main_module.__str__() 1143 total_string = "PAITrackedModule(" + total_string + ")" 1144 return total_string 1145 1146 def __repr__(self): 1147 """Representation of the module.""" 1148 return self.__str__()
Wrapper for modules you don't want to add dendrites to. Ensures all modules are accounted for.
1006 def __init__(self, start_module, name): 1007 """Initialize TrackedNeuronModule. 1008 1009 This function sets up the tracked neuron module to wrap the start_module 1010 without adding dendrites. 1011 1012 Parameters 1013 ---------- 1014 start_module : nn.Module 1015 The module to wrap. 1016 name : str 1017 The name of the neuron module. 1018 """ 1019 super(TrackedNeuronModule, self).__init__() 1020 1021 if isinstance(start_module, nn.Module): 1022 self.main_module = start_module 1023 else: 1024 print("start_module must be nn.Module: %s" % name) 1025 print(type(start_module)) 1026 print(start_module) 1027 sys.exit(-1) 1028 self.name = name 1029 1030 self.type = "tracked_module" 1031 set_tracked_params(self.main_module) 1032 if GPA.pc.get_verbose(): 1033 print( 1034 f"tracking a module {self.name} with main type {type(self.main_module)}" 1035 ) 1036 print(start_module) 1037 GPA.pai_tracker.add_tracked_neuron_module(self) 1038 set_parameter_type(self.main_module, "neuron")
Initialize TrackedNeuronModule.
This function sets up the tracked neuron module to wrap the start_module without adding dendrites.
Parameters
- start_module (nn.Module): The module to wrap.
- name (str): The name of the neuron module.
1169 def type(self, dst_type: dtype | str) -> Self: 1170 r"""Casts all parameters and buffers to :attr:`dst_type`. 1171 1172 .. note:: 1173 This method modifies the module in-place. 1174 1175 Args: 1176 dst_type (type or string): the desired type 1177 1178 Returns: 1179 Module: self 1180 """ 1181 return self._apply(lambda t: t.type(dst_type))
Casts all parameters and buffers to dst_type.
This method modifies the module in-place.
Args: dst_type (type or string): the desired type
Returns: Module: self
1076 def set_mode(self, mode): 1077 """Set mode for tracked module. 1078 1079 Parameters 1080 ---------- 1081 mode : str 1082 The mode to set. Either "n" for neuron training or "p" for pai-dendrite training. 1083 1084 Returns 1085 ------- 1086 bool 1087 True. 1088 1089 Notes 1090 ----- 1091 This function does not change any behavior since this is a tracked module. 1092 """ 1093 1094 if GPA.pc.get_verbose(): 1095 print(f"{self.name} calling set mode {mode}") 1096 return True
Set mode for tracked module.
Parameters
- mode (str): The mode to set. Either "n" for neuron training or "p" for pai-dendrite training.
Returns
- bool: True.
Notes
This function does not change any behavior since this is a tracked module.
1098 def forward(self, *args, **kwargs): 1099 """Forward pass for tracked module. 1100 1101 Parameters 1102 ---------- 1103 *args : tuple 1104 Positional arguments for the forward pass. 1105 **kwargs : dict 1106 Keyword arguments for the forward pass. 1107 1108 Returns 1109 ------- 1110 Any 1111 The output of the module 1112 1113 Notes 1114 ----- 1115 The output of this forward function will have the same format as the output 1116 of the original module 1117 """ 1118 return self.main_module(*args, **kwargs)
Forward pass for tracked module.
Parameters
- *args (tuple): Positional arguments for the forward pass.
- **kwargs (dict): Keyword arguments for the forward pass.
Returns
- Any: The output of the module
Notes
The output of this forward function will have the same format as the output of the original module
1151def init_params(module, neuron_main_module): 1152 """Randomize weights after duplicating the main module for the next set of dendrites. 1153 1154 Parameters 1155 ---------- 1156 module : nn.Module 1157 The new dendrite module to initialize. 1158 neuron_main_module : nn.Module 1159 The main module of the neuron for potential weight scaling. 1160 1161 1162 Returns 1163 ------- 1164 None 1165 This function does not return a value. 1166 """ 1167 for param in module.parameters(): 1168 if param.dtype == torch.uint8: 1169 param.data = torch.randint(0, 256, param.size(), dtype=torch.uint8) 1170 else: 1171 # If factoring in the main modules weights multiply the randn() 1172 # by the average abs value of the main modules weights 1173 if GPA.pc.get_candidate_weight_init_by_main(): 1174 main_module_abs = 0 1175 total_main_params = 0 1176 for main_param in neuron_main_module.parameters(): 1177 main_module_abs += main_param.abs().sum().item() 1178 total_main_params += main_param.numel() 1179 if total_main_params > 0: 1180 main_module_abs /= total_main_params 1181 else: 1182 main_module_abs = 1.0 1183 multiplier = main_module_abs 1184 else: 1185 multiplier = 1.0 1186 param.data = ( 1187 torch.randn(param.size(), dtype=param.dtype) 1188 * GPA.pc.get_candidate_weight_initialization_multiplier() 1189 * multiplier 1190 )
Randomize weights after duplicating the main module for the next set of dendrites.
Parameters
- module (nn.Module): The new dendrite module to initialize.
- neuron_main_module (nn.Module): The main module of the neuron for potential weight scaling.
Returns
- None: This function does not return a value.
1193class PAIDendriteModule(nn.Module): 1194 """Module containing all dendrites modules added to the neuron module.""" 1195 1196 def __init__( 1197 self, 1198 initial_module, 1199 activation_function_value=0.3, 1200 name="no_name_given", 1201 output_dimensions=None, 1202 ): 1203 """Initialize PAINeuronModule. 1204 1205 This function sets up the dendrite module to create candidate and permanent 1206 dendrite modules based on the initial_module provided. 1207 1208 Parameters 1209 ---------- 1210 initial_module : nn.Module 1211 The module to copy. 1212 activation_function_value : float, optional 1213 A value associated with the activation function, by default 0.3. 1214 name : str 1215 The name of the neuron module. 1216 output_dimensions : vector, optional 1217 The dimensions of the input vector 1218 """ 1219 super(PAIDendriteModule, self).__init__() 1220 1221 if output_dimensions is None: 1222 output_dimensions = [] 1223 1224 self.layers = nn.ModuleList([]) 1225 self.processors = [] 1226 self.candidate_processors = [] 1227 self.num_dendrites = 0 1228 self._create_dendrite_fn = None 1229 # Number of dendrite cycles performed 1230 self.register_buffer( 1231 "num_cycles", 1232 torch.zeros(1, device=GPA.pc.get_device(), dtype=GPA.pc.get_d_type()), 1233 ) 1234 self.mode = "n" 1235 self.name = name 1236 # Create a copy of the parent module so you don't have a pointer to the real one which causes save errors 1237 self.parent_module = UPA.deep_copy_pai(initial_module) 1238 self.parent_module.requires_grad_(False) 1239 set_parameter_type(self.parent_module, "ignored") 1240 # Setup the input dimensions and node index for combining dendrite outputs 1241 if GPA.pc.get_perforated_backpropagation(): 1242 MPB.create_extra_tensors(self) 1243 device = next((p.device for p in initial_module.parameters()), None) 1244 if output_dimensions == []: 1245 self.register_buffer( 1246 "this_output_dimensions", torch.tensor(GPA.pc.get_output_dimensions(), device=device) 1247 ) 1248 else: 1249 self.register_buffer( 1250 "this_output_dimensions", output_dimensions.detach().clone() 1251 ) 1252 if (self.this_output_dimensions == GPA.NODE_AXIS).sum() != 1: 1253 print(f"1 need exactly one 0 in the input dimensions: {self.name}") 1254 print(self.this_output_dimensions) 1255 sys.exit(-1) 1256 self.register_buffer( 1257 "this_node_index", 1258 torch.tensor( 1259 GPA.pc.get_output_dimensions().index(GPA.NODE_AXIS), device=device 1260 ), 1261 ) 1262 1263 # Initialize dendrite to dendrite connections 1264 self.dendrites_to_candidates = nn.ParameterList() 1265 self.dendrites_to_dendrites = nn.ParameterList() 1266 1267 # Store an activation function value if required 1268 self.activation_function_value = activation_function_value 1269 self.dendrite_values = nn.ModuleList([]) 1270 for j in range(0, GPA.pc.get_global_candidates()): 1271 if GPA.pc.get_verbose(): 1272 print(f"creating dendrite Values for {self.name}") 1273 self.dendrite_values.append( 1274 DendriteValueTracker( 1275 False, 1276 self.activation_function_value, 1277 self.name, 1278 self.this_output_dimensions, 1279 ) 1280 ) 1281 if GPA.pc.get_perforated_backpropagation(): 1282 self.dendrite_loss = self.set_dendrite_loss_class() 1283 self.apply_pb_grads = MPB.apply_pb_grads.__get__(self, type(self)) 1284 self.apply_pb_zero = MPB.apply_pb_zero.__get__(self, type(self)) 1285 1286 def set_dendrite_loss_class(self) -> 'DendriteLoss': 1287 # TODO currently every PAIDendriteModule has the same loss class, should instead have more customizability 1288 loss_class = MPB.get_global_dendrite_loss_class() 1289 return loss_class() 1290 1291 def __getstate__(self): 1292 """Tell pickle what to save when this object is serialized (e.g. torch.save). 1293 1294 apply_pb_grads and apply_pb_zero are bound methods of functions defined 1295 in modules_pbp and cannot be pickled. Strip them out; __setstate__ will 1296 re-attach them after loading. 1297 """ 1298 import types 1299 1300 pickle_safe_state = {} 1301 for attr_name, attr_value in self.__dict__.items(): 1302 if not isinstance(attr_value, types.MethodType): 1303 pickle_safe_state[attr_name] = attr_value 1304 1305 return pickle_safe_state 1306 1307 def __setstate__(self, saved_state): 1308 """Restore this object from a pickled state (e.g. torch.load). 1309 1310 Restores all normal attributes, then re-attaches apply_pb_grads and 1311 apply_pb_zero if perforated backpropagation is enabled. 1312 """ 1313 self.__dict__.update(saved_state) 1314 1315 # Re-attach the PBP bound methods that were stripped by __getstate__. 1316 # dendrite_loss being present on the saved state means PBP was active 1317 # when the checkpoint was saved. 1318 if "dendrite_loss" in saved_state: 1319 import perforatedbp.modules_pbp as MPB 1320 self.apply_pb_grads = MPB.apply_pb_grads.__get__(self, type(self)) 1321 self.apply_pb_zero = MPB.apply_pb_zero.__get__(self, type(self)) 1322 1323 def create_dendrite(self, parent_module): 1324 """Create a dendrite module from the parent module. 1325 1326 Override this function via set_create_dendrite to control how the dendrite 1327 module is created (e.g. to avoid a deep copy). 1328 1329 Parameters 1330 ---------- 1331 parent_module : nn.Module 1332 The module to create a dendrite from. 1333 1334 Returns 1335 ------- 1336 nn.Module 1337 The new dendrite module. 1338 """ 1339 if self._create_dendrite_fn is not None: 1340 return self._create_dendrite_fn(parent_module) 1341 return UPA.deep_copy_pai(parent_module) 1342 1343 def set_create_dendrite(self, fn): 1344 """Set a custom function for creating dendrite modules. 1345 1346 Call this on a PAIDendriteModule instance to override how dendrites are 1347 created from the parent module. The function receives the parent module 1348 and must return a new nn.Module. 1349 1350 Parameters 1351 ---------- 1352 fn : callable 1353 A function with signature ``fn(parent_module) -> nn.Module``. 1354 1355 Returns 1356 ------- 1357 None 1358 """ 1359 self._create_dendrite_fn = fn 1360 1361 1362 def set_this_output_dimensions(self, new_output_dimensions): 1363 """Set input dimensions for dendrite module. 1364 1365 Signals to this DendriteModule that its input dimensions are different 1366 than the global default. 1367 1368 Parameters 1369 ---------- 1370 new_output_dimensions : list 1371 A list or tensor specifying the new input dimensions. 1372 Returns 1373 ------- 1374 None 1375 1376 """ 1377 1378 if type(new_output_dimensions) is list: 1379 new_output_dimensions = torch.tensor(new_output_dimensions) 1380 device = self.this_output_dimensions.device 1381 delattr(self, "this_output_dimensions") 1382 self.register_buffer( 1383 "this_output_dimensions", new_output_dimensions.detach().clone().to(device) 1384 ) 1385 if (new_output_dimensions == GPA.NODE_AXIS).sum() != 1: 1386 print(f"2 Need exactly one 0 in the input dimensions: {self.name}") 1387 print(new_output_dimensions) 1388 sys.exit(-1) 1389 self.this_node_index.copy_( 1390 (new_output_dimensions == GPA.NODE_AXIS).nonzero(as_tuple=True)[0][0] 1391 ) 1392 for j in range(0, GPA.pc.get_global_candidates()): 1393 self.dendrite_values[j].set_this_output_dimensions(new_output_dimensions) 1394 1395 def create_new_dendrite_module(self, neuron_main_module): 1396 """Add a new set of dendrites. 1397 1398 Parameters 1399 ---------- 1400 neuron_main_module : Any 1401 PyTorch module to be used for dendritic learning. 1402 Typically a copy of the original neuron module. 1403 1404 Returns 1405 ------- 1406 None 1407 This function does not return a value. 1408 """ 1409 # Candidate module 1410 self.candidate_module = nn.ModuleList([]) 1411 # Copy that is unused for open source version 1412 self.best_candidate_module = nn.ModuleList([]) 1413 if GPA.pc.get_verbose(): 1414 print(self.name) 1415 print("Setting candidate processors") 1416 self.candidate_processors = [] 1417 with torch.no_grad(): 1418 for i in range(0, GPA.pc.get_global_candidates()): 1419 1420 new_module = self.create_dendrite(self.parent_module) 1421 new_module.requires_grad_(True) 1422 init_params(new_module, neuron_main_module) 1423 self.candidate_module.append(new_module) 1424 best = self.create_dendrite(new_module) 1425 best.requires_grad_(False) 1426 self.best_candidate_module.append(best) 1427 if type(self.parent_module) in GPA.pc.get_modules_with_processing(): 1428 module_index = GPA.pc.get_modules_with_processing().index( 1429 type(self.parent_module) 1430 ) 1431 self.candidate_processors.append( 1432 GPA.pc.get_modules_processing_classes()[module_index]() 1433 ) 1434 elif ( 1435 type(self.parent_module).__name__ 1436 in GPA.pc.get_module_names_with_processing() 1437 ): 1438 module_index = GPA.pc.get_module_names_with_processing().index( 1439 type(self.parent_module).__name__ 1440 ) 1441 self.candidate_processors.append( 1442 GPA.pc.get_module_by_name_processing_classes()[module_index]() 1443 ) 1444 set_parameter_type(self.candidate_module[i], "candidate") 1445 set_parameter_type(self.best_candidate_module[i], "ignored") 1446 1447 for i in range(0, GPA.pc.get_global_candidates()): 1448 self.candidate_module[i].to(GPA.pc.get_device()) 1449 self.best_candidate_module[i].to(GPA.pc.get_device()) 1450 1451 # Reset the dendrite_values objects 1452 for j in range(0, GPA.pc.get_global_candidates()): 1453 self.dendrite_values[j].reinitialize_for_pai() 1454 1455 # If there are already dendrites initialize the dendrite to dendrite connections 1456 if self.num_dendrites > 0: 1457 self.dendrites_to_candidates = nn.ParameterList() 1458 for j in range(0, GPA.pc.get_global_candidates()): 1459 self.dendrites_to_candidates.append( 1460 nn.Parameter( 1461 torch.zeros( 1462 (self.num_dendrites, self.out_channels), 1463 device=GPA.pc.get_device(), 1464 dtype=GPA.pc.get_d_type(), 1465 ), 1466 requires_grad=True, 1467 ) 1468 ) 1469 if GPA.pc.get_perforated_backpropagation(): 1470 MPB.init_candidates(self, j) 1471 set_parameter_type(self.dendrites_to_candidates, "candidate") 1472 # Initialize best_dendrites_to_candidates_saved to snapshot peak-correlation weights at epoch boundaries 1473 self.best_dendrites_to_candidates_saved = [] 1474 for j in range(0, GPA.pc.get_global_candidates()): 1475 self.best_dendrites_to_candidates_saved.append( 1476 torch.zeros( 1477 (self.num_dendrites, self.out_channels), 1478 device=GPA.pc.get_device(), 1479 dtype=GPA.pc.get_d_type(), 1480 ) 1481 ) 1482 1483 def clear_processors(self): 1484 """Clear processors. 1485 1486 Parameters 1487 ---------- 1488 None 1489 1490 Returns 1491 ------- 1492 None 1493 This function does not return a value. 1494 """ 1495 for processor in self.processors: 1496 if not processor: 1497 continue 1498 else: 1499 processor.clear_processor() 1500 for processor in self.candidate_processors: 1501 if not processor: 1502 continue 1503 else: 1504 processor.clear_processor() 1505 1506 def set_mode(self, mode): 1507 """Perform actions when switching between neuron and dendrite training. 1508 1509 Parameters 1510 ---------- 1511 mode : str 1512 The mode to set. Either "n" for neuron training or "p" for pai-dendrite training. 1513 1514 Returns 1515 ------- 1516 None 1517 """ 1518 1519 self.mode = mode 1520 self.num_cycles += 1 1521 if GPA.pc.get_verbose(): 1522 print(f"Module {self.name} calling set mode {mode} : {self.num_cycles}") 1523 # When switching back to neuron training mode convert candidates modules into accepted modules 1524 if mode == "n": 1525 if GPA.pc.get_verbose(): 1526 print("So calling all the things to add to modules") 1527 # Copy weights/bias from correct candidates 1528 if self.num_dendrites == 1: 1529 self.dendrites_to_dendrites = nn.ParameterList() 1530 self.dendrites_to_dendrites.append(torch.tensor([])) 1531 if self.num_dendrites >= 1: 1532 self.dendrites_to_dendrites.append( 1533 torch.nn.Parameter( 1534 torch.zeros( 1535 [self.num_dendrites, self.out_channels], 1536 device=GPA.pc.get_device(), 1537 dtype=GPA.pc.get_d_type(), 1538 ), 1539 # Grad is true if not pb or if pb and dendrite_update_mode is true 1540 requires_grad=(not GPA.pc.get_perforated_backpropagation()) 1541 or GPA.pc.get_dendrite_update_mode(), 1542 ) 1543 ) 1544 with torch.no_grad(): 1545 if GPA.pc.get_global_candidates() > 1: 1546 print( 1547 "This was a flag that will be needed if using multiple candidates. " 1548 "It's not set up yet but nice work finding it." 1549 ) 1550 print( 1551 "Note: with multiple candidates, best-score ranking in new_best() uses " 1552 "unnormalized covariance (prev_dendrite_candidate_correlation) rather than " 1553 "the normalized correlation coefficient. Candidates with larger output " 1554 "magnitude will be favored regardless of true correlation quality. " 1555 "Fix by tracking running sigma_V and sigma_E and dividing in new_best()." 1556 ) 1557 pdb.set_trace() 1558 plane_max_index = 0 1559 self.layers.append( 1560 UPA.deep_copy_pai(self.best_candidate_module[plane_max_index]) 1561 ) 1562 self.layers[self.num_dendrites].to(GPA.pc.get_device()) 1563 # Set explicitly: best_candidate_module's requires_grad differs between a live 1564 # switch (deepcopy of a trainable candidate) and a checkpoint reload (frozen). 1565 self.layers[self.num_dendrites].requires_grad_( 1566 (not GPA.pc.get_perforated_backpropagation()) 1567 or GPA.pc.get_dendrite_update_mode() 1568 ) 1569 if self.num_dendrites > 0: 1570 self.dendrites_to_dendrites[self.num_dendrites].copy_( 1571 self.best_dendrites_to_candidates_saved[plane_max_index] 1572 ) 1573 if type(self.parent_module) in GPA.pc.get_modules_with_processing(): 1574 self.processors.append(self.candidate_processors[plane_max_index]) 1575 if ( 1576 type(self.parent_module).__name__ 1577 in GPA.pc.get_module_names_with_processing() 1578 ): 1579 self.processors.append(self.candidate_processors[plane_max_index]) 1580 if GPA.pc.get_perforated_backpropagation(): 1581 MPB.set_pb_mode(self, mode) 1582 del self.candidate_module, self.best_candidate_module 1583 1584 self.num_dendrites += 1 1585 set_parameter_type(self.dendrites_to_dendrites, "dendrite") 1586 set_parameter_type(self.layers, "dendrite") 1587 1588 def forward(self, *args, **kwargs): 1589 """Forward pass for dendrite module. 1590 1591 Parameters 1592 ---------- 1593 *args : tuple 1594 Positional arguments for the forward pass. 1595 **kwargs : dict 1596 Keyword arguments for the forward pass. 1597 1598 Returns 1599 ------- 1600 Any 1601 The output of the module after processing through the neuron and dendrite modules. 1602 Any 1603 Remaining outputs are only used for Perforated Backpropagation. 1604 Any 1605 Remaining outputs are only used for Perforated Backpropagation. 1606 Any 1607 Remaining outputs are only used for Perforated Backpropagation. 1608 1609 Notes 1610 ----- 1611 If using Perforated Backpropagation, the additional outputs will be moved around in 1612 this code but left unused and only passed into separate PB functions. 1613 """ 1614 1615 outs = {} 1616 1617 # For all modules apply processors, call the modules, then apply post processors 1618 args2, kwargs2 = args, kwargs 1619 for c in range(0, self.num_dendrites): 1620 if GPA.pc.get_perforated_backpropagation(): 1621 args2, kwargs2 = MPB.preprocess_pb(*args, **kwargs) 1622 if self.processors != []: 1623 try: 1624 args2, kwargs2 = self.processors[c].pre_d(*args2, **kwargs2) 1625 except Exception as e: 1626 traceback.print_exc(limit=None, chain=True) 1627 print(f"Your pre_d processor for {self.name} caused this error") 1628 print( 1629 f"You must check how this is defined and ensure that it is properly" 1630 ) 1631 print( 1632 f"accepting inputs to the PAIModule and returning what will then be" 1633 ) 1634 print(f"the input to the dendrite module") 1635 sys.exit() 1636 out_values = self.layers[c](*args2, **kwargs2) 1637 if self.processors != []: 1638 try: 1639 outs[c] = self.processors[c].post_d(out_values) 1640 except Exception as e: 1641 traceback.print_exc(limit=None, chain=True) 1642 print(f"Your post_d processor for {self.name} caused this error") 1643 print( 1644 f"You must check how this is defined and ensure that it is properly" 1645 ) 1646 print( 1647 f"accepting outputs from the dendrite module and returning the" 1648 ) 1649 print( 1650 f"single tensor to be combined with the neurons output tensor" 1651 ) 1652 sys.exit() 1653 else: 1654 outs[c] = out_values 1655 1656 # Create dendrite outputs 1657 # Each dendrite has input from previously created dendrites 1658 # So activation is added before the nonlinearity is called 1659 view_tuple = [] 1660 for out_index in range(0, self.num_dendrites): 1661 current_out = outs[out_index] 1662 view_tuple = [] 1663 for dim in range(len(current_out.shape)): 1664 if dim == self.this_node_index: 1665 view_tuple.append(-1) 1666 continue 1667 view_tuple.append(1) 1668 1669 for in_index in range(0, out_index): 1670 if view_tuple == [ 1671 1 1672 ]: # This is only the case when passing a single datapoint rather than a batch 1673 current_out = ( 1674 current_out 1675 + self.dendrites_to_dendrites[out_index][in_index, :].to( 1676 current_out.device 1677 ) 1678 * outs[in_index] 1679 ) 1680 else: 1681 current_out = ( 1682 current_out 1683 + self.dendrites_to_dendrites[out_index][in_index, :] 1684 .view(view_tuple) 1685 .to(current_out.device) 1686 * outs[in_index] 1687 ) 1688 outs[out_index] = GPA.pc.get_pai_forward_function()(current_out) 1689 # Return a dict which has all dendritic outputs after the activation functions were called 1690 if GPA.pc.get_perforated_backpropagation(): 1691 candidate_outs, candidate_nonlinear_outs, candidate_non_zeroed = ( 1692 MPB.forward_candidates(self, view_tuple, outs, *args2, **kwargs2) 1693 ) 1694 else: 1695 candidate_outs, candidate_nonlinear_outs, candidate_non_zeroed = ( 1696 {}, 1697 {}, 1698 {}, 1699 ) 1700 return outs, candidate_outs, candidate_nonlinear_outs, candidate_non_zeroed
Module containing all dendrites modules added to the neuron module.
1196 def __init__( 1197 self, 1198 initial_module, 1199 activation_function_value=0.3, 1200 name="no_name_given", 1201 output_dimensions=None, 1202 ): 1203 """Initialize PAINeuronModule. 1204 1205 This function sets up the dendrite module to create candidate and permanent 1206 dendrite modules based on the initial_module provided. 1207 1208 Parameters 1209 ---------- 1210 initial_module : nn.Module 1211 The module to copy. 1212 activation_function_value : float, optional 1213 A value associated with the activation function, by default 0.3. 1214 name : str 1215 The name of the neuron module. 1216 output_dimensions : vector, optional 1217 The dimensions of the input vector 1218 """ 1219 super(PAIDendriteModule, self).__init__() 1220 1221 if output_dimensions is None: 1222 output_dimensions = [] 1223 1224 self.layers = nn.ModuleList([]) 1225 self.processors = [] 1226 self.candidate_processors = [] 1227 self.num_dendrites = 0 1228 self._create_dendrite_fn = None 1229 # Number of dendrite cycles performed 1230 self.register_buffer( 1231 "num_cycles", 1232 torch.zeros(1, device=GPA.pc.get_device(), dtype=GPA.pc.get_d_type()), 1233 ) 1234 self.mode = "n" 1235 self.name = name 1236 # Create a copy of the parent module so you don't have a pointer to the real one which causes save errors 1237 self.parent_module = UPA.deep_copy_pai(initial_module) 1238 self.parent_module.requires_grad_(False) 1239 set_parameter_type(self.parent_module, "ignored") 1240 # Setup the input dimensions and node index for combining dendrite outputs 1241 if GPA.pc.get_perforated_backpropagation(): 1242 MPB.create_extra_tensors(self) 1243 device = next((p.device for p in initial_module.parameters()), None) 1244 if output_dimensions == []: 1245 self.register_buffer( 1246 "this_output_dimensions", torch.tensor(GPA.pc.get_output_dimensions(), device=device) 1247 ) 1248 else: 1249 self.register_buffer( 1250 "this_output_dimensions", output_dimensions.detach().clone() 1251 ) 1252 if (self.this_output_dimensions == GPA.NODE_AXIS).sum() != 1: 1253 print(f"1 need exactly one 0 in the input dimensions: {self.name}") 1254 print(self.this_output_dimensions) 1255 sys.exit(-1) 1256 self.register_buffer( 1257 "this_node_index", 1258 torch.tensor( 1259 GPA.pc.get_output_dimensions().index(GPA.NODE_AXIS), device=device 1260 ), 1261 ) 1262 1263 # Initialize dendrite to dendrite connections 1264 self.dendrites_to_candidates = nn.ParameterList() 1265 self.dendrites_to_dendrites = nn.ParameterList() 1266 1267 # Store an activation function value if required 1268 self.activation_function_value = activation_function_value 1269 self.dendrite_values = nn.ModuleList([]) 1270 for j in range(0, GPA.pc.get_global_candidates()): 1271 if GPA.pc.get_verbose(): 1272 print(f"creating dendrite Values for {self.name}") 1273 self.dendrite_values.append( 1274 DendriteValueTracker( 1275 False, 1276 self.activation_function_value, 1277 self.name, 1278 self.this_output_dimensions, 1279 ) 1280 ) 1281 if GPA.pc.get_perforated_backpropagation(): 1282 self.dendrite_loss = self.set_dendrite_loss_class() 1283 self.apply_pb_grads = MPB.apply_pb_grads.__get__(self, type(self)) 1284 self.apply_pb_zero = MPB.apply_pb_zero.__get__(self, type(self))
Initialize PAINeuronModule.
This function sets up the dendrite module to create candidate and permanent dendrite modules based on the initial_module provided.
Parameters
- initial_module (nn.Module): The module to copy.
- activation_function_value (float, optional): A value associated with the activation function, by default 0.3.
- name (str): The name of the neuron module.
- output_dimensions (vector, optional): The dimensions of the input vector
1323 def create_dendrite(self, parent_module): 1324 """Create a dendrite module from the parent module. 1325 1326 Override this function via set_create_dendrite to control how the dendrite 1327 module is created (e.g. to avoid a deep copy). 1328 1329 Parameters 1330 ---------- 1331 parent_module : nn.Module 1332 The module to create a dendrite from. 1333 1334 Returns 1335 ------- 1336 nn.Module 1337 The new dendrite module. 1338 """ 1339 if self._create_dendrite_fn is not None: 1340 return self._create_dendrite_fn(parent_module) 1341 return UPA.deep_copy_pai(parent_module)
Create a dendrite module from the parent module.
Override this function via set_create_dendrite to control how the dendrite module is created (e.g. to avoid a deep copy).
Parameters
- parent_module (nn.Module): The module to create a dendrite from.
Returns
- nn.Module: The new dendrite module.
1343 def set_create_dendrite(self, fn): 1344 """Set a custom function for creating dendrite modules. 1345 1346 Call this on a PAIDendriteModule instance to override how dendrites are 1347 created from the parent module. The function receives the parent module 1348 and must return a new nn.Module. 1349 1350 Parameters 1351 ---------- 1352 fn : callable 1353 A function with signature ``fn(parent_module) -> nn.Module``. 1354 1355 Returns 1356 ------- 1357 None 1358 """ 1359 self._create_dendrite_fn = fn
Set a custom function for creating dendrite modules.
Call this on a PAIDendriteModule instance to override how dendrites are created from the parent module. The function receives the parent module and must return a new nn.Module.
Parameters
- fn (callable):
A function with signature
fn(parent_module) -> nn.Module.
Returns
- None
1362 def set_this_output_dimensions(self, new_output_dimensions): 1363 """Set input dimensions for dendrite module. 1364 1365 Signals to this DendriteModule that its input dimensions are different 1366 than the global default. 1367 1368 Parameters 1369 ---------- 1370 new_output_dimensions : list 1371 A list or tensor specifying the new input dimensions. 1372 Returns 1373 ------- 1374 None 1375 1376 """ 1377 1378 if type(new_output_dimensions) is list: 1379 new_output_dimensions = torch.tensor(new_output_dimensions) 1380 device = self.this_output_dimensions.device 1381 delattr(self, "this_output_dimensions") 1382 self.register_buffer( 1383 "this_output_dimensions", new_output_dimensions.detach().clone().to(device) 1384 ) 1385 if (new_output_dimensions == GPA.NODE_AXIS).sum() != 1: 1386 print(f"2 Need exactly one 0 in the input dimensions: {self.name}") 1387 print(new_output_dimensions) 1388 sys.exit(-1) 1389 self.this_node_index.copy_( 1390 (new_output_dimensions == GPA.NODE_AXIS).nonzero(as_tuple=True)[0][0] 1391 ) 1392 for j in range(0, GPA.pc.get_global_candidates()): 1393 self.dendrite_values[j].set_this_output_dimensions(new_output_dimensions)
Set input dimensions for dendrite module.
Signals to this DendriteModule that its input dimensions are different than the global default.
Parameters
- new_output_dimensions (list): A list or tensor specifying the new input dimensions.
Returns
- None
1395 def create_new_dendrite_module(self, neuron_main_module): 1396 """Add a new set of dendrites. 1397 1398 Parameters 1399 ---------- 1400 neuron_main_module : Any 1401 PyTorch module to be used for dendritic learning. 1402 Typically a copy of the original neuron module. 1403 1404 Returns 1405 ------- 1406 None 1407 This function does not return a value. 1408 """ 1409 # Candidate module 1410 self.candidate_module = nn.ModuleList([]) 1411 # Copy that is unused for open source version 1412 self.best_candidate_module = nn.ModuleList([]) 1413 if GPA.pc.get_verbose(): 1414 print(self.name) 1415 print("Setting candidate processors") 1416 self.candidate_processors = [] 1417 with torch.no_grad(): 1418 for i in range(0, GPA.pc.get_global_candidates()): 1419 1420 new_module = self.create_dendrite(self.parent_module) 1421 new_module.requires_grad_(True) 1422 init_params(new_module, neuron_main_module) 1423 self.candidate_module.append(new_module) 1424 best = self.create_dendrite(new_module) 1425 best.requires_grad_(False) 1426 self.best_candidate_module.append(best) 1427 if type(self.parent_module) in GPA.pc.get_modules_with_processing(): 1428 module_index = GPA.pc.get_modules_with_processing().index( 1429 type(self.parent_module) 1430 ) 1431 self.candidate_processors.append( 1432 GPA.pc.get_modules_processing_classes()[module_index]() 1433 ) 1434 elif ( 1435 type(self.parent_module).__name__ 1436 in GPA.pc.get_module_names_with_processing() 1437 ): 1438 module_index = GPA.pc.get_module_names_with_processing().index( 1439 type(self.parent_module).__name__ 1440 ) 1441 self.candidate_processors.append( 1442 GPA.pc.get_module_by_name_processing_classes()[module_index]() 1443 ) 1444 set_parameter_type(self.candidate_module[i], "candidate") 1445 set_parameter_type(self.best_candidate_module[i], "ignored") 1446 1447 for i in range(0, GPA.pc.get_global_candidates()): 1448 self.candidate_module[i].to(GPA.pc.get_device()) 1449 self.best_candidate_module[i].to(GPA.pc.get_device()) 1450 1451 # Reset the dendrite_values objects 1452 for j in range(0, GPA.pc.get_global_candidates()): 1453 self.dendrite_values[j].reinitialize_for_pai() 1454 1455 # If there are already dendrites initialize the dendrite to dendrite connections 1456 if self.num_dendrites > 0: 1457 self.dendrites_to_candidates = nn.ParameterList() 1458 for j in range(0, GPA.pc.get_global_candidates()): 1459 self.dendrites_to_candidates.append( 1460 nn.Parameter( 1461 torch.zeros( 1462 (self.num_dendrites, self.out_channels), 1463 device=GPA.pc.get_device(), 1464 dtype=GPA.pc.get_d_type(), 1465 ), 1466 requires_grad=True, 1467 ) 1468 ) 1469 if GPA.pc.get_perforated_backpropagation(): 1470 MPB.init_candidates(self, j) 1471 set_parameter_type(self.dendrites_to_candidates, "candidate") 1472 # Initialize best_dendrites_to_candidates_saved to snapshot peak-correlation weights at epoch boundaries 1473 self.best_dendrites_to_candidates_saved = [] 1474 for j in range(0, GPA.pc.get_global_candidates()): 1475 self.best_dendrites_to_candidates_saved.append( 1476 torch.zeros( 1477 (self.num_dendrites, self.out_channels), 1478 device=GPA.pc.get_device(), 1479 dtype=GPA.pc.get_d_type(), 1480 ) 1481 )
Add a new set of dendrites.
Parameters
- neuron_main_module (Any): PyTorch module to be used for dendritic learning. Typically a copy of the original neuron module.
Returns
- None: This function does not return a value.
1483 def clear_processors(self): 1484 """Clear processors. 1485 1486 Parameters 1487 ---------- 1488 None 1489 1490 Returns 1491 ------- 1492 None 1493 This function does not return a value. 1494 """ 1495 for processor in self.processors: 1496 if not processor: 1497 continue 1498 else: 1499 processor.clear_processor() 1500 for processor in self.candidate_processors: 1501 if not processor: 1502 continue 1503 else: 1504 processor.clear_processor()
Clear processors.
Parameters
- None
Returns
- None: This function does not return a value.
1506 def set_mode(self, mode): 1507 """Perform actions when switching between neuron and dendrite training. 1508 1509 Parameters 1510 ---------- 1511 mode : str 1512 The mode to set. Either "n" for neuron training or "p" for pai-dendrite training. 1513 1514 Returns 1515 ------- 1516 None 1517 """ 1518 1519 self.mode = mode 1520 self.num_cycles += 1 1521 if GPA.pc.get_verbose(): 1522 print(f"Module {self.name} calling set mode {mode} : {self.num_cycles}") 1523 # When switching back to neuron training mode convert candidates modules into accepted modules 1524 if mode == "n": 1525 if GPA.pc.get_verbose(): 1526 print("So calling all the things to add to modules") 1527 # Copy weights/bias from correct candidates 1528 if self.num_dendrites == 1: 1529 self.dendrites_to_dendrites = nn.ParameterList() 1530 self.dendrites_to_dendrites.append(torch.tensor([])) 1531 if self.num_dendrites >= 1: 1532 self.dendrites_to_dendrites.append( 1533 torch.nn.Parameter( 1534 torch.zeros( 1535 [self.num_dendrites, self.out_channels], 1536 device=GPA.pc.get_device(), 1537 dtype=GPA.pc.get_d_type(), 1538 ), 1539 # Grad is true if not pb or if pb and dendrite_update_mode is true 1540 requires_grad=(not GPA.pc.get_perforated_backpropagation()) 1541 or GPA.pc.get_dendrite_update_mode(), 1542 ) 1543 ) 1544 with torch.no_grad(): 1545 if GPA.pc.get_global_candidates() > 1: 1546 print( 1547 "This was a flag that will be needed if using multiple candidates. " 1548 "It's not set up yet but nice work finding it." 1549 ) 1550 print( 1551 "Note: with multiple candidates, best-score ranking in new_best() uses " 1552 "unnormalized covariance (prev_dendrite_candidate_correlation) rather than " 1553 "the normalized correlation coefficient. Candidates with larger output " 1554 "magnitude will be favored regardless of true correlation quality. " 1555 "Fix by tracking running sigma_V and sigma_E and dividing in new_best()." 1556 ) 1557 pdb.set_trace() 1558 plane_max_index = 0 1559 self.layers.append( 1560 UPA.deep_copy_pai(self.best_candidate_module[plane_max_index]) 1561 ) 1562 self.layers[self.num_dendrites].to(GPA.pc.get_device()) 1563 # Set explicitly: best_candidate_module's requires_grad differs between a live 1564 # switch (deepcopy of a trainable candidate) and a checkpoint reload (frozen). 1565 self.layers[self.num_dendrites].requires_grad_( 1566 (not GPA.pc.get_perforated_backpropagation()) 1567 or GPA.pc.get_dendrite_update_mode() 1568 ) 1569 if self.num_dendrites > 0: 1570 self.dendrites_to_dendrites[self.num_dendrites].copy_( 1571 self.best_dendrites_to_candidates_saved[plane_max_index] 1572 ) 1573 if type(self.parent_module) in GPA.pc.get_modules_with_processing(): 1574 self.processors.append(self.candidate_processors[plane_max_index]) 1575 if ( 1576 type(self.parent_module).__name__ 1577 in GPA.pc.get_module_names_with_processing() 1578 ): 1579 self.processors.append(self.candidate_processors[plane_max_index]) 1580 if GPA.pc.get_perforated_backpropagation(): 1581 MPB.set_pb_mode(self, mode) 1582 del self.candidate_module, self.best_candidate_module 1583 1584 self.num_dendrites += 1 1585 set_parameter_type(self.dendrites_to_dendrites, "dendrite") 1586 set_parameter_type(self.layers, "dendrite")
Perform actions when switching between neuron and dendrite training.
Parameters
- mode (str): The mode to set. Either "n" for neuron training or "p" for pai-dendrite training.
Returns
- None
1588 def forward(self, *args, **kwargs): 1589 """Forward pass for dendrite module. 1590 1591 Parameters 1592 ---------- 1593 *args : tuple 1594 Positional arguments for the forward pass. 1595 **kwargs : dict 1596 Keyword arguments for the forward pass. 1597 1598 Returns 1599 ------- 1600 Any 1601 The output of the module after processing through the neuron and dendrite modules. 1602 Any 1603 Remaining outputs are only used for Perforated Backpropagation. 1604 Any 1605 Remaining outputs are only used for Perforated Backpropagation. 1606 Any 1607 Remaining outputs are only used for Perforated Backpropagation. 1608 1609 Notes 1610 ----- 1611 If using Perforated Backpropagation, the additional outputs will be moved around in 1612 this code but left unused and only passed into separate PB functions. 1613 """ 1614 1615 outs = {} 1616 1617 # For all modules apply processors, call the modules, then apply post processors 1618 args2, kwargs2 = args, kwargs 1619 for c in range(0, self.num_dendrites): 1620 if GPA.pc.get_perforated_backpropagation(): 1621 args2, kwargs2 = MPB.preprocess_pb(*args, **kwargs) 1622 if self.processors != []: 1623 try: 1624 args2, kwargs2 = self.processors[c].pre_d(*args2, **kwargs2) 1625 except Exception as e: 1626 traceback.print_exc(limit=None, chain=True) 1627 print(f"Your pre_d processor for {self.name} caused this error") 1628 print( 1629 f"You must check how this is defined and ensure that it is properly" 1630 ) 1631 print( 1632 f"accepting inputs to the PAIModule and returning what will then be" 1633 ) 1634 print(f"the input to the dendrite module") 1635 sys.exit() 1636 out_values = self.layers[c](*args2, **kwargs2) 1637 if self.processors != []: 1638 try: 1639 outs[c] = self.processors[c].post_d(out_values) 1640 except Exception as e: 1641 traceback.print_exc(limit=None, chain=True) 1642 print(f"Your post_d processor for {self.name} caused this error") 1643 print( 1644 f"You must check how this is defined and ensure that it is properly" 1645 ) 1646 print( 1647 f"accepting outputs from the dendrite module and returning the" 1648 ) 1649 print( 1650 f"single tensor to be combined with the neurons output tensor" 1651 ) 1652 sys.exit() 1653 else: 1654 outs[c] = out_values 1655 1656 # Create dendrite outputs 1657 # Each dendrite has input from previously created dendrites 1658 # So activation is added before the nonlinearity is called 1659 view_tuple = [] 1660 for out_index in range(0, self.num_dendrites): 1661 current_out = outs[out_index] 1662 view_tuple = [] 1663 for dim in range(len(current_out.shape)): 1664 if dim == self.this_node_index: 1665 view_tuple.append(-1) 1666 continue 1667 view_tuple.append(1) 1668 1669 for in_index in range(0, out_index): 1670 if view_tuple == [ 1671 1 1672 ]: # This is only the case when passing a single datapoint rather than a batch 1673 current_out = ( 1674 current_out 1675 + self.dendrites_to_dendrites[out_index][in_index, :].to( 1676 current_out.device 1677 ) 1678 * outs[in_index] 1679 ) 1680 else: 1681 current_out = ( 1682 current_out 1683 + self.dendrites_to_dendrites[out_index][in_index, :] 1684 .view(view_tuple) 1685 .to(current_out.device) 1686 * outs[in_index] 1687 ) 1688 outs[out_index] = GPA.pc.get_pai_forward_function()(current_out) 1689 # Return a dict which has all dendritic outputs after the activation functions were called 1690 if GPA.pc.get_perforated_backpropagation(): 1691 candidate_outs, candidate_nonlinear_outs, candidate_non_zeroed = ( 1692 MPB.forward_candidates(self, view_tuple, outs, *args2, **kwargs2) 1693 ) 1694 else: 1695 candidate_outs, candidate_nonlinear_outs, candidate_non_zeroed = ( 1696 {}, 1697 {}, 1698 {}, 1699 ) 1700 return outs, candidate_outs, candidate_nonlinear_outs, candidate_non_zeroed
Forward pass for dendrite module.
Parameters
- *args (tuple): Positional arguments for the forward pass.
- **kwargs (dict): Keyword arguments for the forward pass.
Returns
- Any: The output of the module after processing through the neuron and dendrite modules.
- Any: Remaining outputs are only used for Perforated Backpropagation.
- Any: Remaining outputs are only used for Perforated Backpropagation.
- Any: Remaining outputs are only used for Perforated Backpropagation.
Notes
If using Perforated Backpropagation, the additional outputs will be moved around in this code but left unused and only passed into separate PB functions.
1703class DendriteValueTracker(nn.Module): 1704 """Tracker object that maintains certain values for each set of dendrites.""" 1705 1706 def __init__( 1707 self, 1708 initialized, 1709 activation_function_value, 1710 name, 1711 output_dimensions, 1712 out_channels=-1, 1713 ): 1714 """Initialize DendriteValueTracker. 1715 1716 This function sets up the value tracker to maintain statistics and values 1717 for each set of dendrites. 1718 1719 Parameters 1720 ---------- 1721 initialized : int 1722 Whether the dendrite has been initialized (1) or not (0). 1723 activation_function_value : float 1724 A value associated with the activation function. 1725 name : str 1726 The name of the associated neuron module. 1727 output_dimensions : vector 1728 The dimensions of the input vector. 1729 out_channels : int 1730 The number of output channels 1731 """ 1732 super(DendriteValueTracker, self).__init__() 1733 1734 self.layer_name = name 1735 for val_name in DENDRITE_INIT_VALUES: 1736 self.register_buffer( 1737 val_name, 1738 torch.zeros(1, device=GPA.pc.get_device(), dtype=GPA.pc.get_d_type()), 1739 ) 1740 self.initialized[0] = initialized 1741 self.activation_function_value = activation_function_value 1742 self.register_buffer( 1743 "this_output_dimensions", output_dimensions.clone().detach() 1744 ) 1745 if (self.this_output_dimensions == GPA.NODE_AXIS).sum() != 1: 1746 print(f"3 need exactly one 0 in the input dimensions: {self.layer_name}") 1747 print(self.this_output_dimensions) 1748 sys.exit(-1) 1749 self.register_buffer( 1750 "this_node_index", 1751 (output_dimensions == GPA.NODE_AXIS).nonzero(as_tuple=True)[0], 1752 ) 1753 if out_channels != -1: 1754 ndim = len(output_dimensions) 1755 init_shape = [1] * ndim 1756 init_shape[(output_dimensions == GPA.NODE_AXIS).nonzero(as_tuple=True)[0].item()] = out_channels 1757 self.setup_arrays(init_shape) 1758 else: 1759 self.out_channels = -1 1760 1761 def print(self): 1762 """Print value tracker information. 1763 1764 Parameters 1765 ---------- 1766 None 1767 1768 Returns 1769 ------- 1770 None 1771 This function does not return a value. 1772 """ 1773 total_string = "Value Tracker:" 1774 for val_name in DENDRITE_INIT_VALUES: 1775 total_string += f"\t{val_name}:\n\t\t" 1776 total_string += getattr(self, val_name).__repr__() 1777 total_string += "\n" 1778 for val_name in get_DENDRITE_TENSOR_VALUES(): 1779 if getattr(self, val_name, None) is not None: 1780 total_string += f"\t{val_name}:\n\t\t" 1781 total_string += getattr(self, val_name).__repr__() 1782 total_string += "\n" 1783 print(total_string) 1784 1785 def set_this_output_dimensions(self, new_output_dimensions): 1786 """Set input dimensions for value tracker 1787 1788 Signals to this DendriteValueTracker that its input dimensions are different 1789 than the global default. 1790 1791 Parameters 1792 ---------- 1793 new_output_dimensions : list 1794 A list or tensor specifying the new input dimensions. 1795 Returns 1796 ------- 1797 None 1798 1799 """ 1800 if type(new_output_dimensions) is list: 1801 new_output_dimensions = torch.tensor(new_output_dimensions) 1802 device = self.this_output_dimensions.device 1803 delattr(self, "this_output_dimensions") 1804 self.register_buffer( 1805 "this_output_dimensions", new_output_dimensions.detach().clone().to(device) 1806 ) 1807 if (new_output_dimensions == GPA.NODE_AXIS).sum() != 1: 1808 print(f"4 need exactly one 0 in the input dimensions: {self.layer_name}") 1809 print(new_output_dimensions) 1810 sys.exit(-1) 1811 self.this_node_index.copy_( 1812 (new_output_dimensions == GPA.NODE_AXIS).nonzero(as_tuple=True)[0][0] 1813 ) 1814 1815 def set_out_channels(self, shape_values): 1816 """Set output channels based on shape values and saved node index 1817 1818 Parameters 1819 ---------- 1820 shape_values : list or torch.Size 1821 A list or tensor specifying the shape values. 1822 1823 Returns 1824 ------- 1825 None 1826 """ 1827 # DESIGN ASSUMPTION (spatially resolved covariance): each target layer is 1828 # assumed to emit a fixed H x W on every batch. The spatially resolved 1829 # covariance buffers (shape N x H x W) are sized once, from the H and W read 1830 # off this same shape_values at setup time, and are never resized afterward. 1831 # A layer whose spatial size varies across batches would therefore fail to 1832 # broadcast against these fixed-size buffers; supporting variable spatial 1833 # sizes would require a mismatch policy here and in setup_arrays. 1834 if type(shape_values) == torch.Size: 1835 self.out_channels = int(shape_values[self.this_node_index]) 1836 else: 1837 self.out_channels = int(shape_values[self.this_node_index].item()) 1838 1839 def setup_arrays(self, storage_shape): 1840 """Setup arrays for value tracker. 1841 1842 Parameters 1843 ---------- 1844 storage_shape : list 1845 Shape for the tracking tensors: 1 at every dim except the channel 1846 dim (this_node_index), which holds out_channels. E.g. [1, 5] for 1847 a linear layer with 5 outputs. 1848 Returns 1849 ------- 1850 None 1851 1852 """ 1853 # storage_shape is a list with 1 at every dim except the channel dim. 1854 # Passed in directly from filter_backward so it is always derived from 1855 # the live gradient — not from out_channels, which is not saved/loaded. 1856 self.out_channels = storage_shape[self.this_node_index.item()] 1857 self.register_buffer( 1858 "dendrite_storage_shape", 1859 torch.tensor(storage_shape, dtype=torch.long, device=GPA.pc.get_device()), 1860 ) 1861 for val_name in get_DENDRITE_TENSOR_VALUES(): 1862 self.register_buffer( 1863 val_name, 1864 torch.zeros( 1865 storage_shape, device=GPA.pc.get_device(), dtype=GPA.pc.get_d_type() 1866 ), 1867 ) 1868 1869 for name in get_VALUE_TRACKER_ARRAYS(): 1870 setattr(self, name, {}) 1871 count = 1 1872 if torch.cuda.device_count() > count: 1873 count = torch.cuda.device_count() 1874 for i in range(count): 1875 getattr(self, name)[i] = [] 1876 for val_name in get_DENDRITE_SINGLE_VALUES(): 1877 self.register_buffer( 1878 val_name, 1879 torch.zeros(1, device=GPA.pc.get_device(), dtype=GPA.pc.get_d_type()), 1880 ) 1881 1882 def reinitialize_for_pai(self): 1883 """Reinitialize value tracker to add the next set of dendrites 1884 1885 Parameters 1886 ---------- 1887 None 1888 1889 Returns 1890 ------- 1891 None 1892 This function does not return a value. 1893 """ 1894 1895 if self.out_channels == -1: 1896 print("You have a perforated module that was never initialized") 1897 print("This likely means it is not being added to the autograd graph") 1898 print("Check your forward function that it is actually being used") 1899 print("If its not you should really delete it, but you can also add") 1900 print(self.layer_name) 1901 print("with:") 1902 print("GPA.pc.append_module_ids_to_track(['" + self.layer_name + "'])") 1903 print("This can also happen while testing_dendrite_capacity if you") 1904 print( 1905 "run a validation cycle and try to add Dendrites before doing any training.\n" 1906 ) 1907 pdb.set_trace() 1908 1909 self.initialized[0] = 0 1910 if GPA.pc.get_perforated_backpropagation(): 1911 MPB.reinitialize_for_pb(self) 1912 else: 1913 for val_name in get_DENDRITE_REINIT_VALUES(): 1914 setattr(self, val_name, getattr(self, val_name) * 0)
Tracker object that maintains certain values for each set of dendrites.
1706 def __init__( 1707 self, 1708 initialized, 1709 activation_function_value, 1710 name, 1711 output_dimensions, 1712 out_channels=-1, 1713 ): 1714 """Initialize DendriteValueTracker. 1715 1716 This function sets up the value tracker to maintain statistics and values 1717 for each set of dendrites. 1718 1719 Parameters 1720 ---------- 1721 initialized : int 1722 Whether the dendrite has been initialized (1) or not (0). 1723 activation_function_value : float 1724 A value associated with the activation function. 1725 name : str 1726 The name of the associated neuron module. 1727 output_dimensions : vector 1728 The dimensions of the input vector. 1729 out_channels : int 1730 The number of output channels 1731 """ 1732 super(DendriteValueTracker, self).__init__() 1733 1734 self.layer_name = name 1735 for val_name in DENDRITE_INIT_VALUES: 1736 self.register_buffer( 1737 val_name, 1738 torch.zeros(1, device=GPA.pc.get_device(), dtype=GPA.pc.get_d_type()), 1739 ) 1740 self.initialized[0] = initialized 1741 self.activation_function_value = activation_function_value 1742 self.register_buffer( 1743 "this_output_dimensions", output_dimensions.clone().detach() 1744 ) 1745 if (self.this_output_dimensions == GPA.NODE_AXIS).sum() != 1: 1746 print(f"3 need exactly one 0 in the input dimensions: {self.layer_name}") 1747 print(self.this_output_dimensions) 1748 sys.exit(-1) 1749 self.register_buffer( 1750 "this_node_index", 1751 (output_dimensions == GPA.NODE_AXIS).nonzero(as_tuple=True)[0], 1752 ) 1753 if out_channels != -1: 1754 ndim = len(output_dimensions) 1755 init_shape = [1] * ndim 1756 init_shape[(output_dimensions == GPA.NODE_AXIS).nonzero(as_tuple=True)[0].item()] = out_channels 1757 self.setup_arrays(init_shape) 1758 else: 1759 self.out_channels = -1
Initialize DendriteValueTracker.
This function sets up the value tracker to maintain statistics and values for each set of dendrites.
Parameters
- initialized (int): Whether the dendrite has been initialized (1) or not (0).
- activation_function_value (float): A value associated with the activation function.
- name (str): The name of the associated neuron module.
- output_dimensions (vector): The dimensions of the input vector.
- out_channels (int): The number of output channels
1761 def print(self): 1762 """Print value tracker information. 1763 1764 Parameters 1765 ---------- 1766 None 1767 1768 Returns 1769 ------- 1770 None 1771 This function does not return a value. 1772 """ 1773 total_string = "Value Tracker:" 1774 for val_name in DENDRITE_INIT_VALUES: 1775 total_string += f"\t{val_name}:\n\t\t" 1776 total_string += getattr(self, val_name).__repr__() 1777 total_string += "\n" 1778 for val_name in get_DENDRITE_TENSOR_VALUES(): 1779 if getattr(self, val_name, None) is not None: 1780 total_string += f"\t{val_name}:\n\t\t" 1781 total_string += getattr(self, val_name).__repr__() 1782 total_string += "\n" 1783 print(total_string)
Print value tracker information.
Parameters
- None
Returns
- None: This function does not return a value.
1785 def set_this_output_dimensions(self, new_output_dimensions): 1786 """Set input dimensions for value tracker 1787 1788 Signals to this DendriteValueTracker that its input dimensions are different 1789 than the global default. 1790 1791 Parameters 1792 ---------- 1793 new_output_dimensions : list 1794 A list or tensor specifying the new input dimensions. 1795 Returns 1796 ------- 1797 None 1798 1799 """ 1800 if type(new_output_dimensions) is list: 1801 new_output_dimensions = torch.tensor(new_output_dimensions) 1802 device = self.this_output_dimensions.device 1803 delattr(self, "this_output_dimensions") 1804 self.register_buffer( 1805 "this_output_dimensions", new_output_dimensions.detach().clone().to(device) 1806 ) 1807 if (new_output_dimensions == GPA.NODE_AXIS).sum() != 1: 1808 print(f"4 need exactly one 0 in the input dimensions: {self.layer_name}") 1809 print(new_output_dimensions) 1810 sys.exit(-1) 1811 self.this_node_index.copy_( 1812 (new_output_dimensions == GPA.NODE_AXIS).nonzero(as_tuple=True)[0][0] 1813 )
Set input dimensions for value tracker
Signals to this DendriteValueTracker that its input dimensions are different than the global default.
Parameters
- new_output_dimensions (list): A list or tensor specifying the new input dimensions.
Returns
- None
1815 def set_out_channels(self, shape_values): 1816 """Set output channels based on shape values and saved node index 1817 1818 Parameters 1819 ---------- 1820 shape_values : list or torch.Size 1821 A list or tensor specifying the shape values. 1822 1823 Returns 1824 ------- 1825 None 1826 """ 1827 # DESIGN ASSUMPTION (spatially resolved covariance): each target layer is 1828 # assumed to emit a fixed H x W on every batch. The spatially resolved 1829 # covariance buffers (shape N x H x W) are sized once, from the H and W read 1830 # off this same shape_values at setup time, and are never resized afterward. 1831 # A layer whose spatial size varies across batches would therefore fail to 1832 # broadcast against these fixed-size buffers; supporting variable spatial 1833 # sizes would require a mismatch policy here and in setup_arrays. 1834 if type(shape_values) == torch.Size: 1835 self.out_channels = int(shape_values[self.this_node_index]) 1836 else: 1837 self.out_channels = int(shape_values[self.this_node_index].item())
Set output channels based on shape values and saved node index
Parameters
- shape_values (list or torch.Size): A list or tensor specifying the shape values.
Returns
- None
1839 def setup_arrays(self, storage_shape): 1840 """Setup arrays for value tracker. 1841 1842 Parameters 1843 ---------- 1844 storage_shape : list 1845 Shape for the tracking tensors: 1 at every dim except the channel 1846 dim (this_node_index), which holds out_channels. E.g. [1, 5] for 1847 a linear layer with 5 outputs. 1848 Returns 1849 ------- 1850 None 1851 1852 """ 1853 # storage_shape is a list with 1 at every dim except the channel dim. 1854 # Passed in directly from filter_backward so it is always derived from 1855 # the live gradient — not from out_channels, which is not saved/loaded. 1856 self.out_channels = storage_shape[self.this_node_index.item()] 1857 self.register_buffer( 1858 "dendrite_storage_shape", 1859 torch.tensor(storage_shape, dtype=torch.long, device=GPA.pc.get_device()), 1860 ) 1861 for val_name in get_DENDRITE_TENSOR_VALUES(): 1862 self.register_buffer( 1863 val_name, 1864 torch.zeros( 1865 storage_shape, device=GPA.pc.get_device(), dtype=GPA.pc.get_d_type() 1866 ), 1867 ) 1868 1869 for name in get_VALUE_TRACKER_ARRAYS(): 1870 setattr(self, name, {}) 1871 count = 1 1872 if torch.cuda.device_count() > count: 1873 count = torch.cuda.device_count() 1874 for i in range(count): 1875 getattr(self, name)[i] = [] 1876 for val_name in get_DENDRITE_SINGLE_VALUES(): 1877 self.register_buffer( 1878 val_name, 1879 torch.zeros(1, device=GPA.pc.get_device(), dtype=GPA.pc.get_d_type()), 1880 )
Setup arrays for value tracker.
Parameters
- storage_shape (list): Shape for the tracking tensors: 1 at every dim except the channel dim (this_node_index), which holds out_channels. E.g. [1, 5] for a linear layer with 5 outputs.
Returns
- None
1882 def reinitialize_for_pai(self): 1883 """Reinitialize value tracker to add the next set of dendrites 1884 1885 Parameters 1886 ---------- 1887 None 1888 1889 Returns 1890 ------- 1891 None 1892 This function does not return a value. 1893 """ 1894 1895 if self.out_channels == -1: 1896 print("You have a perforated module that was never initialized") 1897 print("This likely means it is not being added to the autograd graph") 1898 print("Check your forward function that it is actually being used") 1899 print("If its not you should really delete it, but you can also add") 1900 print(self.layer_name) 1901 print("with:") 1902 print("GPA.pc.append_module_ids_to_track(['" + self.layer_name + "'])") 1903 print("This can also happen while testing_dendrite_capacity if you") 1904 print( 1905 "run a validation cycle and try to add Dendrites before doing any training.\n" 1906 ) 1907 pdb.set_trace() 1908 1909 self.initialized[0] = 0 1910 if GPA.pc.get_perforated_backpropagation(): 1911 MPB.reinitialize_for_pb(self) 1912 else: 1913 for val_name in get_DENDRITE_REINIT_VALUES(): 1914 setattr(self, val_name, getattr(self, val_name) * 0)
Reinitialize value tracker to add the next set of dendrites
Parameters
- None
Returns
- None: This function does not return a value.