Repository navigation
Expand file tree
/
Copy pathframework.py
More file actions
302 lines (266 loc) · 10.7 KB
/
Copy pathframework.py
File metadata and controls
302 lines (266 loc) · 10.7 KB
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
import keyword
from abc import ABC, abstractmethod
import array_api_extra as xpx
from saps_framework.einsum import reduction_ops
from saps_framework.unfold import (
normalize_pad_width,
normalize_unfold_args,
normalize_unfold_padding,
)
from saps_framework.where_at import WhereAt
class _At:
"""``xpx.at(x, idx)`` with a framework as its namespace."""
def __init__(self, xp, x, idx):
self.xp = xp
self.x = x
self.idx = idx
def set(self, y, /):
return xpx.at(self.x, self.idx).set(y, xp=self.xp)
class Framework(ABC):
# Benchmark Format -> Eager Tensor
@abstractmethod
def from_binsparse(self, array):
pass
# Eager Tensor -> Benchmark Format
@abstractmethod
def to_binsparse(self, array):
pass
# Eager Tensor -> Lazy Tensor
@abstractmethod
def lazy(self, array):
pass
# Lazy Tensor -> Eager Tensor
@abstractmethod
def compute(self, array):
pass
def compile(self, func):
return func
# x[idx] = y as xp.at(x, idx).set(y), which returns the updated array and
# may or may not modify x (see xpx.at). Arrays without __setitem__ are
# updated with where (WhereAt), returning a new array.
def at(self, x, idx, /):
if not hasattr(x, "__setitem__"):
return WhereAt(self, x, idx)
return _At(self, x, idx)
@abstractmethod
def einsum(self, prgm, **kwargs):
pass
def pad_constant(self, x, pad_width, *, fill_value=0):
"""Pad x with ``fill_value``.
``pad_width`` is ``((before_1, after_1), ... (before_N, after_N))``, the
number of values padded to the edges of each of x's N axes, as in
numpy.pad. ``(before, after)`` pads every axis the same way, and an int
``pad`` is a shortcut for ``(pad, pad)``.
"""
pad_width = normalize_pad_width(x.ndim, pad_width)
for axis, (before, after) in enumerate(pad_width):
if before or after:
shape = list(x.shape)
shape[axis] = before
head = self.full(tuple(shape), fill_value, dtype=x.dtype)
shape[axis] = after
tail = self.full(tuple(shape), fill_value, dtype=x.dtype)
x = self.concat([head, x, tail], axis=axis)
return x
def pad_reflect(self, x, pad_width):
"""Pad by mirroring about the edge, which isn't repeated: 2 1|0 1 2 3|2 1."""
pad_width = normalize_pad_width(x.ndim, pad_width)
for axis, (before, after) in enumerate(pad_width):
if before or after:
size = x.shape[axis]
inner = [slice(None)] * x.ndim
inner[axis] = slice(1, size - 1)
# The mirror image repeats 0 1 2 3 2 1 0 1 2 3 2 1 ...
period = self.concat(
[x, self.flip(x[tuple(inner)], axis=axis)], axis=axis
)
x = self._periodic_window(period, axis, -before, size + after)
return x
def pad_edge(self, x, pad_width):
"""Pad by repeating the edge value: 0 0|0 1 2 3|3 3."""
pad_width = normalize_pad_width(x.ndim, pad_width)
for axis, (before, after) in enumerate(pad_width):
if before or after:
size = x.shape[axis]
if size == 0:
raise ValueError("can't pad an empty axis with its edge values")
first = [slice(None)] * x.ndim
first[axis] = slice(0, 1)
last = [slice(None)] * x.ndim
last[axis] = slice(size - 1, size)
x = self.concat(
[x[tuple(first)]] * before + [x] + [x[tuple(last)]] * after,
axis=axis,
)
return x
def pad_wrap(self, x, pad_width):
"""Pad periodically: 2 3|0 1 2 3|0 1."""
pad_width = normalize_pad_width(x.ndim, pad_width)
for axis, (before, after) in enumerate(pad_width):
if before or after:
x = self._periodic_window(x, axis, -before, x.shape[axis] + after)
return x
def _periodic_window(self, x, axis, start, stop):
"""Return positions start:stop along ``axis`` of x repeated end to end."""
period = x.shape[axis]
if period == 0:
raise ValueError("can't pad an empty axis with values from it")
first = start // period
last = -(-stop // period)
index = [slice(None)] * x.ndim
index[axis] = slice(start - first * period, stop - first * period)
return self.concat([x] * (last - first), axis=axis)[tuple(index)]
def _pad(self, x, padding, axes, padding_mode, fill_value):
pad_width = normalize_unfold_padding(x.ndim, padding, axes)
if padding_mode == "constant":
return self.pad_constant(x, pad_width, fill_value=fill_value)
if padding_mode == "reflect":
return self.pad_reflect(x, pad_width)
if padding_mode == "edge":
return self.pad_edge(x, pad_width)
if padding_mode == "wrap":
return self.pad_wrap(x, pad_width)
raise ValueError(
"padding_mode must be 'constant', 'reflect', 'edge' or 'wrap', "
f"got {padding_mode!r}"
)
@abstractmethod
def unfold(self, x, kernel_shape, *, axes=None, strides=None, dilations=None):
"""Return the sliding windows of x.
Each of ``axes`` (default: the last ``len(kernel_shape)``) is replaced by
its number of windows and the kernel axes are appended, so that
``out[..., i, ..., j] = x[..., i * stride + j * dilation, ...]``.
"""
def padded_unfold(
self,
x,
kernel_shape,
*,
axes=None,
strides=None,
dilations=None,
padding=None,
padding_mode="constant",
fill_value=0,
):
"""Pad ``axes`` of x, then unfold them.
``padding`` is a ``(before, after)`` pair for each of ``axes``, one pair
for all of them, or an int ``pad`` for ``(pad, pad)``.
``padding_mode`` is "constant" (with ``fill_value``), "reflect", "edge"
or "wrap". Backends override this to avoid building the padded input.
"""
axes_t, strides_t, dilations_t = normalize_unfold_args(
x.ndim, kernel_shape, axes, strides, dilations
)
x = self._pad(x, padding, axes_t, padding_mode, fill_value)
return self.unfold(
x, kernel_shape, axes=axes_t, strides=strides_t, dilations=dilations_t
)
def conv(
self,
x,
w,
*,
strides=None,
dilations=None,
padding=None,
padding_mode="constant",
fill_value=0,
group=1,
combine="*",
reduce="+",
):
"""Convolve x of shape (N, C, *spatial) with w of shape (M, C / group, *kernel).
Returns shape (N, M, *windows), computed as the einsum
Y[n, g, m, s] reduce= P[n, g, c, s, k] combine W[g, m, c, k]
where x's channels and w's filters are split into ``group`` groups and P
is ``padded_unfold`` of x's spatial axes. ``combine`` and ``reduce`` are
einsum operators, e.g. combine="+", reduce="max".
"""
batch, channels, *spatial_shape = x.shape
out_channels, group_channels, *kernel_shape = w.shape
rank = len(kernel_shape)
if len(spatial_shape) != rank:
raise ValueError("x and w must have the same number of spatial axes")
if channels != group * group_channels or out_channels % group != 0:
raise ValueError(
f"conv with group={group} can't apply weights of shape {w.shape} "
f"to input of shape {x.shape}"
)
x = self.reshape(x, (batch, group, group_channels, *spatial_shape))
patches = self.padded_unfold(
x,
kernel_shape,
axes=tuple(range(3, 3 + rank)),
strides=strides,
dilations=dilations,
padding=padding,
padding_mode=padding_mode,
fill_value=fill_value,
)
w = self.reshape(
w, (group, out_channels // group, group_channels, *kernel_shape)
)
windows = ",".join(f"s{i}" for i in range(rank))
kernel = ",".join(f"k{i}" for i in range(rank))
p = f"P[n,g,c,{windows},{kernel}]"
q = f"W[g,m,c,{kernel}]"
# Name operators like "max" are calls; symbols, "and" and "or" are infix.
if combine.isidentifier() and not keyword.iskeyword(combine):
expr = f"{combine}({p}, {q})"
else:
expr = f"{p} {combine} {q}"
y = self.einsum(f"Y[n,g,m,{windows}] {reduce}= {expr}", P=patches, W=w)
return self.reshape(y, (batch, out_channels, *y.shape[3:]))
def pool(
self,
x,
kernel_shape,
*,
reduce,
strides=None,
dilations=None,
padding=None,
padding_mode="constant",
fill_value=0,
):
"""Reduce each window of x of shape (N, C, *spatial) to shape (N, C, *windows).
``reduce`` is an einsum reduction such as "max", "+" or "mean". Padding
is reduced like any other value, so max pooling usually wants a
``fill_value`` below every input.
"""
if x.ndim != len(kernel_shape) + 2:
raise ValueError(
f"pool over kernel_shape {tuple(kernel_shape)} needs an input of "
f"rank {len(kernel_shape) + 2}, got rank {x.ndim}"
)
reduce_op = getattr(self, reduction_ops[reduce])
patches = self.padded_unfold(
x,
kernel_shape,
axes=tuple(range(2, x.ndim)),
strides=strides,
dilations=dilations,
padding=padding,
padding_mode=padding_mode,
fill_value=fill_value,
)
return reduce_op(patches, axis=tuple(range(x.ndim, patches.ndim)))
def topk(self, x, k, *, axis=-1, largest=True):
"""Return the k largest (or, with largest=False, smallest) entries of x
along axis, in order, and their indices, like torch.topk. Ties come in
index order.
Backends override this to avoid sorting every entry.
"""
order = self.argsort(-x if largest else x, axis=axis, stable=True)
indices = self.take(order, self.arange(k), axis=axis)
return self.take_along_axis(x, indices, axis=axis), indices
@abstractmethod
def replace(self, arr, old, new):
"""Return an array with every occurrence of scalar old replaced by new.
Includes implicit sparse values and treats NaN as matching NaN.
The input is not modified.
"""
@abstractmethod
def __getattr__(self, name):
pass