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
diff --git a/torch/csrc/jit/python/module_python.h b/torch/csrc/jit/python/module_python.h
index 35e2fc5..5c7f269 100644
--- a/torch/csrc/jit/python/module_python.h
+++ b/torch/csrc/jit/python/module_python.h
@@ -9,7 +9,7 @@
 namespace torch {
 namespace jit {
 
-inline c10::optional<Module> as_module(const py::object& obj) {
+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"));
@@ -17,7 +17,11 @@
   return c10::nullopt;
 }
 
-inline c10::optional<Object> as_object(const py::object& obj) {
+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"));