MCPcopy Create free account
hub / github.com/apple/ml-pointersect / init_weight

Function init_weight

cdslib/core/nn/nn_utils.py:17–100  ·  view source on GitHub ↗

A helper function to initialize the weights of a linear/convolutional layer. Args: weight: (*), an n-dimensional torch.Tensor to be initialized w_init_gain: The nonlinearity after the linear layer. Can be chosen from the functions supported by

(
    weight: torch.Tensor,
    w_init_gain: str = "linear",
    init_method: str = "xavier_normal",
    lrelu_nslope: float = 0.01,
    kaiming_fan_mode: str = "fan_in",
)

Source from the content-addressed store, hash-verified

15
16
17def init_weight(
18 weight: torch.Tensor,
19 w_init_gain: str = "linear",
20 init_method: str = "xavier_normal",
21 lrelu_nslope: float = 0.01,
22 kaiming_fan_mode: str = "fan_in",
23):
24 """
25 A helper function to initialize the weights of a linear/convolutional layer.
26
27 Args:
28 weight:
29 (*), an n-dimensional torch.Tensor to be initialized
30 w_init_gain:
31 The nonlinearity after the linear layer. Can be chosen from the functions supported by
32 torch.nn.init.calculate_gain.
33 This includes:
34 'linear', 'relu', 'silu', 'leaky_relu', 'relu', 'tanh', 'sigmoid'.
35 init_method:
36 The initialization method. Can be chosen from:
37 'normal':
38 randomly sampeld from a Gaussian distribution
39 'uniform':
40 randomly sampeld from a uniform distribution
41 'xavier_uniform':
42 Check :py:func:`torch.nn.init.xavier_uniform_`.
43 'xavier_normal'
44 Check :py:func:`torch.nn.init.xavier_normal_`.
45 'xavier':
46 same as 'xavier_normal'
47 'kaiming_uniform':
48 Check :py:func:`torch.nn.init.kaiming_uniform_`.
49 'kaiming_normal'
50 Check :py:func:`torch.nn.init.kaiming_normal_`.
51 'kaiming':
52 same as 'kaiming_normal'
53 'orthogonal':
54 Check :py:func:`torch.nn.init.orthogonal_`.
55 lrelu_nslope:
56 Negative slope used in the leaky-relu.
57 kaiming_fan_mode:
58 Fan mode used by kaiming_* init_methods.
59 Returns:
60 Does not return. The function directly modifies the content of weight.
61
62 Note that the function contains torch.no_grad, so there is no need to wrap it with one.
63 """
64
65 # handle silu/swish
66 if w_init_gain in {"silu", "swish"}:
67 # since silu and relu has similar shape, use the gain for relu
68 w_init_gain = "relu"
69
70 # calculate gain
71 if w_init_gain == "leaky_relu":
72 gain = torch.nn.init.calculate_gain(w_init_gain, lrelu_nslope)
73 kaiming_a = lrelu_nslope
74 else:

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected