| 65 | |
| 66 | |
| 67 | def _matmul(inp1, inp2, transpose_a=False, transpose_b=False, compute_mode="default"): |
| 68 | dim1, dim2 = inp1.ndim, inp2.ndim |
| 69 | assert dim1 > 0 and dim2 > 0 |
| 70 | maxdim = dim1 if dim1 > dim2 else dim2 |
| 71 | compute_mode = _config._get_actual_op_param(compute_mode, _config.__compute_mode) |
| 72 | |
| 73 | if dim1 == 1 and dim2 == 1: # dispatch to Dot |
| 74 | (result,) = apply(builtin.Dot(), inp1, inp2) |
| 75 | return result |
| 76 | elif maxdim <= 2 or (dim2 <= 2 and not transpose_a): # dispath to MatrixMul |
| 77 | # 2x1 |
| 78 | # 1x2 |
| 79 | # 2x2 |
| 80 | # nx1(transpose_a=False), n>=3 |
| 81 | # nx2(transpose_a=False), n>=3 |
| 82 | ret = matmul_cpp( |
| 83 | inp1 if dim1 > 1 else expand_dims_cpp(inp1, 0), |
| 84 | inp2 if dim2 > 1 else expand_dims_cpp(inp2, -1), |
| 85 | max(dim1, 2), |
| 86 | max(dim2, 2), |
| 87 | transpose_a, |
| 88 | transpose_b, |
| 89 | compute_mode, |
| 90 | _config._benchmark_kernel, |
| 91 | _config._deterministic_kernel, |
| 92 | ) |
| 93 | if dim1 == 1: |
| 94 | ret = squeeze_cpp(ret, -2) |
| 95 | elif dim2 == 1: |
| 96 | ret = squeeze_cpp(ret, -1) |
| 97 | return ret |
| 98 | else: # dispath to BatchedMatrixMul |
| 99 | # nx1(transpose_a=True), n>=3 |
| 100 | # nx2(transpose_a=True), n>=3 |
| 101 | # nxm,n>=3,m>=3 |
| 102 | # 1xm,m>=3 |
| 103 | # 2xm,m>=3 |
| 104 | ret = batched_matmul_cpp( |
| 105 | inp1 if dim1 > 1 else expand_dims_cpp(inp1, 0), |
| 106 | inp2 if dim2 > 1 else expand_dims_cpp(inp2, -1), |
| 107 | max(dim1, 2), |
| 108 | max(dim2, 2), |
| 109 | transpose_a, |
| 110 | transpose_b, |
| 111 | compute_mode, |
| 112 | _config._benchmark_kernel, |
| 113 | _config._deterministic_kernel, |
| 114 | ) |
| 115 | if dim1 == 1: |
| 116 | ret = squeeze_cpp(ret, -2) |
| 117 | elif dim2 == 1: |
| 118 | ret = squeeze_cpp(ret, -1) |
| 119 | return ret |
| 120 | |
| 121 | |
| 122 | def _unary_elwise(mode): |