leezu commented on a change in pull request #19685:
URL: https://github.com/apache/incubator-mxnet/pull/19685#discussion_r562242065



##########
File path: tests/python/unittest/test_ffi_container.py
##########
@@ -0,0 +1,72 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+import mxnet
+import numpy as _np
+from mxnet import np, npx, _api_internal
+from mxnet.ndarray import NDArray
+from mxnet.test_utils import use_np
+
+@use_np
+def test_str_map():
+    amap = mxnet._ffi.convert_to_node({"a": 2, "b": 3})
+    assert "a" in amap
+    assert len(amap) == 2
+    dd = dict(amap.items())
+    # TODO add attribute visitor
+    # assert amap["a"].value == 2

Review comment:
       TODO

##########
File path: src/api/_api_internal/_api_internal.cc
##########
@@ -58,15 +59,47 @@ MXNET_REGISTER_GLOBAL("_ADT")
     using namespace runtime;
     std::vector<ObjectRef> data;
     for (int i = 0; i < args.size(); ++i) {
-      if (args[i].type_code() != kNull) {
-        data.push_back(args[i].operator ObjectRef());
+      if (args[i].type_code() == kNDArrayHandle) {
+        mxnet::NDArray *array = args[i].operator mxnet::NDArray*();
+        ObjectRef input = NDArrayHandle(array);
+        data.push_back(input);
+      } else if (args[i].type_code() != kNull) {
+        ObjectRef input = String::CanConvertFrom(args[i]) ? args[i].operator 
String()
+                                                          : args[i].operator 
ObjectRef();
+        data.push_back(input);
       } else {
         data.emplace_back(nullptr);
       }
     }
     *ret = ADT(0, data.begin(), data.end());
 });
 
+MXNET_REGISTER_GLOBAL("_Map")
+.set_body([](runtime::MXNetArgs args, runtime::MXNetRetValue* ret) {
+    using namespace runtime;
+    CHECK_EQ(args.size() % 2, 0);
+    std::unordered_map<ObjectRef, ObjectRef, ObjectHash, ObjectEqual> data;
+    for (int i = 0; i < args.num_args; i += 2) {
+      ObjectRef k =
+          String::CanConvertFrom(args[i]) ? args[i].operator String()
+                                          : args[i].operator ObjectRef();
+      ObjectRef v;
+      if (args[i + 1].type_code() == kNDArrayHandle) {
+        mxnet::NDArray *array = args[i + 1].operator mxnet::NDArray*();
+        v = NDArrayHandle(array);
+      } else {
+        v = args[i + 1];
+      }
+      data.emplace(std::move(k), std::move(v));
+    }
+    *ret = Map<ObjectRef, ObjectRef>(data);
+});
+
+MXNET_REGISTER_GLOBAL("_echo")
+.set_body([](runtime::MXNetArgs args, runtime::MXNetRetValue* ret) {
+  *ret = args[0];
+});

Review comment:
       What is this used for?

##########
File path: python/mxnet/_ffi/_cython/function.pxi
##########
@@ -188,10 +192,35 @@ cdef class FunctionBase:
         FuncCall(self.chandle, args, &ret_val, &ret_tcode)
         return make_ret(ret_val, ret_tcode, args)
 
+cdef object make_packed_func(MXNetFunctionHandle chandle, int is_global):
+    obj = _CLASS_PACKED_FUNC.__new__(_CLASS_PACKED_FUNC)
+    (<FunctionBase>obj).chandle = chandle
+    (<FunctionBase>obj).is_global = is_global
+    return obj
 
-_CLASS_OBJECT = None
+def get_global_func(name, allow_missing=False):
+    cdef MXNetFunctionHandle chandle
+    CALL(MXNetFuncGetGlobal(c_str(name), &chandle))
+    if chandle != NULL:
+        return make_packed_func(chandle, True)
+
+    if allow_missing:
+        return None
 
+    raise ValueError("Cannot find global function %s" % name)
+
+_CLASS_OBJECT = None
+_CLASS_PACKED_FUNC = None
+_FUNC_CONVERT_TO_NODE = None
 
 def _set_class_object(obj_class):
     global _CLASS_OBJECT
     _CLASS_OBJECT = obj_class
+
+def _set_class_packed_func(func_class):
+    global _CLASS_PACKED_FUNC
+    _CLASS_PACKED_FUNC = func_class
+
+def _set_node_generic(func_convert_to_node):
+    global _FUNC_CONVERT_TO_NODE
+    _FUNC_CONVERT_TO_NODE = func_convert_to_node

Review comment:
       Please add some doc. Why is this function called upon import?

##########
File path: python/mxnet/_ffi/_cython/object.pxi
##########
@@ -47,6 +51,29 @@ cdef inline object make_ret_object(void* chandle):
     (<ObjectBase>obj).chandle = chandle
     return obj
 
+class PyNativeObject:
+    """Base class of all MXNet objects that also subclass python's builtin 
types."""

Review comment:
       Which objects are that?

##########
File path: python/setup.py
##########
@@ -81,7 +81,7 @@ def config_cython():
             libraries = ['mxnet']
             # Default paths to libmxnet.so relative to the shared library file 
generated by cython.
             # These precede LD_LIBRARY_PATH.
-            extra_link_args = 
["-Wl,-rpath=$ORIGIN/..:$ORIGIN/../../../lib:$ORIGIN/../../../build"]
+            extra_link_args = 
["-Wl,-rpath,$ORIGIN/..:$ORIGIN/../../../lib:$ORIGIN/../../../build"]

Review comment:
       Do you know why the change is needed?

##########
File path: tests/python/unittest/test_ffi_container.py
##########
@@ -0,0 +1,72 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+import mxnet
+import numpy as _np
+from mxnet import np, npx, _api_internal
+from mxnet.ndarray import NDArray
+from mxnet.test_utils import use_np
+
+@use_np
+def test_str_map():
+    amap = mxnet._ffi.convert_to_node({"a": 2, "b": 3})
+    assert "a" in amap
+    assert len(amap) == 2
+    dd = dict(amap.items())
+    # TODO add attribute visitor
+    # assert amap["a"].value == 2
+    assert "a" in dd
+    assert "b" in dd
+
+@use_np
+def test_string():
+    x = mxnet.container.String("xyz")
+    assert isinstance(x, mxnet.container.String)
+    assert isinstance(x, str)
+    assert x.startswith("xy")
+    assert x + "1" == "xyz1"
+    y = _api_internal._echo(x)
+    assert isinstance(y, mxnet.container.String)
+    assert x.__mxnet_object__.same_as(y.__mxnet_object__)
+    assert x == y
+
+@use_np
+def test_string_adt():
+    s = mxnet.container.String("xyz")
+    arr = mxnet._ffi.convert_to_node([s, s])
+    assert arr[0] == s
+    assert isinstance(arr[0], mxnet.container.String)
+
+# TODO add attribute visitor
+# def test_adt():
+#     a = mxnet._ffi.convert_to_node([1, 2, 3])
+#     assert len(a) == 3
+#     assert a[-1].value == 3
+#     a_slice = a[-3:-1]
+#     assert (a_slice[0].value, a_slice[1].value) == (1, 2)

Review comment:
       Do you intend to add it in this PR?




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
[email protected]


Reply via email to