MCPcopy Create free account
hub / github.com/MegEngine/MegEngine / sort

Function sort

imperative/python/megengine/functional/math.py:613–652  ·  view source on GitHub ↗

r"""Returns sorted tensor and the indices would sort the input tensor. Args: inp: input tensor. The result would be sorted along the given dimension. descending: sort in descending order, where the largest comes first. Default: False dim: which dimension to sort along. D

(inp: Tensor, descending: bool = False, dim: int = -1)

Source from the content-addressed store, hash-verified

611
612
613def sort(inp: Tensor, descending: bool = False, dim: int = -1) -> Tuple[Tensor, Tensor]:
614 r"""Returns sorted tensor and the indices would sort the input tensor.
615
616 Args:
617 inp: input tensor. The result would be sorted along the given dimension.
618 descending: sort in descending order, where the largest comes first. Default: False
619 dim: which dimension to sort along. Default: -1 (last dimension)
620
621 Returns:
622 tuple of two tensors `(sorted_tensor, indices_of_int32)`.
623
624 Examples:
625 >>> import numpy as np
626 >>> x = Tensor(np.array([1,2], dtype=np.float32))
627 >>> out, indices = F.sort(x)
628 >>> out.numpy()
629 array([1., 2.], dtype=float32)
630 """
631 if descending:
632 order = "descending"
633 else:
634 order = "ascending"
635
636 op = builtin.Argsort(order=order)
637
638 transposed = swapaxes(inp, dim, -1)
639 transposed_shape = transposed.shape
640 nrows = transposed_shape[-1]
641 ncols = 1
642 for i in range(len(transposed_shape) - 1):
643 ncols *= transposed_shape[i]
644 reshaped = transposed.reshape(ncols, nrows)
645 tns, ind = apply(op, reshaped)
646
647 def restore(tensor):
648 unreshaped = tensor.reshape(transposed_shape)
649 untransposed = swapaxes(unreshaped, dim, -1)
650 return untransposed
651
652 return restore(tns), restore(ind)
653
654
655def topk(

Callers 15

init_graph_rtFunction · 0.85
init_tensorFunction · 0.85
_expand_dims_cppFunction · 0.85
_squeeze_cppFunction · 0.85
addAxis_grad_ruleFunction · 0.85
removeAxis_grad_ruleFunction · 0.85
makeMethod · 0.85
gpu_usage_timeMethod · 0.85
collectMethod · 0.85
parse_dictFunction · 0.85
parse_dictFunction · 0.85

Calls 4

swapaxesFunction · 0.85
restoreFunction · 0.85
applyFunction · 0.50
reshapeMethod · 0.45

Tested by 9

parse_dictFunction · 0.68
TESTFunction · 0.68
TESTFunction · 0.68
TESTFunction · 0.68
run_topk_testMethod · 0.68
TESTFunction · 0.68
TESTFunction · 0.68
run_permutationFunction · 0.68
run_permutationFunction · 0.68