# MindSpore报错“ValueError: For 'MatMul', the input dimensions必须相等

**1. 系统环境**

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

软件环境: MindSpore 版本: 1.6.0

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

Python 版本: 3.7

操作系统平台: linux

**2. 报错信息**

2.1 问题描述

训练脚本是通过构建MatMul的单算子网络，对输入的两个张量计算矩阵乘积。脚本如下：

2.2 报错信息

```
The function call stack (See file '/rank_0/om/analyze_fail.dat' for more details):
# 0 In file demo.py(06)
        out = ops.matmul (x1, x2)
              ^
# 1 In file /lib/python3.7/site-packages/mindspore/ops/composite/math_ops.py(810)
    if not _check_same_type(dtype1, dtype2):
    ^
# 2 In file /lib/python3.7/site-packages/mindspore/ops/composite/math_ops.py(824)
    if F.rank(x2) == 2:
# 3 In file /lib/python3.7/site-packages/mindspore/ops/composite/math_ops.py(825)
        if F.rank(x1) &gt; 2:
# 4 In file /lib/python3.7/site-packages/mindspore/ops/composite/math_ops.py(827)
        res = P.MatMul(False, transpose_b)(x1, x2)
              ^

Traceback (most recent call last):
  File &quot;demo.py&quot;, line 12, in &lt;module&gt;
    out = net(x1, x2)
  File &quot;/lib/python3.7/site-packages/mindspore/nn/cell.py&quot;, line 586, in __call__
    out = self.compile_and_run(*args)
  File &quot;/lib/python3.7/site-packages/mindspore/nn/cell.py&quot;, line 964, in compile_and_run
    self.compile(*inputs)
  File &quot;/lib/python3.7/site-packages/mindspore/nn/cell.py&quot;, line 937, in compile
    _cell_graph_executor.compile(self, *inputs, phase=self.phase, auto_parallel_mode=self._auto_parallel_mode)
  File &quot;/lib/python3.7/site-packages/mindspore/common/api.py&quot;, line 1040, in compile
    result = self._graph_executor.compile(obj, args_list, phase, self._use_vm_mode())
  File &quot;/lib/python3.7/site-packages/mindspore/ops/primitive.py&quot;, line 467, in __check__
    fn(*(x[track] for x in args))
  File &quot;/lib/python3.7/site-packages/mindspore/ops/operations/math_ops.py&quot;, line 1430, in check_shape
    raise ValueError(f&quot;For '{cls_name}', the input dimensions must be equal, but got 'x1_col': {x1_col} &quot;
ValueError: For 'MatMul', the input dimensions must be equal, but got 'x1_col': 12800 and 'x2_row': 10. And 'x' shape [32, 12800](transpose_a=False), 'y' shape [10, 1280](transpose_b=False).
```

2.3 脚本信息

```
class Net(nn.Cell):
    def __init__(self):
        super(Net, self).__init__()

    def construct(self, x1, x2):
        out = ops.matmul (x1, x2)
        return out

net = Net()
x1 = Tensor(np.arange(32*12800).reshape(32, 12800), mindspore.float32)
x2 = Tensor(np.arange(10*1280).reshape(10, 1280), mindspore.float32)
out = net(x1, x2)
print('out',out.shape)
```

**3. 根因分析**

我们来看报错信息，在ValueError中，写到the input dimensions must be equal, but got 'x1\_col': 12800 and 'x2\_row': 10，结合官网对matmul算子的介绍\(如下图\)，即x1的最后一个维度和x2的倒数第二个维度需要保持一致，可知我们输入的x1、x2对应位置的维度12800、10不满足计算要求。

![](figures/zh-cn_image_0000002143109089.png)

当然，在出现类似shape不匹配的问题时，通常在报错日志中会打印相应的图结构调用栈信息，也可以先从调用栈信息尝试定位错误位置。调用栈信息不够清晰时，可以考虑参考analyze\_fail.dat文件辅助分析。

**4. 解决方案**

基于上面已知的原因，很容易做出如下修改：

```
class Net(nn.Cell):
    def __init__(self):
        super(Net, self).__init__()

    def construct(self, x1, x2):
        out = ops.matmul (x1, x2)
        return out

net = Net()
x1 = Tensor(np.arange(32*12800).reshape(32, 12800), mindspore.float32)
x2 = Tensor(np.arange(10*1280).reshape(10, 1280), mindspore.float32)
out = net(x1, x2)
print('out',out.shape)
```

此时执行成功，输出如下：

```
out（32，1280）
```

