Created
April 25, 2021 01:55
-
-
Save wangkuiyi/dd2e3794d11010f0cd562ed009664f90 to your computer and use it in GitHub Desktop.
torch.nn.AssocEmb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import torch | |
class AssocEmb(torch.nn.Module): | |
def __init__(self, dim: list[int]): | |
super(AssocEmb, self).__init__() | |
self.dim = dim | |
self.tbl = torch.nn.ParameterDict() | |
def forward(self, idx: str) -> torch.Tensor: | |
if idx not in self.tbl: | |
p = torch.rand(self.dim, requires_grad=True) | |
self.tbl[idx] = torch.nn.Parameter(p) | |
return self.tbl[idx] | |
m = AssocEmb([2, 2]) | |
x = m("apple") | |
y = m("orange") | |
z = x * y | |
c = z.sum() | |
c.backward() | |
for k, v in enumerate(m.tbl): | |
print(v, m.tbl[v], m.tbl[v].grad) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment