|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +from typing import List |
| 17 | + |
| 18 | +import torch.nn as nn |
| 19 | +from opacus.layers import DPGRU |
| 20 | + |
| 21 | +from .errors import ShouldReplaceModuleError, UnsupportedModuleError |
| 22 | +from .utils import register_module_fixer, register_module_validator |
| 23 | + |
| 24 | + |
| 25 | +@register_module_validator(nn.GRU) |
| 26 | +def validate(module: nn.GRU) -> List[UnsupportedModuleError]: |
| 27 | + return [ |
| 28 | + ShouldReplaceModuleError( |
| 29 | + "We do not support nn.GRU because its implementation uses special " |
| 30 | + "modules. We have written a GRU class that is a drop-in replacement " |
| 31 | + "which is compatible with our Grad Sample hooks. Please run the recommended " |
| 32 | + "replacement!" |
| 33 | + ) |
| 34 | + ] |
| 35 | + |
| 36 | + |
| 37 | +@register_module_fixer(nn.GRU) |
| 38 | +def fix(module: nn.GRU) -> DPGRU: |
| 39 | + dpgru = DPGRU( |
| 40 | + input_size=module.input_size, |
| 41 | + hidden_size=module.hidden_size, |
| 42 | + num_layers=module.num_layers, |
| 43 | + bias=module.bias, |
| 44 | + batch_first=module.batch_first, |
| 45 | + dropout=module.dropout, |
| 46 | + bidirectional=module.bidirectional, |
| 47 | + proj_size=module.proj_size, |
| 48 | + ) |
| 49 | + dpgru.load_state_dict(module.state_dict()) |
| 50 | + return dpgru |
0 commit comments