# MindSpore报错：all types should be same, but got \[mindspore.tensor\[float64\], mindspore.tensor\[float32\]

**1. 系统环境**

硬件环境\(Ascend/GPU/CPU\): Ascend

软件环境: MindSpore 版本: 2.1

执行模式（静态图/动态图）：静态图

Python 版本: 3.7.6

操作系统平台: linux

**2. 报错信息**

2.1 问题描述

训练网络，动态图可以正常产生loss，静态图编译报错。

2.2 报错信息

```
[ERROR] ANALYZER(711187,fffd1d0131d0,python):2023-10-12-03:28:24.426.772 [mindspore/ccsrc/pipeline/jit/static_analysis/async_eval_result.cc:69] HandleException] Exception happened, check the information as below.

The function call stack (See file '/home/mindspore/hezhiyu/bevformer/rank_0/om/analyze_fail.ir' for more details. Get instructions about `analyze_fail.ir` at https://www.mindspore.cn/search?inputValue=analyze_fail.ir):
# 0 In file /home/mindspore/hezhiyu/bevformer/mindauto/utils/train_step_wrapper.py:95
        if not self.is_cpu_device:
        ^
# 1 In file /home/mindspore/hezhiyu/bevformer/mindauto/utils/train_step_wrapper.py:91
        loss = self.network(*inputs)  # mini-batch loss
               ^
# 2 In file /home/mindspore/hezhiyu/bevformer/mindauto/models/bevformer.py:231
        if self.training:
# 3 In file /home/mindspore/hezhiyu/bevformer/mindauto/models/bevformer.py:243
            return self.forward_train(**new_args)
                   ^
# 4 In file /home/mindspore/hezhiyu/bevformer/mindauto/models/bevformer.py:315
        if self.use_grid_mask:
# 5 In file /home/mindspore/hezhiyu/bevformer/mindauto/models/bevformer.py:316
            prev_bev = self.obtain_history_bev(prev_grid_img,
                       ^
# 6 In file /home/mindspore/hezhiyu/bevformer/mindauto/models/bevformer.py:257
        for i in range(len_queue):
# 7 In file /home/mindspore/hezhiyu/bevformer/mindauto/models/bevformer.py:316
            prev_bev = self.obtain_history_bev(prev_grid_img,
                       ^
# 8 In file /home/mindspore/hezhiyu/bevformer/mindauto/models/bevformer.py:257
        for i in range(len_queue):
# 9 In file /home/mindspore/hezhiyu/bevformer/mindauto/models/bevformer.py:316
            prev_bev = self.obtain_history_bev(prev_grid_img,
                       ^
# 10 In file /home/mindspore/hezhiyu/bevformer/mindauto/models/bevformer.py:263
            prev_bev = self.pts_bbox_head(
# 11 In file /home/mindspore/hezhiyu/bevformer/mindauto/models/heads/bevformer_head.py:154
        if only_bev:  # only use encoder to obtain BEV features, TODO: refine the workaround
        ^
# 12 In file /home/mindspore/hezhiyu/bevformer/mindauto/models/heads/bevformer_head.py:155
            return self.transformer.get_bev_features(
# 13 In file /home/mindspore/hezhiyu/bevformer/mindauto/models/heads/bevformer_head.py:155
            return self.transformer.get_bev_features(
                   ^
# 14 In file /home/mindspore/hezhiyu/bevformer/mindauto/models/transformer/transformer.py:451
        for lvl, feat in enumerate(mlvl_feats):
        ^
# 15 In file /home/mindspore/hezhiyu/bevformer/mindauto/models/heads/bevformer_head.py:155
            return self.transformer.get_bev_features(
                   ^
# 16 In file /home/mindspore/hezhiyu/bevformer/mindauto/models/transformer/transformer.py:451
        for lvl, feat in enumerate(mlvl_feats):
        ^
# 17 In file /home/mindspore/hezhiyu/bevformer/mindauto/models/transformer/transformer.py:468
        bev_embed = self.encoder(
# 18 In file /home/mindspore/hezhiyu/bevformer/mindauto/models/transformer/encoder.py:178
        if prev_bev is not None:
# 19 In file /home/mindspore/hezhiyu/bevformer/mindauto/models/transformer/encoder.py:180
            prev_bev = ops.stack([prev_bev, bev_query], 1).reshape(bs * 2, len_bev, -1)
                       ^
# 20 In file /home/mindspore/.conda/envs/bevformer/lib/python3.8/site-packages/mindspore/ops/function/array_func.py:2207
    return _stack(tensors)
           ^

Traceback (most recent call last):
  File "tools/train.py", line 233, in <module>
    main(config)
  File "tools/train.py", line 215, in main
    model.train(
  File "/home/mindspore/.conda/envs/bevformer/lib/python3.8/site-packages/mindspore/train/model.py", line 1061, in train
    self._train(epoch,
  File "/home/mindspore/.conda/envs/bevformer/lib/python3.8/site-packages/mindspore/train/model.py", line 113, in wrapper
    func(self, *args, **kwargs)
  File "/home/mindspore/.conda/envs/bevformer/lib/python3.8/site-packages/mindspore/train/model.py", line 613, in _train
    self._train_process(epoch, train_dataset, list_callback, cb_params, initial_epoch, valid_infos)
  File "/home/mindspore/.conda/envs/bevformer/lib/python3.8/site-packages/mindspore/train/model.py", line 914, in _train_process
    outputs = self._train_network(*next_element)
  File "/home/mindspore/.conda/envs/bevformer/lib/python3.8/site-packages/mindspore/nn/cell.py", line 639, in __call__
    out = self.compile_and_run(*args, **kwargs)
  File "/home/mindspore/.conda/envs/bevformer/lib/python3.8/site-packages/mindspore/nn/cell.py", line 963, in compile_and_run
    self.compile(*args, **kwargs)
  File "/home/mindspore/.conda/envs/bevformer/lib/python3.8/site-packages/mindspore/nn/cell.py", line 940, in compile
    _cell_graph_executor.compile(self, phase=self.phase,
  File "/home/mindspore/.conda/envs/bevformer/lib/python3.8/site-packages/mindspore/common/api.py", line 1625, in compile
    result = self._graph_executor.compile(obj, args, kwargs, phase, self._use_vm_mode())
  File "/home/mindspore/.conda/envs/bevformer/lib/python3.8/site-packages/mindspore/ops/operations/array_ops.py", line 3108, in __infer__
    all_shape = _get_stack_shape(value, x_shape, x_type, self.axis, self.name)
  File "/home/mindspore/.conda/envs/bevformer/lib/python3.8/site-packages/mindspore/ops/operations/array_ops.py", line 3002, in _get_stack_shape
    raise TypeError("For \'{}\', all types should be same, but got {}".format(prim_name, x_type))
TypeError: For 'Stack', all types should be same, but got [mindspore.tensor[float64], mindspore.tensor[float32]]
```

