pytorch/torch/csrc/jit/python/module_python.h
Peter Bell f125bd2cbb Support torch.ScriptObject in torch::jit::as_object (#84398)
When a torchbind class is returned from an operator, it has the class
`torch.ScriptObject`, yet the `torch.ops` interface checks against
`torch.jit.RecursiveScriptClass` or else falls back to a much slower
path that doesn't return the original c++ object.

On my machine I see a 2 us performance improvement when calling a
`torch.ops` function with a `ScriptObject` argument.
Pull Request resolved: https://github.com/pytorch/pytorch/pull/84398
Approved by: https://github.com/ezyang
2022-09-06 15:00:52 +00:00

34 lines
826 B
C++

#pragma once
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <torch/csrc/jit/api/module.h>
#include <torch/csrc/utils/pybind.h>
namespace py = pybind11;
namespace torch {
namespace jit {
inline c10::optional<Module> as_module(py::handle obj) {
if (py::isinstance(
obj, py::module::import("torch.jit").attr("ScriptModule"))) {
return py::cast<Module>(obj.attr("_c"));
}
return c10::nullopt;
}
inline c10::optional<Object> as_object(py::handle obj) {
if (py::isinstance(obj, py::module::import("torch").attr("ScriptObject"))) {
return py::cast<Object>(obj);
}
if (py::isinstance(
obj, py::module::import("torch.jit").attr("RecursiveScriptClass"))) {
return py::cast<Object>(obj.attr("_c"));
}
return c10::nullopt;
}
} // namespace jit
} // namespace torch