如何并行对多个张量进行thergrid?

发布于 2025-02-11 02:10:37 字数 291 浏览 1 评论 0原文

假设我们有一个大小[60,9]的张量X和一个大小的张量[60,9] 是否可以进行操作,例如xx,yy = torch.meshgrid(x,y),以便xx和yy具有大小[60,9,9]和xx [i, :,:],yy [i,:,:]基本上是torch.meshgrid(x [i],y [i])

内置的torch.meshgrid操作仅接受1D张量,是否可以在不使用循环的情况下执行上述操作(因为不使用GPU的并行操作,这是效率低下的)?

Let's say we have a tensor x of size [60,9] and a tensor y of size [60,9]
Is it possible to do an operation like xx,yy = torch.meshgrid(x,y) such that xx and yy is of size [60,9,9] and xx[i,:,:], yy[i,:,:] is basically torch.meshgrid(x[i],y[i])?

The built-in torch.meshgrid operation only accepts 1d tensors, is it possible to do the above operation without using for loops (which is inefficient as it does not take use of GPU's parallel operation)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

江湖彼岸 2025-02-18 02:10:37

我不相信您会获得任何收益,因为在GPU上没有进行张量的初始化。因此,提出的方法确实是在xy或使用 map 作为一个迭代:

grids = map(torch.meshgrid, zip(x,y))

I don't believe you will gain anything since the initialization of the tensors is not done on the GPU. So a proposed approach would indeed be to loop over x and y or using map as an iterable:

grids = map(torch.meshgrid, zip(x,y))
如此安好 2025-02-18 02:10:37

在为grid_sample生成网格的情况下,我找到了一种方法,这被称为一批图像。

特别是,您有2个张量grid_xgrid_y带有shape(m,n),其中m是批处理大小,n是每个网格维度的点数。您需要grid_sample的网格是大小(m,n,n,2),您可以通过在第一个维度上循环,应用:

for i in range(M):
    gx, gy = torch.meshgrid(grid_x[i], grid_y[i], indexing='ij')
    grid[i, :, :, 0] = gx
    grid[i, :, :, 1] = gy

一种更有效的方法是:

grid = torch.stack([grid_x.unsqueeze(-1).expand(M, -1, grid_y.shape[1]),
                    grid_y.unsqueeze(1).expand(M, grid_x.shape[1], -1)],
                    dim=-1
)

它的阅读不是很容易,但是它显示了meshgrid的替代方法。

I found a way to do this in the case when a grid is being generated for grid_sample, which is being called for a batch of images.

In particular, you have 2 tensors grid_x, grid_y with shape (M, N), where M is the batch size and N is the number of points per grid dimension. The grid you need for grid_sample is of size (M, N, N, 2), and you could obtain it by looping over the first dimension, applying:

for i in range(M):
    gx, gy = torch.meshgrid(grid_x[i], grid_y[i], indexing='ij')
    grid[i, :, :, 0] = gx
    grid[i, :, :, 1] = gy

A much more efficient way to do this is:

grid = torch.stack([grid_x.unsqueeze(-1).expand(M, -1, grid_y.shape[1]),
                    grid_y.unsqueeze(1).expand(M, grid_x.shape[1], -1)],
                    dim=-1
)

It's not very easy to read, but it shows an alternative to meshgrid.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文