[math] Trace float.fromhex (#156976)

Pull Request resolved: https://github.com/pytorch/pytorch/pull/156976
Approved by: https://github.com/zou3519
ghstack dependencies: #156975, #156977
This commit is contained in:
Guilherme Leobas
2025-07-22 14:32:05 -03:00
committed by PyTorch MergeBot
parent f5314f89c8
commit 576253c476
5 changed files with 21 additions and 0 deletions

View File

@ -132,6 +132,7 @@ from ..utils import (
get_locals_to_steal,
get_static_address_type,
is_frozen_dataclass,
is_function,
is_function_or_wrapper,
is_invoke_subgraph,
is_lru_cache_wrapped_function,
@ -161,6 +162,7 @@ from .base import (
VariableTracker,
VariableTrackerMeta,
)
from .builtin import BuiltinVariable
from .constant import ConstantVariable, EnumVariable
from .ctx_manager import (
AutocastModeVariable,
@ -1223,6 +1225,12 @@ class VariableBuilder:
) and BuiltinMethodVariable.is_supported_builtin_method(value):
self.install_guards(GuardBuilder.ID_MATCH)
return BuiltinMethodVariable(value, source=self.source)
elif is_function(value) and value in (float.fromhex, float.hex):
self.install_guards(GuardBuilder.ID_MATCH)
return GetAttrVariable(
BuiltinVariable(float, source=self.source),
value.__name__,
)
elif is_function_or_wrapper(value):
value, attr_name = unwrap_with_attr_name_if_wrapper(value)
# For these wrappers, Dynamo points to the wrapped function,

View File

@ -1271,6 +1271,19 @@ class BuiltinVariable(VariableTracker):
args[1:],
)
if self.fn is float and len(args) == 1 and name in ("fromhex", "hex"):
if isinstance(args[0], ConstantVariable):
try:
fn = getattr(float, name)
res = fn(args[0].as_python_constant())
return variables.ConstantVariable.create(res)
except (OverflowError, ValueError) as e:
raise_observed_exception(
type(e),
tx,
args=list(map(ConstantVariable.create, e.args)),
)
if self.fn is object and name == "__init__":
# object.__init__ is a no-op
return variables.ConstantVariable(None)