Skip to content

Instantly share code, notes, and snippets.

@wayofnumbers
Last active November 1, 2019 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wayofnumbers/cf9ab55f2717634bf7344791f743f259 to your computer and use it in GitHub Desktop.
Save wayofnumbers/cf9ab55f2717634bf7344791f743f259 to your computer and use it in GitHub Desktop.
Iteration 2 of the myLinear model
class myLinear(nn.Module):
def __init__(self, in_features, out_features, bias=True):
super().__init__()
self.in_features = in_features
self.out_features = out_features
self.bias = bias
self.weight = torch.nn.Parameter(torch.Tensor(out_features, in_features))
if bias:
self.bias = torch.nn.Parameter(torch.Tensor(out_features))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
torch.nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))
if self.bias is not None:
fan_in, _ = torch.nn.init._calculate_fan_in_and_fan_out(self.weight)
bound = 1 / math.sqrt(fan_in)
torch.nn.init.uniform_(self.bias, -bound, bound)
def forward(self, input):
x, y = input.shape
if y != self.in_features:
print(f'Wrong Input Features. Please use tensor with {self.in_features} Input Features')
return 0
output = input.matmul(weight.t())
if bias is not None:
output += bias
ret = output
return ret
def extra_repr(self):
return 'in_features={}, out_features={}, bias={}'.format(
self.in_features, self.out_features, self.bias is not None
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment