如何实现torch.arange的tensor版本

文章目录

背景

python 复制代码
import torch

我们都知道,torch.arange只支持数字,不支持tensor,如下:

python 复制代码
torch.arange(0,5,1)

tensor(0, 1, 2, 3, 4)

但是如果使用tensor,就会报错:

python 复制代码
torch.arange(torch.tensor([0]),torch.tensor([5]),torch.tensor([1]))

可问题是,我们有如下场景怎么办:

python 复制代码
torch.arange(torch.tensor([0,2]),torch.tensor([5,7]),torch.tensor([1,1]))

也就是说,我们希望

python 复制代码
torch.arange(0,5,1)和torch.arange(2,7,1)

并行做,难道就不行吗?

实现方案

上面这种并行是可以做到的,如下:

python 复制代码
x=torch.arange(0,5,1).reshape(1,-1)
a=torch.tensor([0,2])
a=a.reshape(-1,1)
x=a+x
x

tensor(\[0, 1, 2, 3, 4,

2, 3, 4, 5, 6])

不可行的情况

细心的人可以发现,上面是具有特殊性的,

python 复制代码
torch.arange(torch.tensor([0,2]),torch.tensor([5,7]),torch.tensor([1,1]))

python 复制代码
torch.tensor([0,2])+5=torch.tensor([5,7])

且步长是一样的:

python 复制代码
torch.tensor([1,1])#步长都是1

为什么必须这样呢?因为这样才可以保证,输出的结果的维度是一样的。比如你换一个:

python 复制代码
torch.arange(torch.tensor([0,2]),torch.tensor([5,7]),torch.tensor([1,2]))

步长一个是1,一个是2,这样肯定不行,两个arange输出的维度不同,就肯定不可能并行。再比如:

python 复制代码
torch.arange(torch.tensor([0,2]),torch.tensor([5,9]),torch.tensor([1,1]))

步长是一样了,但是5-0=5,9-2=7(end-start),最终arange输出的维度还是会不同,无法并行。

相关推荐
Sirius.z3 小时前
第R6周:LSTM实现糖尿病探索与预测
python
名字还没想好☜3 小时前
Python f-string 进阶:数字格式化、对齐填充、调试 = 号与嵌套表达式
开发语言·数据库·python·字符串格式化·f-string
IvanCodes3 小时前
RAG 实战教程(一):RAG 工作原理与完整流程——分片、索引、召回、重排和生成
人工智能·后端·agent
·薯条大王3 小时前
经济实惠玩云服务器|一台云服务器多人共用,子账号配置教程
java·linux·运维·服务器·汇编·c++·python
今天AI了吗3 小时前
合规场景下的 AI 推理可解释性:Attention 可视化与推理路径追踪的工程实践
人工智能
周末程序猿4 小时前
浅析大模型推理十二篇之KV Cache
人工智能
鱼樱前端4 小时前
用 AI 做内容变收入
前端·人工智能·ai编程
Dxy12393102164 小时前
Python 如何使用 MySQL 的事务
python·mysql
Dawson Zhu5 小时前
基于Palantir Foundry构建半导体制造AI友好型数据中台:从良率分析场景谈起
人工智能·语言模型·架构·制造·agi
fthux5 小时前
装闭 RenoPit 源码解析(04):装修图纸和合同文件上传处理流程
人工智能·ai·开源·github·open source·renopit