**3. 根因分析**

静态图和动态图的区别可以参考官网说明：https://www.mindspore.cn/docs/zh-CN/r2.1/design/dynamic\_graph\_and\_static\_graph.html

静态图有控制流语法限制，支持语法可从官网查询到：https://www.mindspore.cn/docs/zh-CN/r2.1/note/static\_graph\_syntax\_support.html

分析代码发现有部分有控制流，使用note打开产生的analyze\_fail.ir文件，查找是否产生了Any类型

当控制流产生，静态图编译时会将不同分支产生的不同数据类型转成Any类型，找到产生Any的地方：prev\_bev = prev\_bev.permute\(1, 0, 2\).astype\(ms.float32\)。

```
: (<Int64, NoShape>, <Int64, NoShape>, <Int64, NoShape>, <Int64, NoShape>) -> (<Tensor[Float32], (2, 2500, 1, 2)>)
      #scope: (Default/network-BEVFormer/pts_bbox_head-BEVFormerHead/transformer-PerceptionTransformer/encoder-BEVFormerEncoder)
      # In file /home/mindspore/hezhiyu/bevformer/mindauto/models/transformer/encoder.py:181/            hybird_ref_2d = ops.stack([shift_ref_2d, ref_2d], 1).reshape(/
  %25([CNode]8228) = getattr(%para1614_prev_bev, "permute")
      : (<Any(Tensor)[Float64], (-2)>, <String, NoShape>) -> (<Any(Tensor)[Float64], (-2)>)
      #scope: (Default/network-BEVFormer/pts_bbox_head-BEVFormerHead/transformer-PerceptionTransformer/encoder-BEVFormerEncoder)
      # In file /home/mindspore/hezhiyu/bevformer/mindauto/models/transformer/encoder.py:179/            prev_bev = prev_bev.permute(1, 0, 2).astype(ms.float32)/
  %26([CNode]8229) = %25(I64(1), I64(0), I64(2))
```

该处代码逻辑有的时候是None，有的时候又是某一种shape的tensor，还有判断条件会进行permute，因此静态图产生了Any类型数据，Cast不生效。

**4. 解决方案**

统一数据类型，修改控制流跑通代码。

