xref: /aosp_15_r20/external/libopus/dnn/torch/osce/utils/misc.py (revision a58d3d2adb790c104798cd88c8a3aff4fa8b82cc)
1 """
2 /* Copyright (c) 2023 Amazon
3    Written by Jan Buethe */
4 /*
5    Redistribution and use in source and binary forms, with or without
6    modification, are permitted provided that the following conditions
7    are met:
8 
9    - Redistributions of source code must retain the above copyright
10    notice, this list of conditions and the following disclaimer.
11 
12    - Redistributions in binary form must reproduce the above copyright
13    notice, this list of conditions and the following disclaimer in the
14    documentation and/or other materials provided with the distribution.
15 
16    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17    ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
20    OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
21    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22    PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
23    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
24    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
25    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28 """
29 
30 import torch
31 from torch.nn.utils import remove_weight_norm
32 
33 def count_parameters(model, verbose=False):
34     total = 0
35     for name, p in model.named_parameters():
36         count = torch.ones_like(p).sum().item()
37 
38         if verbose:
39             print(f"{name}: {count} parameters")
40 
41         total += count
42 
43     return total
44 
45 def count_nonzero_parameters(model, verbose=False):
46     total = 0
47     for name, p in model.named_parameters():
48         count = torch.count_nonzero(p).item()
49 
50         if verbose:
51             print(f"{name}: {count} non-zero parameters")
52 
53         total += count
54 
55     return total
56 def retain_grads(module):
57     for p in module.parameters():
58         if p.requires_grad:
59             p.retain_grad()
60 
61 def get_grad_norm(module, p=2):
62     norm = 0
63     for param in module.parameters():
64         if param.requires_grad:
65             norm = norm + (torch.abs(param.grad) ** p).sum()
66 
67     return norm ** (1/p)
68 
69 def create_weights(s_real, s_gen, alpha):
70     weights = []
71     with torch.no_grad():
72         for sr, sg in zip(s_real, s_gen):
73             weight = torch.exp(alpha * (sr[-1] - sg[-1]))
74             weights.append(weight)
75 
76     return weights
77 
78 
79 def _get_candidates(module: torch.nn.Module):
80     candidates = []
81     for key in module.__dict__.keys():
82         if hasattr(module, key + '_v'):
83             candidates.append(key)
84     return candidates
85 
86 def remove_all_weight_norm(model : torch.nn.Module, verbose=False):
87     for name, m in model.named_modules():
88         candidates = _get_candidates(m)
89 
90         for candidate in candidates:
91             try:
92                 remove_weight_norm(m, name=candidate)
93                 if verbose: print(f'removed weight norm on weight {name}.{candidate}')
94             except:
95                 pass
96