Skip to content

← Tensor Foundations step 6 of 7

Medium Framework

Masked Fill

A mask selects which tensor entries to replace. Here, true means replace with a supplied scalar; false means keep the original value.

Your task

Implement masked_fill(x, mask, fill_value).

  • x is a floating-point tensor of any shape.
  • mask has exactly the same shape. Test inputs contain 0.0 and 1.0; convert these to boolean values before using them as a condition.
  • fill_value is a scalar replacement value, not a tensor to broadcast.

Return a tensor with the same shape and dtype as x, leaving both inputs unchanged. Apply this rule independently to each entry:

output[index] = fill_value if mask[index] is true else x[index]

For x=[[1, 2], [3, 4]], mask=[[0, 1], [1, 0]] and fill_value=-1, return [[1, -1], [-1, 4]]. Keep all positions in the output; do not gather only the selected entries.

An all-false mask keeps every value. An all-true mask replaces every value. For an empty input, return an empty tensor of the same shape.

Applying the mask

torch.where(condition, fill_value, x) and jnp.where(condition, fill_value, x) select the replacement when the condition is true. PyTorch's nonmutating x.masked_fill(condition, fill_value) also implements this rule. Pass the converted boolean mask as condition.

Multiplying x by a mask is a different operation: it cannot insert an arbitrary replacement value. Also check the mask convention when using this operation elsewhere; some APIs use true to mean keep rather than replace.