# Buggy code
def _calc_results(self, session_id, graph_key, graph, context_dict, chunk_targets):
    _, op_name = concat_operand_keys(graph, "_")

    logger.debug("Start calculating operand %s in %s.", graph_key, self.uid)
    start_time = time.time()

    for chunk in graph:
        for inp, prepare_inp in zip(chunk.inputs, chunk.op.prepare_inputs):
            if not prepare_inp:
                context_dict[inp.key] = None

    local_context_dict = DistributedDictContext(
        self.get_scheduler(self.default_uid()),
        session_id,
        actor_ctx=self.ctx,
        address=self.address,
        n_cpu=self._get_n_cpu(),
    )
    local_context_dict["_actor_cls"] = type(self)
    local_context_dict["_actor_uid"] = self.uid
    local_context_dict["_op_key"] = graph_key
    local_context_dict.update(context_dict)
    context_dict.clear()

    if self._execution_ref:
        self._execution_ref.deallocate_scheduler_resource(
            session_id, graph_key, delay=0.5, _tell=True, _wait=False
        )

    # start actual execution
    executor = Executor(storage=local_context_dict)
    with EventContext(
        self._events_ref,
        EventCategory.PROCEDURE,
        EventLevel.NORMAL,
        self._calc_event_type,
        self.uid,
    ):
        self._execution_pool.submit(
            executor.execute_graph, graph, chunk_targets, retval=False
        ).result()

    end_time = time.time()

    # collect results
    result_keys = []
    result_values, result_sizes, result_shapes = [], [], []
    collected_chunk_keys = set()
    for k in list(local_context_dict.keys()):
        v = local_context_dict[k]
        if isinstance(k, tuple):
            k = tuple(to_str(i) for i in k)
        else:
            k = to_str(k)

        chunk_key = get_chunk_key(k)
        if chunk_key in chunk_targets:
            result_keys.append(k)
            result_values.append(dataserializer.serialize(v))
            result_sizes.append(result_values[-1].total_bytes)
            result_shapes.append(getattr(v, "shape", None))
            collected_chunk_keys.add(chunk_key)

        local_context_dict.pop(k)

    # check if all targets generated
    if any(k not in collected_chunk_keys for k in chunk_targets):
        raise KeyError([k for k in chunk_targets if k not in collected_chunk_keys])

    # adjust sizes in allocation
    apply_allocs = defaultdict(lambda: 0)
    for k, size in zip(result_keys, result_sizes):
        apply_allocs[get_chunk_key(k)] += size

    apply_alloc_quota_keys, apply_alloc_sizes = [], []
    for k, v in apply_allocs.items():
        apply_alloc_quota_keys.append(
            build_quota_key(session_id, k, owner=self.proc_id)
        )
        apply_alloc_sizes.append(v)
    self._mem_quota_ref.alter_allocations(
        apply_alloc_quota_keys, apply_alloc_sizes, _tell=True, _wait=False
    )
    self._mem_quota_ref.hold_quotas(apply_alloc_quota_keys, _tell=True)

    if self._status_ref:
        self._status_ref.update_mean_stats(
            "calc_speed." + op_name,
            sum(apply_alloc_sizes) * 1.0 / (end_time - start_time),
            _tell=True,
            _wait=False,
        )

    return self.storage_client.put_objects(
        session_id,
        result_keys,
        result_values,
        [self._calc_intermediate_device],
        sizes=result_sizes,
        shapes=result_shapes,
    ).then(lambda *_: result_keys)


# Traceback (AttributeError)
AttributeError                            Traceback (most recent call last)
<ipython-input-3-a85925f048d0> in <module>
1 start=time.time()
2 df_mars=df_mars.to_gpu()
----> 3 print(df_mars.sum().to_frame(name="sum").execute())

/opt/conda/envs/rapids/lib/python3.6/site-packages/mars/core.py in execute(self, session, **kw)
580
581     def execute(self, session=None, **kw):
--> 582         self._data.execute(session, **kw)
583         return self
584

/opt/conda/envs/rapids/lib/python3.6/site-packages/mars/core.py in execute(self, session, **kw)
368
369         # no more fetch, thus just fire run
--> 370         session.run(self, **kw)
371         # return Tileable or ExecutableTuple itself
372         return self

