Basic block for fully-connected neural networks. Applies a dense linearity and a nonlinear activation function.
| 36 | return self.forward(*args, **kwargs) |
| 37 | |
| 38 | class FullyConnectedModule(Module): |
| 39 | """Basic block for fully-connected neural networks. |
| 40 | |
| 41 | Applies a dense linearity and a nonlinear activation function. |
| 42 | |
| 43 | """ |
| 44 | |
| 45 | global_count = 0 # Static counter, used for default names |
| 46 | |
| 47 | def __init__(self, |
| 48 | size, |
| 49 | bias=True, |
| 50 | transpose=False, |
| 51 | weights=[], |
| 52 | activation=None, |
| 53 | name=None, |
| 54 | data_layout='data_parallel', |
| 55 | parallel_strategy={}): |
| 56 | """Initialize fully-connected module. |
| 57 | |
| 58 | Args: |
| 59 | size (int): Size of output tensor. |
| 60 | activation (type): Layer class for activation function. |
| 61 | bias (bool): Whether to apply bias after linearity. |
| 62 | transpose (bool): Whether to apply transpose of weights |
| 63 | matrix. |
| 64 | weights (`Weights` or iterator of `Weights`): Weights in |
| 65 | fully-connected layer. There are at most two: the |
| 66 | matrix and the bias. If weights are not provided, the |
| 67 | matrix will be initialized with He normal |
| 68 | initialization and the bias with zeros. |
| 69 | name (str): Default name is in the form 'fcmodule<index>'. |
| 70 | data_layout (str): Data layout. |
| 71 | parallel_strategy (dict): Data partitioning scheme. |
| 72 | |
| 73 | """ |
| 74 | super().__init__() |
| 75 | FullyConnectedModule.global_count += 1 |
| 76 | self.instance = 0 |
| 77 | self.size = size |
| 78 | self.bias = bias |
| 79 | self.transpose = transpose |
| 80 | self.data_layout = data_layout |
| 81 | self.parallel_strategy = parallel_strategy |
| 82 | |
| 83 | self.name = (name |
| 84 | if name |
| 85 | else 'fcmodule{0}'.format(FullyConnectedModule.global_count)) |
| 86 | |
| 87 | # Initialize weights |
| 88 | # Note: If weights are not provided, matrix weights are |
| 89 | # initialized with He normal scheme and bias weights are |
| 90 | # initialized with zeros. |
| 91 | self.weights = list(make_iterable(weights)) |
| 92 | if len(self.weights) > 2: |
| 93 | raise ValueError('`FullyConnectedModule` has ' |
| 94 | 'at most two weights, ' |
| 95 | 'but got {0}'.format(len(self.weights))) |