torch.is_nonzero
function is_nonzero(input: {
numel(): number;
device: string;
storage: Float32Array | Int32Array | null;
}): booleanChecks if a single-element tensor contains a non-zero value.
Evaluates whether a tensor with exactly one element is non-zero. Primarily used in control flow where tensor values need boolean conversion. This is important because directly using a tensor as a boolean is ambiguous (should it check if any element is non-zero, or if all are?).
Requirements:
- Input must have exactly one element (numel() === 1)
- Returns true if that element != 0
- Returns false if that element == 0
Common Uses:
- Conditional execution based on tensor value
- Converting scalar tensors to Python/JS booleans
- Testing in control flow statements
- Size checking: Throws error if not exactly 1 element
- Device support: Currently only works with CPU tensors
- Type agnostic: Works with any numeric dtype
- Synchronous: Returns value immediately (CPU only)
- GPU limitation: Not yet implemented for WebGPU tensors
- Single element required: Will error on multi-element tensors
Parameters
input{ numel(): number; device: string; storage: Float32Array | Int32Array | null; }- Single-element tensor to evaluate
Returns
boolean– true if the tensor's value is non-zero, false if zeroExamples
// Check if scalar tensor is non-zero
const scalar = torch.tensor(5);
if (torch.is_nonzero(scalar)) {
console.log('Non-zero'); // Prints
}
// Zero tensor
const zero = torch.tensor(0);
if (!torch.is_nonzero(zero)) {
console.log('Is zero'); // Prints
}
// Result of comparison is non-zero
const result = torch.tensor(3) > torch.tensor(2); // true → 1
torch.is_nonzero(result); // true
// Error: more than one element
const multi = torch.tensor([1, 2, 3]);
torch.is_nonzero(multi); // Error: requires single elementSee Also
- PyTorch torch.is_nonzero()
- Tensor.item - Get scalar value from single-element tensor
- Tensor.numel - Get total number of elements