Skip to content

← Dtypes and Numerics step 2 of 6

Easy Primitives

Counting with the wrong operator

Jump to the task

Adding two boolean tensors produces another boolean tensor. It tells you whether either input is true, rather than how many inputs are true.

import torch

a = torch.tensor([True, True, False])
b = torch.tensor([True, False, False])
print((a + b).tolist())  # [True, True, False]

The desired counts would be [2, 1, 0]. Once the addition has reduced two true values to one boolean, casting the result to an integer cannot recover the count.

Count before information is lost

Convert the masks to integers before adding, or stack them and sum over the new axis. By default, summing a boolean tensor produces int64 counts.

print((a.int() + b.int()).tolist())             # [2, 1, 0]
print(torch.stack([a, b]).sum(dim=0).tolist())   # [2, 1, 0]

Stacking creates a combined tensor, so it uses additional memory. Integer addition is another valid approach; choose based on the surrounding code and input size. Both approaches must preserve the count at each position.

For boolean logic, use & for elementwise AND, | for OR, ^ for XOR and ~ for NOT. These express logical intent more clearly than boolean addition. This behavior concerns PyTorch boolean tensors; Python's True + True produces the integer 2.

Your task

def count_true(masks: list) -> torch.Tensor

Given a nonempty list of one-dimensional boolean tensors with the same shape, return an integer tensor of that shape. Each output position counts how many input masks are true there. A single mask must also produce integer counts, not a boolean result.