CwiseMul.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include <iostream>
  2. #define EIGEN_USE_SYCL
  3. #include <unsupported/Eigen/CXX11/Tensor>
  4. using Eigen::array;
  5. using Eigen::SyclDevice;
  6. using Eigen::Tensor;
  7. using Eigen::TensorMap;
  8. int main()
  9. {
  10. using DataType = float;
  11. using IndexType = int64_t;
  12. constexpr auto DataLayout = Eigen::RowMajor;
  13. auto devices = Eigen::get_sycl_supported_devices();
  14. const auto device_selector = *devices.begin();
  15. Eigen::QueueInterface queueInterface(device_selector);
  16. auto sycl_device = Eigen::SyclDevice(&queueInterface);
  17. // create the tensors to be used in the operation
  18. IndexType sizeDim1 = 3;
  19. IndexType sizeDim2 = 3;
  20. IndexType sizeDim3 = 3;
  21. array<IndexType, 3> tensorRange = {{sizeDim1, sizeDim2, sizeDim3}};
  22. // initialize the tensors with the data we want manipulate to
  23. Tensor<DataType, 3,DataLayout, IndexType> in1(tensorRange);
  24. Tensor<DataType, 3,DataLayout, IndexType> in2(tensorRange);
  25. Tensor<DataType, 3,DataLayout, IndexType> out(tensorRange);
  26. // set up some random data in the tensors to be multiplied
  27. in1 = in1.random();
  28. in2 = in2.random();
  29. // allocate memory for the tensors
  30. DataType * gpu_in1_data = static_cast<DataType*>(sycl_device.allocate(in1.size()*sizeof(DataType)));
  31. DataType * gpu_in2_data = static_cast<DataType*>(sycl_device.allocate(in2.size()*sizeof(DataType)));
  32. DataType * gpu_out_data = static_cast<DataType*>(sycl_device.allocate(out.size()*sizeof(DataType)));
  33. //
  34. TensorMap<Tensor<DataType, 3, DataLayout, IndexType>> gpu_in1(gpu_in1_data, tensorRange);
  35. TensorMap<Tensor<DataType, 3, DataLayout, IndexType>> gpu_in2(gpu_in2_data, tensorRange);
  36. TensorMap<Tensor<DataType, 3, DataLayout, IndexType>> gpu_out(gpu_out_data, tensorRange);
  37. // copy the memory to the device and do the c=a*b calculation
  38. sycl_device.memcpyHostToDevice(gpu_in1_data, in1.data(),(in1.size())*sizeof(DataType));
  39. sycl_device.memcpyHostToDevice(gpu_in2_data, in2.data(),(in2.size())*sizeof(DataType));
  40. gpu_out.device(sycl_device) = gpu_in1 * gpu_in2;
  41. sycl_device.memcpyDeviceToHost(out.data(), gpu_out_data,(out.size())*sizeof(DataType));
  42. sycl_device.synchronize();
  43. // print out the results
  44. for (IndexType i = 0; i < sizeDim1; ++i) {
  45. for (IndexType j = 0; j < sizeDim2; ++j) {
  46. for (IndexType k = 0; k < sizeDim3; ++k) {
  47. std::cout << "device_out" << "(" << i << ", " << j << ", " << k << ") : " << out(i,j,k)
  48. << " vs host_out" << "(" << i << ", " << j << ", " << k << ") : " << in1(i,j,k) * in2(i,j,k) << "\n";
  49. }
  50. }
  51. }
  52. printf("c=a*b Done\n");
  53. }