Complex Tensor in C++ API?

Hi everyone,

I am currently trying to integrate PyTorch into my project on c++ side. I notice that It seems there is no complex type similarity of k (ex: kfloat…), but the pytorch implementation does have complex…

I am wondering if it is possible to initialize a complex type tensor/scalar/storage?

The complex type is implemented as kComplexHalf, kComplexFloat, and kComplexDouble as seen here.

Thanks, I was wondering how to create an Scalar with complex64 dtype in C++, can you give me an example, e.g.

a = 3+5j

Somthing like this?

This should work:

tensor = at::tensor(c10::complex<float>(1.0, 2.0), at::dtype(at::kComplexFloat))
1 Like

Thanks, I only want to get the Scalar, not Scalar to tensor. So basically just do this?

auto base = c10::Scalar(c10::complex<double>(1.0, 2.0));

Is this equivilent to the python code of:

base = 1.0 + 2.0j;

Since the default dtype for scalar is double not float.

Another question is that, when I try to print out the complex tensor using the std::cout method, the imaginary part didn’t get printed out.
Here is a simple example:

auto a = at::tensor({c10::complex<double>(1, 0.5), c10::complex<double>(1, 0.5)}, at::dtype(at::kComplexFloat));

    std::cout << a << std::endl;

What I got:

[W Copy.cpp:219] Warning: Casting complex values to real discards the imaginary part (function operator())
 1
 1

So, how can I print out the value of a complex tensor including the imaginary part?
Much appreciated.

@ptrblck Can you help me with this? Thanks.

These approaches work for me:

#include <iostream>
#include <ATen/ATen.h>

using std::cout;
using namespace at;

int main() {
  auto format = [] (Scalar a) {
    std::ostringstream str;
    str << a;
    return str.str();
  };

  std::cout << format(Scalar(c10::complex<double>(2.0, 3.1))) << std::endl;
  std::cout << Scalar(c10::complex<double>(3.2, 4.4)) << std::endl;
  std::cout << c10::complex<float>(4.5, 5.6) << std::endl;

  return 0;
}

Build:

./build# cmake -DCMAKE_PREFIX_PATH=`python -c 'import torch;print(torch.utils.cmake_prefix_path)'` .. && cmake --build . --config Release

Output:

./build# ./example-app 
(2,3.1)
(3.2,4.4)
(4.5,5.6)

I find your example show how to create complex number( or scalar), but @BruceDai003 want to create a complex tensor (and print it ).