|
| 1 | +from numpy.core.numeric import normalize_axis_tuple |
| 2 | + |
| 3 | +import dpctl |
| 4 | +import dpctl.tensor as dpt |
| 5 | +import dpctl.tensor._tensor_impl as ti |
| 6 | + |
| 7 | + |
| 8 | +# can be refactored later into general reduction |
| 9 | +def _boolean_reduction(x, axis, keepdims, func): |
| 10 | + if not isinstance(x, dpt.usm_ndarray): |
| 11 | + raise TypeError(f"Expected dpctl.tensor.usm_ndarray, got {type(x)}") |
| 12 | + |
| 13 | + nd = x.ndim |
| 14 | + if axis is None: |
| 15 | + axis = tuple(range(nd)) |
| 16 | + if not isinstance(axis, (tuple, list)): |
| 17 | + axis = (axis,) |
| 18 | + axis = normalize_axis_tuple(axis, nd, "axis") |
| 19 | + |
| 20 | + exec_q = x.sycl_queue |
| 21 | + res_usm_type = x.usm_type |
| 22 | + |
| 23 | + red_nd = len(axis) |
| 24 | + if red_nd == 0: |
| 25 | + return dpt.astype(x, dpt.bool) |
| 26 | + |
| 27 | + perm = [i for i in range(nd) if i not in axis] + list(axis) |
| 28 | + x_tmp = dpt.permute_dims(x, perm) |
| 29 | + res_shape = x_tmp.shape[: nd - red_nd] |
| 30 | + |
| 31 | + wait_list = [] |
| 32 | + res_tmp = dpt.empty( |
| 33 | + res_shape, |
| 34 | + dtype=dpt.int32, |
| 35 | + usm_type=res_usm_type, |
| 36 | + sycl_queue=exec_q, |
| 37 | + ) |
| 38 | + hev0, ev0 = func( |
| 39 | + src=x_tmp, |
| 40 | + trailing_dims_to_reduce=red_nd, |
| 41 | + dst=res_tmp, |
| 42 | + sycl_queue=exec_q, |
| 43 | + ) |
| 44 | + wait_list.append(hev0) |
| 45 | + |
| 46 | + # copy to boolean result array |
| 47 | + res = dpt.empty( |
| 48 | + res_shape, |
| 49 | + dtype=dpt.bool, |
| 50 | + usm_type=res_usm_type, |
| 51 | + sycl_queue=exec_q, |
| 52 | + ) |
| 53 | + hev1, _ = ti._copy_usm_ndarray_into_usm_ndarray( |
| 54 | + src=res_tmp, dst=res, sycl_queue=exec_q, depends=[ev0] |
| 55 | + ) |
| 56 | + wait_list.append(hev1) |
| 57 | + |
| 58 | + if keepdims: |
| 59 | + res_shape = res_shape + (1,) * red_nd |
| 60 | + inv_perm = sorted(range(nd), key=lambda d: perm[d]) |
| 61 | + res = dpt.permute_dims(dpt.reshape(res, res_shape), inv_perm) |
| 62 | + dpctl.SyclEvent.wait_for(wait_list) |
| 63 | + |
| 64 | + return res |
| 65 | + |
| 66 | + |
| 67 | +def all(x, axis=None, out=None, keepdims=False): |
| 68 | + return _boolean_reduction(x, axis, keepdims, ti._all) |
| 69 | + |
| 70 | + |
| 71 | +def any(x, axis=None, keepdims=False): |
| 72 | + return _boolean_reduction(x, axis, keepdims, ti._any) |
0 commit comments