fastpath type Tensor in THPVariable_NewWithVar (#161634)

It is cheap to do an exact check against Tensor and much faster when it works (PyType_IsSubtype does not have this fastpath, I checked [source](9ee0214b5d/Objects/typeobject.c (L2889))). Spot-checked in perf on detach-DTensor-in-a-loop benchmark; small win but clear.

Differential Revision: [D81530101](https://our.internmc.facebook.com/intern/diff/D81530101)
Pull Request resolved: https://github.com/pytorch/pytorch/pull/161634
Approved by: https://github.com/Skylion007, https://github.com/albanD
ghstack dependencies: #161591, #161595, #161633
This commit is contained in:
Scott Wolchok
2025-09-08 11:09:12 -07:00
committed by PyTorch MergeBot
parent a951f435fd
commit eab2afeff7

View File

@ -2111,7 +2111,7 @@ static PyObject* THPVariable_NewWithVar(
std::optional<bool> has_torch_dispatch_if_known) {
// Make sure that the reinterpret into a THPVariable* will be valid
TORCH_CHECK(
PyType_IsSubtype(type, &THPVariableType),
type == &THPVariableType || PyType_IsSubtype(type, &THPVariableType),
"Creating a Tensor subclass from a class ",
"that does not inherit from Tensor is not possible. Make sure your class inherits from Tensor.");