/opt/conda/envs/rapids/lib/python3.6/site-packages/mars/session.py in run(self, *tileables, **kw)
460         tileables = tuple(mt.tensor(t) if not isinstance(t, (Entity, Base)) else t
461                           for t in tileables)
--> 462         result = self._sess.run(*tileables, **kw)
463
464         for t in tileables:

/opt/conda/envs/rapids/lib/python3.6/site-packages/mars/session.py in run(self, *tileables, **kw)
105             # set number of running cores
106             self.context.set_ncores(kw['n_parallel'])
--> 107             res = self._executor.execute_tileables(tileables, **kw)
108             return res
109

/opt/conda/envs/rapids/lib/python3.6/site-packages/mars/utils.py in _wrapped(*args, **kwargs)
406                 _kernel_mode.eager = False
407             _kernel_mode.eager_count = enter_eager_count + 1
--> 408             return func(*args, **kwargs)
409         finally:
410             _kernel_mode.eager_count -= 1

/opt/conda/envs/rapids/lib/python3.6/site-packages/mars/utils.py in inner(*args, **kwargs)
500     def inner(*args, **kwargs):
501         with build_mode():
--> 502             return func(*args, **kwargs)
503     return inner
504

/opt/conda/envs/rapids/lib/python3.6/site-packages/mars/executor.py in execute_tileables(self, tileables, fetch, n_parallel, n_thread, print_progress, mock, compose, name)
878                                    n_parallel=n_parallel or n_thread,
879                                    print_progress=print_progress, mock=mock,
--> 880                                    chunk_result=chunk_result)
881
882                 # update shape of tileable and its chunks whatever it's successful or not

/opt/conda/envs/rapids/lib/python3.6/site-packages/mars/executor.py in execute_graph(self, graph, keys, n_parallel, print_progress, mock, no_intermediate, compose, retval, chunk_result)
688             print_progress=print_progress, mock=mock, mock_max_memory=self._mock_max_memory,
689             fetch_keys=fetch_keys, no_intermediate=no_intermediate)
--> 690         res = graph_execution.execute(retval)
691         self._mock_max_memory = max(self._mock_max_memory, graph_execution._mock_max_memory)
692         if mock:

/opt/conda/envs/rapids/lib/python3.6/site-packages/mars/executor.py in execute(self, retval)
569         # wait until all the futures completed
570         for future in executed_futures:
--> 571             future.result()
572
573         if retval:

/opt/conda/envs/rapids/lib/python3.6/concurrent/futures/_base.py in result(self, timeout)
423                 raise CancelledError()
424             elif self._state == FINISHED:
--> 425                 return self.__get_result()
426
427             self._condition.wait(timeout)

/opt/conda/envs/rapids/lib/python3.6/concurrent/futures/_base.py in __get_result(self)
382     def __get_result(self):
383         if self._exception:
--> 384             raise self._exception
385         else:
386             return self._result

/opt/conda/envs/rapids/lib/python3.6/concurrent/futures/thread.py in run(self)
54
55         try:
---> 56             result = self.fn(*self.args, **self.kwargs)
57         except BaseException as exc:
58             self.future.set_exception(exc)

/opt/conda/envs/rapids/lib/python3.6/site-packages/mars/executor.py in _execute_operand(self, op)
441             # so we pass the first operand's first output to Executor.handle
442             first_op = ops[0]
--> 443             Executor.handle(first_op, results, self._mock)
444
445             # update maximal memory usage during execution

/opt/conda/envs/rapids/lib/python3.6/site-packages/mars/executor.py in handle(cls, op, results, mock)
639                 # The `UFuncTypeError` was introduced by numpy#12593 since v1.17.0.
640                 try:
--> 641                     return runner(results, op)
642                 except UFuncTypeError as e:
643                     raise TypeError(str(e)).with_traceback(sys.exc_info()[2]) from None

/opt/conda/envs/rapids/lib/python3.6/site-packages/mars/dataframe/reduction/core.py in execute(cls, ctx, op)
405                 cls._execute_agg(ctx, op)
406             elif op.stage == OperandStage.map:
--> 407                 cls._execute_map(ctx, op)
408             else:
409                 in_data = ctx[op.inputs[0].key]

