Helper method to make it easier to cleanly torch.export() a method on a module that is not `forward`. TODO(suo): upstream this to torch.export.wrapper.
(obj: torch.nn.Module, new_method)
| 137 | |
| 138 | @contextmanager |
| 139 | def patch_forward(obj: torch.nn.Module, new_method): |
| 140 | """Helper method to make it easier to cleanly torch.export() a method on a |
| 141 | module that is not `forward`. |
| 142 | |
| 143 | TODO(suo): upstream this to torch.export.wrapper. |
| 144 | """ |
| 145 | # Save the original method |
| 146 | original_method = obj.forward |
| 147 | |
| 148 | # Patch the method |
| 149 | obj.forward = new_method.__get__(obj, obj.__class__) |
| 150 | |
| 151 | try: |
| 152 | yield |
| 153 | finally: |
| 154 | # Restore the original method |
| 155 | obj.forward = original_method |
| 156 | |
| 157 | |
| 158 | class WrapperModule(torch.nn.Module): |
no outgoing calls