MCPcopy
hub / github.com/tinygrad/tinygrad / reshape

Method reshape

tinygrad/mixin/movement.py:156–176  ·  view source on GitHub ↗

Returns a tensor with the same data as the original tensor but with a different shape. `shape` can be passed as a tuple or as separate arguments. ```python exec="true" source="above" session="tensor" result="python" t = Tensor.arange(6) print(t.reshape(2, 3).numpy()) ```

(self, shape, *args)

Source from the content-addressed store, hash-verified

154 return self._broadcast_to(new_shape)
155
156 def reshape(self, shape, *args) -> Self:
157 """
158 Returns a tensor with the same data as the original tensor but with a different shape.
159 `shape` can be passed as a tuple or as separate arguments.
160
161 ```python exec="true" source="above" session="tensor" result="python"
162 t = Tensor.arange(6)
163 print(t.reshape(2, 3).numpy())
164 ```
165 """
166 # resolve None and args
167 new_shape = tuple([s if s is not None else self.shape[i] for i, s in enumerate(argfix(shape, *args))])
168 # resolve -1
169 if (c := new_shape.count(-1)) > 1:
170 raise RuntimeError(f"only one dimension can be inferred using -1, getting {new_shape}")
171 if c:
172 new_shape = tuple([-prod(self.shape) // prod(new_shape) if s == -1 else s for s in new_shape])
173 if prod(self.shape) != prod(new_shape):
174 raise ValueError(f"size mismatch, can't reshape ({self.shape}) -> ({new_shape})")
175 ret = self._mop(Ops.RESHAPE, arg=new_shape)
176 return self if ret.shape == self.shape else ret
177
178 def pad(self, arg:tuple[tuple[sint, sint] | None, ...]) -> Self:
179 if self.ndim != len(arg):

Callers 15

_broadcast_toMethod · 0.95
viewMethod · 0.95
squeezeMethod · 0.95
unsqueezeMethod · 0.95
flattenMethod · 0.95
unflattenMethod · 0.95
repeatMethod · 0.95
_make_buffer_viewFunction · 0.80
broadcast_to_inputFunction · 0.80
gradient.pyFile · 0.80
_fromnpFunction · 0.80
_apply_winograd_matrixFunction · 0.80

Calls 4

_mopMethod · 0.95
argfixFunction · 0.90
prodFunction · 0.90
countMethod · 0.45

Tested by 15

test_expandMethod · 0.64
test_reshapeMethod · 0.64
test_as_stridedMethod · 0.64
test_repeat_multidimMethod · 0.64
test_cumsum_2dMethod · 0.64