如何初始化at::Scalar

How can I initialize an at::Scalar?

本文关键字:Scalar at 初始化      更新时间:2024-05-23

我试图调用名为linspace的PyTorch C++API函数。当我试着把它写成Python风格时,我写道:

torch::Tensor x = torch::linspace(-1, 1, 100);

这个代码出现了一个分段错误:

[1]    6038 segmentation fault  ./example-app

我阅读了pytorch.org中的C++文档,它给出了linspace的格式:

at::Tensor torch::linspace(const at::Scalar &start, const at::Scalar &end, c10::optional<int64_t> steps = c10::nullopt, at::TensorOptions options = {})

在这里,我不知道at::Scalar的确切含义,所以我在命名空间的关于的文档中搜索了它,但我没有找到任何名为Scalar的类。

然而,我确实在at命名空间中发现了许多具有Scalar类型参数的函数。

这是关于linspace函数的文档,这是关于命名空间中的文档。

我今天遇到了另一个与标量相关的问题,并开始寻找文档。我找不到文档,但在头文件中找到了这个:

namespace c10
{
/**
* Scalar represents a 0-dimensional tensor which contains a single element.
* Unlike a tensor, numeric literals (in C++) are implicitly convertible to
* Scalar (which is why, for example, we provide both add(Tensor) and
* add(Scalar) overloads for many operations). It may also be used in
* circumstances where you statically know a tensor is 0-dim and single size,
* but don't know its type.
*/
class C10_API Scalar
{
public:
Scalar() : Scalar(int64_t(0)) {}
void destroy()
{
if (Tag::HAS_si == tag || Tag::HAS_sd == tag) {
raw::intrusive_ptr::decref(v.p);
v.p = nullptr;
}
}
...    
Scalar(T vv) : tag(Tag::HAS_b)
{
v.i = convert<int64_t, bool>(vv);
}
...
}

这并不难找到,但我认为他们应该把它放在主要文档中。。。不管怎样,看起来你做得对。