gpt4 book ai didi

python - 4 次矩阵乘法的 np.einsum 性能

转载 作者:行者123 更新时间:2023-11-30 22:11:16 29 4
gpt4 key购买 nike

给定以下 3 个矩阵:

M = np.arange(35 * 37 * 59).reshape([35, 37, 59])
A = np.arange(35 * 51 * 59).reshape([35, 51, 59])
B = np.arange(37 * 51 * 51 * 59).reshape([37, 51, 51, 59])
C = np.arange(59 * 27).reshape([59, 27])

我使用einsum来计算:

D1 = np.einsum('xyf,xtf,ytpf,fr->tpr', M, A, B, C, optimize=True);

但我发现它的性能要低得多:

tmp = np.einsum('xyf,xtf->tfy', A, M, optimize=True)
tmp = np.einsum('ytpf,yft->ftp', B, tmp, optimize=True)
D2 = np.einsum('fr,ftp->tpr', C, tmp, optimize=True)

我不明白为什么。
总的来说,我正在尽力优化这段代码。我已经阅读过有关 np.tensordot 函数的信息,但我似乎无法弄清楚如何将它用于给定的计算。

最佳答案

看起来您偶然发现了一种情况,其中贪婪路径给出了非最佳缩放。

>>> path, desc = np.einsum_path('xyf,xtf,ytpf,fr->tpr', M, A, B, C, optimize="greedy");
>>> print(desc)
Complete contraction: xyf,xtf,ytpf,fr->tpr
Naive scaling: 6
Optimized scaling: 5
Naive FLOP count: 3.219e+10
Optimized FLOP count: 4.165e+08
Theoretical speedup: 77.299
Largest intermediate: 5.371e+06 elements
--------------------------------------------------------------------------
scaling current remaining
--------------------------------------------------------------------------
5 ytpf,xyf->xptf xtf,fr,xptf->tpr
4 xptf,xtf->ptf fr,ptf->tpr
4 ptf,fr->tpr tpr->tpr

>>> path, desc = np.einsum_path('xyf,xtf,ytpf,fr->tpr', M, A, B, C, optimize="optimal");
>>> print(desc)
Complete contraction: xyf,xtf,ytpf,fr->tpr
Naive scaling: 6
Optimized scaling: 4
Naive FLOP count: 3.219e+10
Optimized FLOP count: 2.744e+07
Theoretical speedup: 1173.425
Largest intermediate: 1.535e+05 elements
--------------------------------------------------------------------------
scaling current remaining
--------------------------------------------------------------------------
4 xtf,xyf->ytf ytpf,fr,ytf->tpr
4 ytf,ytpf->ptf fr,ptf->tpr
4 ptf,fr->tpr tpr->tpr

使用 np.einsum('xyf,xtf,ytpf,fr->tpr', M, A, B, C, Optimize="optimal") 应该可以让您以最佳性能运行。我可以看看这条边,看看贪婪能否捕获它。

关于python - 4 次矩阵乘法的 np.einsum 性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51475114/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com