-
Notifications
You must be signed in to change notification settings - Fork 204
/
Copy pathpytorch_bindings.py
179 lines (142 loc) · 6.78 KB
/
pytorch_bindings.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
from typing import List
from tigre.utilities.geometry import Geometry
import torch
import tigre
import numpy as np
import itertools
class AXFunction(torch.autograd.Function):
@staticmethod
def forward(
volume_input:torch.Tensor,
geo : Geometry,
gpuids : List[str],
volume_dimension : List,
sinogram_dimension : List
) -> torch.Tensor:
"""AXFunction is an autograd function that performs a forward operation
and preserves the gradients.
Args:
volume_input (torch.Tensor): input volume tensor
geo (Geometry): geometry
gpuids (List[str]): gpus on which to perform the computations
volume_dimension (List): integers describing the volume dimension
sinogram_dimension (List): integers describing the volume dimension
Returns:
torch.Tensor: sinogram
"""
device = volume_input.device
### Might be good to add a check
extra_dimensions = len(volume_input.size()) - 3
extra_dims = list(volume_input.size()[:extra_dimensions])
sinogram_output = volume_input.new_empty((extra_dims + sinogram_dimension), dtype=torch.float32) # type:ignore
volume_input = volume_input.detach().cpu().numpy()
for subspace in itertools.product(*[range(dim_size) for dim_size in extra_dims]):
sinogram_output[subspace] = torch.from_numpy(
tigre.Ax(volume_input[subspace],geo, geo.angles, gpuids = gpuids)).to(device)
return sinogram_output
@staticmethod
def setup_context(ctx, inputs, output):
input, geo, gpuids, volume_dimension, sinogram_dimension = inputs
ctx.geo = geo
ctx.volume_dimension = volume_dimension
ctx.gpuids = gpuids
@staticmethod
def backward(ctx, grad_output:torch.Tensor): #type:ignore
device = grad_output.device
extra_dimensions = len(grad_output.size()) - 3
extra_dims = list(grad_output.size()[:extra_dimensions])
volume_output = grad_output.new_empty((extra_dims + ctx.volume_dimension), dtype=torch.float32) # type:ignore
grad_output : np.ndarray = grad_output.detach().cpu().numpy()
for subspace in itertools.product(*[range(dim_size) for dim_size in extra_dims]):
volume_output[subspace] = torch.from_numpy(
tigre.Atb(grad_output[subspace], ctx.geo, ctx.geo.angles, gpuids = ctx.gpuids)).to(device)
return volume_output, None, None, None, None
class A(torch.nn.Module):
def __init__(self, geo:Geometry, angles, gpuids:List[str]):
super(A, self).__init__()
geo.angles = angles
self.geo = geo
self.gpuids = gpuids
self.volume_dimension = geo.nVoxel.tolist()
self.sinogram_dimension = [len(geo.angles)] + geo.nDetector.tolist()
def forward(self, x:torch.Tensor):
return AXFunction.apply(x, self.geo, self.gpuids, self.volume_dimension, self.sinogram_dimension)
class ATBFunction(torch.autograd.Function):
@staticmethod
def forward(
sinogram_input:torch.Tensor,
geo : Geometry,
gpuids : List[str],
volume_dimension : List,
sinogram_dimension : List
) -> torch.Tensor:
"""AXFunction is an autograd function that performs a forward operation
and preserves the gradients.
Args:
sinogram_input (torch.Tensor): input sinogram tensor
geo (Geometry): geometry
gpuids (List[str]): gpus on which to perform the computations
volume_dimension (List): integers describing the volume dimension
sinogram_dimension (List): integers describing the volume dimension
Returns:
torch.Tensor: volume
"""
device = sinogram_input.device
### Might be good to add a check
extra_dimensions = len(sinogram_input.size()) - 3
extra_dims = list(sinogram_input.size()[:extra_dimensions])
volume_output = sinogram_input.new_empty((extra_dims + volume_dimension), dtype=torch.float32) # type:ignore
sinogram_input = sinogram_input.detach().cpu().numpy()
for subspace in itertools.product(*[range(dim_size) for dim_size in extra_dims]):
volume_output[subspace] = torch.from_numpy(
tigre.Atb(sinogram_input[subspace],geo, geo.angles, gpuids = gpuids)).to(device)
return volume_output
@staticmethod
def setup_context(ctx, inputs, output):
input, geo, gpuids, volume_dimension, sinogram_dimension = inputs
ctx.geo = geo
ctx.sinogram_dimension = sinogram_dimension
ctx.gpuids = gpuids
@staticmethod
def backward(ctx, grad_output:torch.Tensor): #type:ignore
device = grad_output.device
extra_dimensions = len(grad_output.size()) - 3
extra_dims = list(grad_output.size()[:extra_dimensions])
sinogram_output = grad_output.new_empty((extra_dims + ctx.sinogram_dimension), dtype=torch.float32) # type:ignore
grad_output : np.ndarray = grad_output.detach().cpu().numpy()
for subspace in itertools.product(*[range(dim_size) for dim_size in extra_dims]):
sinogram_output[subspace] = torch.from_numpy(
tigre.Ax(grad_output[subspace], ctx.geo, ctx.geo.angles, gpuids = ctx.gpuids)).to(device)
return sinogram_output, None, None, None, None
class At(torch.nn.Module):
def __init__(self, geo:Geometry, angles:np.array, gpuids:List[str]):
super(At, self).__init__()
geo.angles = angles
self.geo = geo
self.gpuids = gpuids
self.volume_dimension = geo.nVoxel.tolist()
self.sinogram_dimension = [len(geo.angles)] + geo.nDetector.tolist()
def forward(self, x:torch.Tensor):
return ATBFunction.apply(x, self.geo, self.gpuids, self.volume_dimension, self.sinogram_dimension)
def create_pytorch_operator(geo, angles, gpuids=None):
if gpuids is None:
gpuids = [str(i) for i in range(torch.cuda.device_count())]
return A(geo, angles, gpuids), At(geo, angles, gpuids)
## This may be useful for non-torch stuff, but doesn't work for torch autograd.
# I'll leave it here for now.
class Operator:
def __init__(self, geo, angles, gpuids):
super(Operator, self).__init__()
self.geo = geo
self.angles = angles
self.gpuids = gpuids
self.ax = A(self.geo, self.angles, self.gpuids)
self.atb = At(self.geo, self.angles, self.gpuids)
def __call__(self, x):
return self.forward(x)
def forward(self, x):
return self.ax(x)
def T(self,b):
return self.backward(b)
def backward(self, b):
return self.atb(b)