MCPcopy Create free account
hub / github.com/MegEngine/MegEngine / _unpack_indexes

Function _unpack_indexes

imperative/python/src/tensor_utils.cpp:790–895  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

788}
789
790py::tuple _unpack_indexes(py::handle inp_hdl, py::tuple tuple_val) {
791 py::object inp = py::reinterpret_borrow<py::object>(inp_hdl);
792
793 bool use_subtensor = true;
794 bool need_remove_ellipsis = false;
795 bool need_expand_bool_dim = false;
796 size_t idx_ndim = 0;
797 for (size_t i = 0; i < tuple_val.size(); ++i) {
798 py::object k = tuple_val[i];
799 if (k.is_none()) {
800 continue;
801 } else if (k.ptr() == Py_Ellipsis) {
802 need_remove_ellipsis = true;
803 } else {
804 if (is_bool_dtype(k.ptr()) && hasattr(k, "ndim")) {
805 size_t ndim = get_ndim_safe(k).first;
806 idx_ndim += ndim;
807 if (ndim > 1) {
808 need_expand_bool_dim = true;
809 }
810 } else {
811 idx_ndim++;
812 }
813 }
814 }
815 try {
816 size_t inp_ndim = getattr(inp, "ndim").cast<size_t>();
817 if (idx_ndim > inp_ndim) {
818 std::string msg = "too many indices for tensor: tensor is " +
819 std::to_string(inp_ndim) + "-dimensional, but " +
820 std::to_string(idx_ndim) + " were indexed";
821 throw py::index_error(msg.c_str());
822 }
823 } catch (py::error_already_set& err) {
824 ; // ignore
825 }
826 if (need_remove_ellipsis) {
827 tuple_val = _remove_ellipsis(inp, tuple_val);
828 }
829
830 if (need_expand_bool_dim) {
831 py::object shape = getattr(inp, "shape");
832 if (shape.ptr() != Py_None) {
833 py::tuple ret = _expand_bool_dim(inp, tuple_val);
834 inp = ret[0];
835 tuple_val = ret[1];
836 }
837 }
838
839 std::vector<int32_t> axis;
840 for (size_t i = 0; i < tuple_val.size(); ++i) {
841 if (tuple_val[i].is_none()) {
842 axis.push_back(i);
843 }
844 }
845 if (axis.size()) {
846 std::shared_ptr<OpDef> op = AddAxis::make(axis);
847 py::object Op = py::cast(op);

Callers 2

_getitem_cppFunction · 0.85
_setitem_cppFunction · 0.85

Calls 15

is_bool_dtypeFunction · 0.85
get_ndim_safeFunction · 0.85
to_stringFunction · 0.85
_remove_ellipsisFunction · 0.85
_expand_bool_dimFunction · 0.85
castFunction · 0.85
py_applyFunction · 0.85
is_scalarFunction · 0.85
_get_indexFunction · 0.85
pushFunction · 0.85
makeFunction · 0.50
sizeMethod · 0.45

Tested by

no test coverage detected