base class for MoCo-style memory cache
| 4 | |
| 5 | |
| 6 | class BaseMoCo(nn.Module): |
| 7 | """base class for MoCo-style memory cache""" |
| 8 | def __init__(self, K=65536, T=0.07): |
| 9 | super(BaseMoCo, self).__init__() |
| 10 | self.K = K |
| 11 | self.T = T |
| 12 | self.index = 0 |
| 13 | |
| 14 | def _update_pointer(self, bsz): |
| 15 | self.index = (self.index + bsz) % self.K |
| 16 | |
| 17 | def _update_memory(self, k, queue): |
| 18 | """ |
| 19 | Args: |
| 20 | k: key feature |
| 21 | queue: memory buffer |
| 22 | """ |
| 23 | with torch.no_grad(): |
| 24 | num_neg = k.shape[0] |
| 25 | out_ids = torch.arange(num_neg).cuda() |
| 26 | out_ids = torch.fmod(out_ids + self.index, self.K).long() |
| 27 | queue.index_copy_(0, out_ids, k) |
| 28 | |
| 29 | def _compute_logit(self, q, k, queue): |
| 30 | """ |
| 31 | Args: |
| 32 | q: query/anchor feature |
| 33 | k: key feature |
| 34 | queue: memory buffer |
| 35 | """ |
| 36 | # pos logit |
| 37 | bsz = q.shape[0] |
| 38 | pos = torch.bmm(q.view(bsz, 1, -1), k.view(bsz, -1, 1)) |
| 39 | pos = pos.view(bsz, 1) |
| 40 | |
| 41 | # neg logit |
| 42 | neg = torch.mm(queue, q.transpose(1, 0)) |
| 43 | neg = neg.transpose(0, 1) |
| 44 | |
| 45 | out = torch.cat((pos, neg), dim=1) |
| 46 | out = torch.div(out, self.T) |
| 47 | out = out.squeeze().contiguous() |
| 48 | |
| 49 | return out |
| 50 | |
| 51 | |
| 52 | class RGBMoCo(BaseMoCo): |
nothing calls this directly
no outgoing calls
no test coverage detected