A few utilities for torch.nn.Modules, to be used as a mixin.
| 71 | |
| 72 | |
| 73 | class ModuleUtilsMixin: |
| 74 | """ |
| 75 | A few utilities for torch.nn.Modules, to be used as a mixin. |
| 76 | """ |
| 77 | |
| 78 | def num_parameters(self, only_trainable: bool = False) -> int: |
| 79 | """ |
| 80 | Get number of (optionally, trainable) parameters in the module. |
| 81 | """ |
| 82 | params = filter(lambda x: x.requires_grad, self.parameters()) if only_trainable else self.parameters() |
| 83 | return sum(p.numel() for p in params) |
| 84 | |
| 85 | @staticmethod |
| 86 | def _hook_rss_memory_pre_forward(module, *args, **kwargs): |
| 87 | try: |
| 88 | import psutil |
| 89 | except (ImportError): |
| 90 | raise ImportError("You need to install psutil (pip install psutil) to use memory tracing.") |
| 91 | |
| 92 | process = psutil.Process(os.getpid()) |
| 93 | mem = process.memory_info() |
| 94 | module.mem_rss_pre_forward = mem.rss |
| 95 | return None |
| 96 | |
| 97 | @staticmethod |
| 98 | def _hook_rss_memory_post_forward(module, *args, **kwargs): |
| 99 | try: |
| 100 | import psutil |
| 101 | except (ImportError): |
| 102 | raise ImportError("You need to install psutil (pip install psutil) to use memory tracing.") |
| 103 | |
| 104 | process = psutil.Process(os.getpid()) |
| 105 | mem = process.memory_info() |
| 106 | module.mem_rss_post_forward = mem.rss |
| 107 | mem_rss_diff = module.mem_rss_post_forward - module.mem_rss_pre_forward |
| 108 | module.mem_rss_diff = mem_rss_diff + (module.mem_rss_diff if hasattr(module, "mem_rss_diff") else 0) |
| 109 | return None |
| 110 | |
| 111 | def add_memory_hooks(self): |
| 112 | """ Add a memory hook before and after each sub-module forward pass to record increase in memory consumption. |
| 113 | Increase in memory consumption is stored in a `mem_rss_diff` attribute for each module and can be reset to zero with `model.reset_memory_hooks_state()` |
| 114 | """ |
| 115 | for module in self.modules(): |
| 116 | module.register_forward_pre_hook(self._hook_rss_memory_pre_forward) |
| 117 | module.register_forward_hook(self._hook_rss_memory_post_forward) |
| 118 | self.reset_memory_hooks_state() |
| 119 | |
| 120 | def reset_memory_hooks_state(self): |
| 121 | for module in self.modules(): |
| 122 | module.mem_rss_diff = 0 |
| 123 | module.mem_rss_post_forward = 0 |
| 124 | module.mem_rss_pre_forward = 0 |
| 125 | |
| 126 | @property |
| 127 | def device(self) -> device: |
| 128 | """ |
| 129 | Get torch.device from module, assuming that the whole module has one device. |
| 130 | """ |
nothing calls this directly
no outgoing calls
no test coverage detected