mirror of
https://github.com/zebrajr/pytorch.git
synced 2025-12-07 12:21:27 +01:00
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
34 lines
826 B
C++
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
|