TensorDictBase.where#
- TensorDictBase.where(condition: Tensor, other: Tensor | TensorDictBase, *, out: TensorDictBase | None = None, pad: int | bool = None, update_batch_size: bool = False) Self#
Returns a tensordict with the leaves where
conditionisTrueandotherelsewhere.torch.where()is applied to every leaf.conditionis aligned with the batch dimensions of each leaf and expanded over its feature dimensions.- Parameters:
condition (Tensor) – a boolean mask over the leading batch dimensions.
other (TensorDictBase, Tensor or Number) – the values to take where
conditionisFalse. A tensordict is paired with the tensordict key by key. On aLazyStackedTensorDict, a tensorotherthat starts with the batch shape up to the stack dimension is split along that dimension, one piece per member, so it must have the stack size there: expand it to the batch shape first. The pieces line up with the leaves as inTensorDictonly for the leaves with as many dims asother; for the others the lazy stack emits aFutureWarning: starting with TensorDict 0.17, the default will change to broadcasting like TensorDict.where, which alignsotherwith each leaf from the right.
- Keyword Arguments:
out (TensorDictBase, optional) – the tensordict to write the result into, which is returned. Defaults to
None, which returns a new tensordict.pad (Number or bool, optional) – the value that stands in for an entry that only one of the tensordict and a tensordict
otherhas. Defaults toNone, which raises aKeyErrorfor such an entry.update_batch_size (bool, optional) – passed to
update()when the result is written intoout. IfTrue, a lazy stackoutgets as many members as the result. Whenotheris not a tensordict, orselfis a lazy stack, anoutwhose batch size is a prefix of the result’s ([]for[2]) keeps it, with aFutureWarning: starting with TensorDict 0.17, the default will change to givingoutthe batch size of the result, asupdate()does. Defaults toFalse.
Examples
>>> import torch >>> from tensordict import TensorDict >>> td = TensorDict(x=torch.ones(2, 3), batch_size=[2]) >>> td.where(torch.tensor([True, False]), 0.0)["x"] tensor([[1., 1., 1.], [0., 0., 0.]]) >>> other = TensorDict(y=torch.zeros(2), batch_size=[2]) >>> sorted(td.where(torch.tensor([True, False]), other, pad=-1).keys()) ['x', 'y']
Every tensordict class and every tensorclass has this method. For the other methods, see Methods by task.