Skip to content

← Indexing and Selection step 8 of 9

Easy Primitives

Everything above the threshold

Jump to the task

A boolean mask selects the elements whose condition is true. When the mask has the same shape as the input, the result is a one-dimensional tensor.

import torch

x = torch.tensor([[1.0, 5.0], [2.0, 8.0]])
print(x[x > 3.0].tolist())  # [5.0, 8.0]
print(x[x > 0.0].tolist())  # [1.0, 5.0, 2.0, 8.0]
print(x[x > 10.0].tolist()) # []

The values appear in logical row-major order, as if you visited each row from left to right. A value equal to the threshold is excluded because the comparison is strictly greater than.

The output length depends on the values

The input shape is unchanged between these examples, but the number of selected elements differs. Reading with advanced boolean indexing creates a new tensor rather than a view sharing the input's storage.

A variable output length can complicate compiled execution and CUDA graph capture. Behavior depends on the compiler, configuration and backend; a changing count does not universally force a recompile. On CUDA, determining the output size can also require synchronization. Measure the actual workload before drawing performance conclusions from the expression alone.

If you want to keep the original shape and replace unwanted entries, consider where or masked_fill instead. Those perform a different task: they replace values rather than returning a shorter selection.

Your task

def above(x: torch.Tensor, threshold: float) -> torch.Tensor

For the supplied two-dimensional float32 tensor, return a one-dimensional tensor containing only values strictly greater than threshold, in row-major order. Return an empty tensor when no values qualify.

Use at most three tensor operations counted by the harness's TorchDispatchMode. This is a dispatch count, not a timing benchmark or a count of GPU kernels. The starter's scalar loop exceeds that limit.