perforatedai.suggestions_perforatedai
Analysis of how a PAI run ended, with suggestions for what to try next.
When training ends because the newest dendrites did not improve the validation score on any of their max_dendrite_tries tries, the tracker calls analyze_outcome with the network that still holds those dendrites, before it deletes them by reloading the best model. Each function in OUTCOME_CHECKS looks at that network and the results of the run, and returns a suggestion, or None when it has nothing to suggest. The results that the CSV files are written from are in GPA.pai_tracker.member_vars, and the files themselves are in the GPA.pc.get_save_name() folder. To add a check, write a function with the same arguments as check_dendrite_lr_multiplier and append it to OUTCOME_CHECKS.
1"""Analysis of how a PAI run ended, with suggestions for what to try next. 2 3When training ends because the newest dendrites did not improve the validation 4score on any of their max_dendrite_tries tries, the tracker calls 5analyze_outcome with the network that still holds those dendrites, before it 6deletes them by reloading the best model. Each function in OUTCOME_CHECKS 7looks at that network and the results of the run, and returns a suggestion, 8or None when it has nothing to suggest. The results that the CSV files are 9written from are in GPA.pai_tracker.member_vars, and the files themselves are 10in the GPA.pc.get_save_name() folder. To add a check, write a function with 11the same arguments as check_dendrite_lr_multiplier and append it to 12OUTCOME_CHECKS. 13""" 14 15from perforatedai import globals_perforatedai as GPA 16from perforatedai import modules_perforatedai as PA 17from perforatedai import utils_perforatedai as UPA 18 19# Below this, the newest dendrites' output weights are too small for the dendrites 20# to change the network (see newest_dendrite_to_top_ratios). Fine-tuning bert-mini 21# at a learning rate of 2e-5, a dendrite trained at 1x that rate reached 0.0003 22# after a cycle, at 10x 0.008 and at 30x 0.18. Training a CNN on MNIST from 23# scratch, the largest ratio of any module was at least 0.007 at every epoch. 24SMALL_DENDRITE_TO_TOP_RATIO = 0.001 25 26 27def newest_dendrite_to_top_ratios(net): 28 """Measure the output weights (dendrites_to_top) of the newest dendrite of each perforated module. 29 30 For each output of a module, the newest dendrite's output weight is divided 31 by the norm of the module's weights for that output, which is about the size 32 of that output for inputs of unit size. The module's ratio is the median over 33 its outputs. 34 35 Parameters 36 ---------- 37 net : nn.Module 38 The network, with dendrites added. 39 40 Returns 41 ------- 42 dict 43 Module name to ratio, for the modules with dendrites whose weight has the 44 outputs as its first dimension. 45 """ 46 ratios = {} 47 for module in UPA.get_pai_modules(net, 0): 48 if module.dendrite_modules_added == 0: 49 continue 50 weight = getattr(module.main_module, "weight", None) 51 to_top = module.dendrites_to_top[-1][-1].detach().abs() 52 if weight is None or weight.dim() < 2 or weight.shape[0] != to_top.shape[0]: 53 continue 54 output_size = weight.detach().flatten(1).norm(dim=1).clamp_min(1e-12) 55 ratios[module.name] = (to_top / output_size.to(to_top.device)).median().item() 56 return ratios 57 58 59def check_dendrite_lr_multiplier(net, dendrites_added): 60 """Suggest a higher dendrite_lr_multiplier if the most recently deleted dendrites stayed too small. 61 62 A dendrite's output weights (dendrites_to_top) start at 0. With a small 63 learning rate, such as when fine-tuning a pretrained model, they barely grow, 64 so the dendrites cannot change the network or improve its score. When 65 dendrites were kept, the score may then have improved only because training 66 restarted after each one was added. 67 68 Parameters 69 ---------- 70 net : nn.Module 71 The network holding the most recently deleted dendrites. 72 dendrites_added : bool 73 Whether the final model kept at least one dendrite. 74 75 Returns 76 ------- 77 str or None 78 The suggestion, or None. 79 """ 80 ratios = newest_dendrite_to_top_ratios(net) 81 if not ratios or max(ratios.values()) >= SMALL_DENDRITE_TO_TOP_RATIO: 82 return None 83 multiplier = GPA.pc.get_dendrite_lr_multiplier() 84 finding = ( 85 f"{'The' if dendrites_added else 'No dendrites were kept, and the'} output " 86 f"weights (dendrites_to_top) of the last dendrites tried stayed very small: " 87 f"at most {max(ratios.values()):.1e} of the size of the module weights. " 88 f"These weights start at 0, and with a small learning rate, such as when " 89 f"fine-tuning a pretrained model, they barely grow, so the dendrites cannot " 90 f"change the network." 91 ) 92 if dendrites_added: 93 finding += ( 94 " The dendrites that were kept may have improved the score only because " 95 "training restarted after each one was added." 96 ) 97 optimizer = GPA.pai_tracker.member_vars.get("optimizer_instance") 98 if multiplier != 1 and _trains_dendrites_at_neuron_lr(optimizer): 99 return ( 100 f"{finding} dendrite_lr_multiplier is {multiplier:g}, but the optimizer " 101 f"trains the dendrites at the learning rate of the neurons. Build its " 102 f"parameters with UPA.get_parameter_groups(params, lr), both where you " 103 f"first create it and where you create it again after each restructure." 104 ) 105 if multiplier == 1: 106 setting = "GPA.pc.set_dendrite_lr_multiplier(10), then 30 or 100" 107 else: 108 setting = f"GPA.pc.set_dendrite_lr_multiplier({multiplier * 3:g})" 109 suggestion = ( 110 f"{finding} Next, try {setting} (or dendrite_lr_multiplier in your config " 111 f"file) to train the dendrites at that multiple of the learning rate." 112 ) 113 if not UPA.parameter_groups_requested: 114 suggestion += ( 115 " setup_optimizer applies it. If you build the optimizer yourself for " 116 "set_optimizer_instance, build its parameters with " 117 "UPA.get_parameter_groups(params, lr), both where you first create it " 118 "and where you create it again after each restructure." 119 ) 120 return suggestion 121 122 123def _trains_dendrites_at_neuron_lr(optimizer): 124 """Return whether a parameter group of the optimizer mixes dendrite and neuron parameters.""" 125 for param_group in getattr(optimizer, "param_groups", []): 126 dendrite = [PA.is_dendrite_parameter(p) for p in param_group["params"]] 127 if any(dendrite) and not all(dendrite): 128 return True 129 return False 130 131 132OUTCOME_CHECKS = [check_dendrite_lr_multiplier] 133 134 135def analyze_outcome(net, dendrites_added): 136 """Run every check in OUTCOME_CHECKS and return their suggestions. 137 138 A check that raises an error is skipped, so that it cannot stop training 139 from ending normally. 140 141 Parameters 142 ---------- 143 net : nn.Module 144 The network holding the most recently deleted dendrites. 145 dendrites_added : bool 146 Whether the final model kept at least one dendrite. 147 148 Returns 149 ------- 150 list of str 151 The suggestions of all checks that made one. 152 """ 153 suggestions = [] 154 for check in OUTCOME_CHECKS: 155 try: 156 suggestion = check(net, dendrites_added) 157 except Exception as e: 158 print(f"Skipping the outcome check {check.__name__}: {e}") 159 continue 160 if suggestion: 161 suggestions.append(suggestion) 162 return suggestions
28def newest_dendrite_to_top_ratios(net): 29 """Measure the output weights (dendrites_to_top) of the newest dendrite of each perforated module. 30 31 For each output of a module, the newest dendrite's output weight is divided 32 by the norm of the module's weights for that output, which is about the size 33 of that output for inputs of unit size. The module's ratio is the median over 34 its outputs. 35 36 Parameters 37 ---------- 38 net : nn.Module 39 The network, with dendrites added. 40 41 Returns 42 ------- 43 dict 44 Module name to ratio, for the modules with dendrites whose weight has the 45 outputs as its first dimension. 46 """ 47 ratios = {} 48 for module in UPA.get_pai_modules(net, 0): 49 if module.dendrite_modules_added == 0: 50 continue 51 weight = getattr(module.main_module, "weight", None) 52 to_top = module.dendrites_to_top[-1][-1].detach().abs() 53 if weight is None or weight.dim() < 2 or weight.shape[0] != to_top.shape[0]: 54 continue 55 output_size = weight.detach().flatten(1).norm(dim=1).clamp_min(1e-12) 56 ratios[module.name] = (to_top / output_size.to(to_top.device)).median().item() 57 return ratios
Measure the output weights (dendrites_to_top) of the newest dendrite of each perforated module.
For each output of a module, the newest dendrite's output weight is divided by the norm of the module's weights for that output, which is about the size of that output for inputs of unit size. The module's ratio is the median over its outputs.
Parameters
- net (nn.Module): The network, with dendrites added.
Returns
- dict: Module name to ratio, for the modules with dendrites whose weight has the outputs as its first dimension.
60def check_dendrite_lr_multiplier(net, dendrites_added): 61 """Suggest a higher dendrite_lr_multiplier if the most recently deleted dendrites stayed too small. 62 63 A dendrite's output weights (dendrites_to_top) start at 0. With a small 64 learning rate, such as when fine-tuning a pretrained model, they barely grow, 65 so the dendrites cannot change the network or improve its score. When 66 dendrites were kept, the score may then have improved only because training 67 restarted after each one was added. 68 69 Parameters 70 ---------- 71 net : nn.Module 72 The network holding the most recently deleted dendrites. 73 dendrites_added : bool 74 Whether the final model kept at least one dendrite. 75 76 Returns 77 ------- 78 str or None 79 The suggestion, or None. 80 """ 81 ratios = newest_dendrite_to_top_ratios(net) 82 if not ratios or max(ratios.values()) >= SMALL_DENDRITE_TO_TOP_RATIO: 83 return None 84 multiplier = GPA.pc.get_dendrite_lr_multiplier() 85 finding = ( 86 f"{'The' if dendrites_added else 'No dendrites were kept, and the'} output " 87 f"weights (dendrites_to_top) of the last dendrites tried stayed very small: " 88 f"at most {max(ratios.values()):.1e} of the size of the module weights. " 89 f"These weights start at 0, and with a small learning rate, such as when " 90 f"fine-tuning a pretrained model, they barely grow, so the dendrites cannot " 91 f"change the network." 92 ) 93 if dendrites_added: 94 finding += ( 95 " The dendrites that were kept may have improved the score only because " 96 "training restarted after each one was added." 97 ) 98 optimizer = GPA.pai_tracker.member_vars.get("optimizer_instance") 99 if multiplier != 1 and _trains_dendrites_at_neuron_lr(optimizer): 100 return ( 101 f"{finding} dendrite_lr_multiplier is {multiplier:g}, but the optimizer " 102 f"trains the dendrites at the learning rate of the neurons. Build its " 103 f"parameters with UPA.get_parameter_groups(params, lr), both where you " 104 f"first create it and where you create it again after each restructure." 105 ) 106 if multiplier == 1: 107 setting = "GPA.pc.set_dendrite_lr_multiplier(10), then 30 or 100" 108 else: 109 setting = f"GPA.pc.set_dendrite_lr_multiplier({multiplier * 3:g})" 110 suggestion = ( 111 f"{finding} Next, try {setting} (or dendrite_lr_multiplier in your config " 112 f"file) to train the dendrites at that multiple of the learning rate." 113 ) 114 if not UPA.parameter_groups_requested: 115 suggestion += ( 116 " setup_optimizer applies it. If you build the optimizer yourself for " 117 "set_optimizer_instance, build its parameters with " 118 "UPA.get_parameter_groups(params, lr), both where you first create it " 119 "and where you create it again after each restructure." 120 ) 121 return suggestion
Suggest a higher dendrite_lr_multiplier if the most recently deleted dendrites stayed too small.
A dendrite's output weights (dendrites_to_top) start at 0. With a small learning rate, such as when fine-tuning a pretrained model, they barely grow, so the dendrites cannot change the network or improve its score. When dendrites were kept, the score may then have improved only because training restarted after each one was added.
Parameters
- net (nn.Module): The network holding the most recently deleted dendrites.
- dendrites_added (bool): Whether the final model kept at least one dendrite.
Returns
- str or None: The suggestion, or None.
136def analyze_outcome(net, dendrites_added): 137 """Run every check in OUTCOME_CHECKS and return their suggestions. 138 139 A check that raises an error is skipped, so that it cannot stop training 140 from ending normally. 141 142 Parameters 143 ---------- 144 net : nn.Module 145 The network holding the most recently deleted dendrites. 146 dendrites_added : bool 147 Whether the final model kept at least one dendrite. 148 149 Returns 150 ------- 151 list of str 152 The suggestions of all checks that made one. 153 """ 154 suggestions = [] 155 for check in OUTCOME_CHECKS: 156 try: 157 suggestion = check(net, dendrites_added) 158 except Exception as e: 159 print(f"Skipping the outcome check {check.__name__}: {e}") 160 continue 161 if suggestion: 162 suggestions.append(suggestion) 163 return suggestions
Run every check in OUTCOME_CHECKS and return their suggestions.
A check that raises an error is skipped, so that it cannot stop training from ending normally.
Parameters
- net (nn.Module): The network holding the most recently deleted dendrites.
- dendrites_added (bool): Whether the final model kept at least one dendrite.
Returns
- list of str: The suggestions of all checks that made one.