pytorch 这段代码是否正确地将循环矩阵乘法转换为einsum?

rekjcdws  于 2023-11-19  发布在  其他
关注(0)|答案(1)|浏览(87)

我写了一个基于循环和基于单和的矩阵乘法代码,我想执行。你能帮我检查它的正确性吗??
`

w = torch.randn((10,32,32))
x = torch.randn((3,32,32))
x_c = x.clone()
z = torch.zeros(x.shape)
for i in range(x.shape[0]):
  dummy_x = torch.zeros((x.shape[1],w.shape[2]))
  for j in range(w.shape[0]):
    dummy_x += torch.matmul(x[i],w[j])
  z[i]=dummy_x

result = torch.einsum("ijk,lkm->ijm",x_c,w)
# result = torch.einsum("iljm->ijm",result)
torch.eq(result,z)

字符串
我尝试了上面的代码,并使用torch.eq检查了是否相等,但答案是false

deyfvvtc

deyfvvtc1#

import torch

# Initialize the tensors
w = torch.randn((10, 32, 32))
x = torch.randn((3, 32, 32))

# For loop based matrix multiplication
z = torch.zeros(x.shape)
for i in range(x.shape[0]):
    dummy_x = torch.zeros((x.shape[1], w.shape[2]))
    for j in range(w.shape[0]):
        dummy_x += torch.matmul(x[i], w[j])
    z[i] = dummy_x

# Expand dimensions to make the tensors broadcastable
x_expanded = x.unsqueeze(1)  # Shape: (3, 1, 32, 32)
w_expanded = w.unsqueeze(0)  # Shape: (1, 10, 32, 32)

# Perform batch matrix multiplication and sum over the second dimension
result = torch.matmul(x_expanded, w_expanded).sum(dim=1)  # Shape: (3, 32, 32)

# Check for equality
are_equal = torch.all(torch.eq(result, z))

print("Are the results equal: ", are_equal.item())

字符串

相关问题