forked from data-apis/array-api-compat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__init__.py
85 lines (78 loc) · 1.78 KB
/
__init__.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
from jax.numpy import (
# Constants
e,
inf,
nan,
pi,
newaxis,
# Dtypes
bool,
float32,
float64,
int8,
int16,
int32,
int64,
uint8,
uint16,
uint32,
uint64,
complex64,
complex128,
iinfo,
finfo,
can_cast,
result_type,
# functions
zeros,
all,
any,
isnan,
isfinite,
reshape
)
from jax.numpy import (
asarray,
s_,
int_,
argpartition,
take_along_axis
)
def top_k(
x,
k,
/,
axis=None,
*,
largest=True,
):
# The largest keyword can't be implemented with `jax.lax.top_k`
# efficiently so am using `jax.numpy` for now
if k <= 0:
raise ValueError(f'k(={k}) provided must be positive.')
positive_axis: int
_arr = asarray(x)
if axis is None:
arr = _arr.ravel()
positive_axis = 0
else:
arr = _arr
positive_axis = axis if axis > 0 else axis % arr.ndim
slice_start = (s_[:],) * positive_axis
if largest:
indices_array = argpartition(arr, -k, axis=axis)
slice = slice_start + (s_[-k:],)
topk_indices = indices_array[slice]
else:
indices_array = argpartition(arr, k-1, axis=axis)
slice = slice_start + (s_[:k],)
topk_indices = indices_array[slice]
topk_indices = topk_indices.astype(int_)
topk_values = take_along_axis(arr, topk_indices, axis=axis)
return (topk_values, topk_indices)
__all__ = ['top_k', 'e', 'inf', 'nan', 'pi', 'newaxis', 'bool',
'float32', 'float64', 'int8', 'int16', 'int32',
'int64', 'uint8', 'uint16', 'uint32', 'uint64',
'complex64', 'complex128', 'iinfo', 'finfo',
'can_cast', 'result_type', 'zeros', 'all', 'isnan',
'isfinite', 'reshape', 'any']