-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathIndexMerger.py
57 lines (40 loc) · 1.53 KB
/
IndexMerger.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/env python
import torch.nn as nn
import torch
from torch.autograd import Variable
#----------------------------------------------------------------------
# a module which can be used as first module to put together
# a minibatch of indices
#
# note that this can't be used inside a Sequential module because
# the Sequential module does not expect to be passed indices
# so we give the subsequent layers as an argument
class IndexMerger(nn.Module):
def __init__(self, childModule):
super(IndexMerger, self).__init__()
self.childModule = childModule
self.cudaDevice = None
self.isCuda = False
def cuda(self, device_id=None):
self.cudaDevice = device_id
self.isCuda = True
self.childModule.cuda(device_id)
def cpu(self):
self.cudaDevice = None
self.isCuda = False
self.childModule.cpu()
def forward(self, x, indices):
# x is expected to be a list of numpy arrays
#
# we convert the numpy arrays into torch tensors and those
# into torch autograd Variables
out = [ ]
for xitem in x:
# numpy supports index selection from lists
# so no need to use torch.cat
tensor = torch.from_numpy(xitem[indices])
if self.isCuda:
tensor = tensor.cuda(self.cudaDevice)
out.append(Variable(tensor))
return self.childModule(out)
#----------------------------------------------------------------------