朱莉娅:使用base.ntuples函数实现类型稳定性

马可·罗西(Marco Rossi)

我最近开始使用Julia,目前正在处理某些打字方面的问题。我正在尝试定义类型TensorTrain(https://www.researchgate.net/profile/Ivan_Oseledets2/publication/220412263_Tensor-Train_Decomposition/links/5bbfb5c5299bf1004c5a56e3/Tensor-Train-Decomposition.pdf),但是我无法获得其中一种方法我定义为稳定的:

abstract type AbstractTensorTrain <: Any end

struct TensorTrain{T<:AbstractFloat} <: AbstractTensorTrain
    cores::Vector{Array{T,3}}
end

Base.size(t::TensorTrain, d::Int) = size(t.cores[d],2)
Base.size(t::TensorTrain) = ntuple(d->size(t,d),length(t.cores))

但是,如果我运行:

@code_warntype TensorTrain([rand(2,3,4)]);

我得到:

Variables
  #self#::Core.Compiler.Const(size, false)
  t::TensorTrain{Float64}
  #19::var"#19#20"{TensorTrain{Float64}}
  d::Int64

Body::Tuple{Vararg{Int64,N} where N}
1 ─ %1 = Base.getproperty(t, :cores)::Array{Array{Float64,3},1}
│        (d = Main.length(%1))
│   %3 = Main.:(var"#19#20")::Core.Compiler.Const(var"#19#20", false)
│   %4 = Core.typeof(t)::Core.Compiler.Const(TensorTrain{Float64}, false)
│   %5 = Core.apply_type(%3, %4)::Core.Compiler.Const(var"#19#20"{TensorTrain{Float64}}, false)
│        (#19 = %new(%5, t))
│   %7 = #19::var"#19#20"{TensorTrain{Float64}}
│   %8 = Main.ntuple(%7, d)::Tuple{Vararg{Int64,N} where N}
└──      return %8

为什么是这样?

phipsgabler

因为d = length(t.cores)仅在运行时才知道,所以ntuple无法静态推断N参数。有一个采用的方法,该方法Val在其他情况下对于类型稳定很有用,但在此不做任何更改-d仍然是动态的。

您可以制作cores一个NTupleStaticVector,(实际上是相同的东西),然后就可以了。但是在深入研究类型级编程之前,请检查它是否真的有所作为。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章