Skip to content

Commit 5ca99d0

Browse files
crcrparshino16
authored andcommitted
Support torch.square natively (#2329)
1 parent 35340e2 commit 5ca99d0

3 files changed

Lines changed: 27 additions & 2 deletions

File tree

thunder/tests/opinfos.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2192,6 +2192,14 @@ def imag_error_generator(op, device, **kwargs):
21922192
elementwise_unary_ops.append(clone_opinfo)
21932193

21942194

2195+
square_opinfo = OpInfo(
2196+
ltorch.square,
2197+
sample_input_generator=elementwise_unary_generator,
2198+
torch_reference=_elementwise_unary_torch(torch.square),
2199+
)
2200+
elementwise_unary_ops.append(square_opinfo)
2201+
2202+
21952203
# Puts all opinfos into the "opinfos" list
21962204
opinfos.extend(elementwise_unary_ops)
21972205

thunder/torch/__init__.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2248,6 +2248,25 @@ def threshold_(a: TensorProxy, /, threshold: float, value: float) -> TensorLike:
22482248
_inplace_to_out_of_place[threshold_] = threshold, -1
22492249

22502250

2251+
@torchsymbol(torch.square, is_method=True)
2252+
def square(a):
2253+
if isinstance(dtypes.to_dtype(a), dtypes.bool_):
2254+
a = clang.maybe_convert_to_dtype(a, dtypes.int64)
2255+
return a * a
2256+
2257+
2258+
@torchsymbol(torch.square_, is_method=True, tags=(prims.OpTags.IN_PLACE,))
2259+
def square_(a):
2260+
utils.check(
2261+
not isinstance(dtypes.to_dtype(a), dtypes.bool_),
2262+
lambda: f"Result type of {dtypes.int64} cannot be stored into {dtypes.to_dtype(a)}",
2263+
)
2264+
return _copy_(a, square(a))
2265+
2266+
2267+
_inplace_to_out_of_place[square_] = square, -1
2268+
2269+
22512270
#
22522271
# Elementwise binary operations
22532272
#

thunder/torch/default_torch_ops.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,6 @@
252252
torch.split_with_sizes,
253253
torch.split_with_sizes_copy,
254254
torch.spmm,
255-
torch.square,
256255
torch.squeeze_copy,
257256
torch.sspaddmm,
258257
torch.std_mean,
@@ -548,7 +547,6 @@
548547
torch.Tensor.sparse_dim,
549548
torch.Tensor.sparse_mask,
550549
torch.Tensor.split_with_sizes,
551-
torch.Tensor.square,
552550
torch.Tensor.sspaddmm,
553551
torch.Tensor.stft,
554552
torch.Tensor.subtract,

0 commit comments

Comments
 (0)