MCPcopy
hub / github.com/tinygrad/tinygrad / NonZero

Function NonZero

tinygrad/nn/onnx.py:1130–1138  ·  view source on GitHub ↗
(x:Tensor)

Source from the content-addressed store, hash-verified

1128
1129 # ***** Indexing Ops *****
1130 def NonZero(x:Tensor):
1131 mask = (x!=0).flatten()
1132 flat_idx = Tensor.arange(mask.numel(), dtype=dtypes.int64, device=x.device).masked_select(mask)
1133 if flat_idx.ndim == 0: flat_idx = flat_idx.reshape(1)
1134 if x.ndim == 0:
1135 return Tensor.zeros((0, flat_idx.shape[0]), dtype=dtypes.int64, device=x.device)
1136 strides = [prod(int(s) for s in x.shape[i+1:]) if i+1 < x.ndim else 1 for i in range(x.ndim)]
1137 coords = [((flat_idx // stride) % int(dim)) for stride, dim in zip(strides, x.shape)]
1138 return Tensor.stack(*coords, dim=0)
1139
1140 def ArrayFeatureExtractor(x:Tensor, indices:Tensor): return x[..., indices]
1141

Callers

nothing calls this directly

Calls 8

prodFunction · 0.90
flattenMethod · 0.80
masked_selectMethod · 0.80
arangeMethod · 0.80
numelMethod · 0.80
reshapeMethod · 0.80
zerosMethod · 0.80
stackMethod · 0.80

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…