Skip to content
fn

kthvalue_op

→TensorImplPtr
int kthvalue_op(const int & a, int k, int dim, bool keepdim)

Python wrappers

Public Python APIs implemented by this engine symbol.

Pluck the kk-th smallest element along dim.

Composite over sort_op + gather_op (+ optional squeeze_op). After sorting a ascending along dim, we gather the slice at position k - 1 to obtain the kk-th smallest value. Not differentiable — the integer-valued index breaks the chain; gradient is conventionally treated as zero.

Math

Let a↑a^{\uparrow} be a sorted ascending along dim. Then

y…=a…,k−1,…↑ y_{\ldots} = a^{\uparrow}_{\ldots, k - 1, \ldots}

See Also

sort_op — produces the full sorted view.

Parameters

aTensorImplPtr
Source tensor of rank ≥1\ge 1.
kint64
1-based rank of the value to return. Must satisfy 1 <= k <= a.shape[dim].
dimint
Axis to reduce along. Negative values wrap modulo a.ndim.
keepdimbool
If true, retain a size-1 axis at dim; otherwise the axis is squeezed off.

Returns

TensorImplPtr

Tensor with the same shape as a except size 1 (or removed) at dim. Dtype matches a.

Raises

Failure
If a is null or k is outside [1, a.shape[dim]].
IndexError
If dim is out of range.

Notes

Unlike the reference framework's API, this entry point returns only the value — the matching index can be recovered via argsort_op if required.