/opt/conda/envs/rapids/lib/python3.6/site-packages/mars/dataframe/reduction/core.py in _execute_map(cls, ctx, op)
380             cls._execute_map_with_count(ctx, op)
381         else:
--> 382             cls._execute_without_count(ctx, op)
383
384     @classmethod

/opt/conda/envs/rapids/lib/python3.6/site-packages/mars/dataframe/reduction/core.py in _execute_without_count(cls, ctx, op, reduction_func)
370                 # cannot just do xdf.DataFrame(r).T
371                 # cuz the dtype will be object since pandas 1.0
--> 372                 df = xdf.DataFrame(OrderedDict((d, [v]) for d, v in r.iteritems()))
373             else:
374                 df = xdf.DataFrame(r)

AttributeError: 'Series' object has no attribute 'iteritems'

# Fixed code
def _calc_results(self, session_id, graph_key, graph, context_dict, chunk_targets):
    _, op_name = concat_operand_keys(graph, "_")

    logger.debug("Start calculating operand %s in %s.", graph_key, self.uid)
    start_time = time.time()

    for chunk in graph:
        for inp, prepare_inp in zip(chunk.inputs, chunk.op.prepare_inputs):
            if not prepare_inp:
                context_dict[inp.key] = None

    local_context_dict = DistributedDictContext(
        self.get_scheduler(self.default_uid()),
        session_id,
        actor_ctx=self.ctx,
        address=self.address,
        n_cpu=self._get_n_cpu(),
    )
    local_context_dict["_actor_cls"] = type(self)
    local_context_dict["_actor_uid"] = self.uid
    local_context_dict["_op_key"] = graph_key
    local_context_dict.update(context_dict)
    context_dict.clear()

    if self._execution_ref:
        self._execution_ref.deallocate_scheduler_resource(
            session_id, graph_key, delay=0.5, _tell=True, _wait=False
        )

    # start actual execution
    executor = Executor(storage=local_context_dict)
    with EventContext(
        self._events_ref,
        EventCategory.PROCEDURE,
        EventLevel.NORMAL,
        self._calc_event_type,
        self.uid,
    ):
        self._execution_pool.submit(
            executor.execute_graph, graph, chunk_targets, retval=False
        ).result()

    end_time = time.time()

    # collect results
    result_keys = []
    result_values, result_sizes, result_shapes = [], [], []
    collected_chunk_keys = set()
    for k in list(local_context_dict.keys()):
        v = local_context_dict[k]
        if isinstance(k, tuple):
            k = tuple(to_str(i) for i in k)
        else:
            k = to_str(k)

        chunk_key = get_chunk_key(k)
        if chunk_key in chunk_targets:
            result_keys.append(k)
            if self._calc_intermediate_device in self._calc_dest_devices:
                result_values.append(v)
                result_sizes.append(calc_data_size(v))
            else:
                result_values.append(dataserializer.serialize(v))
                result_sizes.append(result_values[-1].total_bytes)
            result_shapes.append(getattr(v, "shape", None))
            collected_chunk_keys.add(chunk_key)

        local_context_dict.pop(k)

    # check if all targets generated
    if any(k not in collected_chunk_keys for k in chunk_targets):
        raise KeyError([k for k in chunk_targets if k not in collected_chunk_keys])

    # adjust sizes in allocation
    apply_allocs = defaultdict(lambda: 0)
    for k, size in zip(result_keys, result_sizes):
        apply_allocs[get_chunk_key(k)] += size

    apply_alloc_quota_keys, apply_alloc_sizes = [], []
    for k, v in apply_allocs.items():
        apply_alloc_quota_keys.append(
            build_quota_key(session_id, k, owner=self.proc_id)
        )
        apply_alloc_sizes.append(v)
    self._mem_quota_ref.alter_allocations(
        apply_alloc_quota_keys, apply_alloc_sizes, _tell=True, _wait=False
    )
    self._mem_quota_ref.hold_quotas(apply_alloc_quota_keys, _tell=True)

    if self._status_ref:
        self._status_ref.update_mean_stats(
            "calc_speed." + op_name,
            sum(apply_alloc_sizes) * 1.0 / (end_time - start_time),
            _tell=True,
            _wait=False,
        )

    return self.storage_client.put_objects(
        session_id,
        result_keys,
        result_values,
        [self._calc_intermediate_device],
        sizes=result_sizes,
        shapes=result_shapes,
    ).then(lambda *_: result_keys)