MCPcopy Create free account
hub / github.com/AkaliKong/MiniOneRec / MemoryUnit

Class MemoryUnit

utility.py:152–180  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

150
151
152class MemoryUnit(nn.Module):
153 # clusters_k is k keys
154 def __init__(self, input_size, output_size, emb_size, clusters_k=10):
155 super(MemoryUnit, self).__init__()
156 self.clusters_k = clusters_k
157 self.input_size = input_size
158 self.output_size = output_size
159 self.array = nn.Parameter(init.xavier_uniform_(torch.FloatTensor(self.clusters_k, input_size*output_size)))
160 self.index = nn.Parameter(init.xavier_uniform_(torch.FloatTensor(self.clusters_k, emb_size)))
161 self.softmax = nn.Softmax(dim=-1)
162
163 def forward(self, bias_emb):
164 """
165 bias_emb: [batch_size, 1, emb_size]
166 """
167 att_scores = torch.matmul(bias_emb, self.index.transpose(-1, -2)) # [batch_size, clusters_k]
168 att_scores = self.softmax(att_scores)
169
170 # [batch_size, input_size, output_size]
171 para_new = torch.matmul(att_scores, self.array) # [batch_size, input_size*output_size]
172 para_new = para_new.view(-1, self.output_size, self.input_size)
173
174 return para_new
175
176 def reg_loss(self, reg_weights=1e-2):
177 loss_1 = reg_weights * self.array.norm(2)
178 loss_2 = reg_weights * self.index.norm(2)
179
180 return loss_1 + loss_2

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected