ABACUS develop
Atomic-orbital Based Ab-initio Computation at UStc
Loading...
Searching...
No Matches
tensor.h
Go to the documentation of this file.
1#ifndef ATEN_CORE_TENSOR_H_
2#define ATEN_CORE_TENSOR_H_
3
9
10#include <ATen/kernels/memory.h>
11
12#include <base/macros/macros.h>
13
14// TODO:
15// 1. add log system
16// 2. add exception system
17// 3. refact cmake system, use cmake parant scope to construct the libraries
18
19namespace ct = container;
20
21namespace container {
22
32class Tensor {
33 public:
34
41 Tensor();
42
52 explicit Tensor(DataType data_type);
53
61
72
74
82 Tensor(const Tensor& other);
83
93 Tensor(Tensor&& other) noexcept;
94
95 ~Tensor();
107 template <typename T>
108 Tensor(std::initializer_list<T> values, DeviceType device = DeviceType::CpuDevice) :
109 Tensor(DataTypeToEnum<T>::value, device, TensorShape({static_cast<int64_t>(values.size())})) {
110 TEMPLATE_ALL_2(this->data_type_, this->device_,
112 this->data<T>(), values.begin(), this->NumElements()))
113 }
114
120 DataType data_type() const;
121
127 DeviceType device_type() const;
128
134 const TensorShape& shape() const;
135
141 int64_t NumElements() const;
142
148 void* data() const;
149
163 template <typename T>
164 T* data() const {
165 if ((std::is_same<T, float>::value && data_type_ != DataType::DT_FLOAT) ||
166 (std::is_same<T, int>::value && data_type_ != DataType::DT_INT) ||
167 (std::is_same<T, int64_t>::value && data_type_ != DataType::DT_INT64) ||
168 (std::is_same<T, double>::value && data_type_ != DataType::DT_DOUBLE) ||
169 (std::is_same<T, std::complex<float>>::value && data_type_ != DataType::DT_COMPLEX) ||
170 (std::is_same<T, std::complex<double>>::value && data_type_ != DataType::DT_COMPLEX_DOUBLE))
171 {
172 std::cerr << "Tensor data type does not match requested type." << std::endl;
173 exit(EXIT_FAILURE);
174 }
175 return buffer_->base<T>();
176 }
177
197 switch (data_type) {
199 return sizeof(float);
200 case DataType::DT_INT:
201 return sizeof(int32_t);
203 return sizeof(int64_t);
205 return sizeof(double);
207 return sizeof(std::complex<float>);
209 return sizeof(std::complex<double>);
210 default:
211 std::cerr << "Unsupported data type!" << std::endl;
212 exit(EXIT_FAILURE);
213 }
214 }
215
221 const TensorBuffer& buffer() const;
222
230 template <typename DEVICE>
233 return *this;
234 }
235 // Create output tensor on device
237
238 // Copy data to a specified device
239 // TODO: move the memory operator into the tensor_buff class.
240 TEMPLATE_ALL_2(this->data_type_, this->device_,
242 output.data<T_>(), this->data<T_>(), this->NumElements()))
243
244 return output;
245 }
246
268 template <typename DEVICE, typename T>
269 void copy_from_device(const T* data, int64_t num_elements = -1) {
270 if (num_elements == -1) {
271 num_elements = this->NumElements();
272 }
273 REQUIRES_OK(this->shape_.NumElements() >= num_elements,
274 "The number of elements of the input data must match the number of elements of the tensor.")
275
276 TEMPLATE_CZ_2(this->data_type_, this->device_,
278 this->data<T_>(), data, num_elements))
279 }
280
288 template <typename T>
289 Tensor cast() const {
290 // Create output tensor on device
292
293 // TODO: error handle of cast memory
294 // TODO: move the memory operator into the tensor_buff class.
295 // Copy data to a specified device
296 TEMPLATE_CZ_2(this->data_type_, this->device_,
298 output.data<T>(), this->data<T_>(), this->NumElements()))
299
300 return output;
301 }
302
306 void zero();
307
316
324 Tensor shaped(const TensorShape& shape) const;
325
336 Tensor slice(const std::vector<int>& start, const std::vector<int>& size) const;
337
351 void resize(const TensorShape& new_shape);
352
360 // TODO: Delete this function, and use a singleton allocator class.
362
373 template <typename T, typename... Indices>
374 T& get_value(Indices... indices) const {
375 if (sizeof...(Indices) != shape_.ndim()) {
376 throw std::invalid_argument("Incorrect number of indices.");
377 }
378
379 // Calculate the linear index corresponding to the given indices
380 size_t linearIndex = calculateLinearIndex(indices...);
381
382 // Access the element at the calculated linear index
383 return *reinterpret_cast<T*>(data<T>() + linearIndex);
384 }
385
397 template <typename T>
398 T* inner_most_ptr(const int& index) const
399 {
400 const unsigned int rank = shape_.ndim();
401 if (rank == 0 || rank > 2)
402 {
403 throw std::invalid_argument("Invalid call, inner_most_ptr only supports tensor ranks 1 and 2!");
404 }
405 const int64_t outer_size = shape_.dim_size(0);
406 if (index < 0 || static_cast<int64_t>(index) >= outer_size)
407 {
408 throw std::invalid_argument("Invalid index, inner_most_ptr index is out of bounds!");
409 }
410 if (rank == 1)
411 {
412 return data<T>() + index;
413 }
414 return data<T>() + index * shape_.dim_size(1);
415 }
416
426 bool operator==(const Tensor& other) const;
427
437 Tensor& operator=(const Tensor& other);
438
450 Tensor& operator=(Tensor&& other) noexcept;
451
462 bool CopyFrom(const Tensor& other);
463
478 bool CopyFrom(const Tensor& other, const TensorShape& shape);
479
491 bool AllocateFrom(const Tensor& other, const TensorShape& shape);
492
504 template <typename T, size_t N, typename index_t = int64_t>
506 // Check if the tensor's rank is greater than 0
507 static_assert(N > 0,
508 "Accessor is used to access the data of a tensor with rank > 0, for scalars use *data<T>()");
509 // Check if the rank of the tensor matches the rank of the accessor
510 REQUIRES_OK(this->shape_.ndim() == N,
511 "The rank of the tensor must match the rank of the accessor.")
512 // Create and return a TensorAccessor object
513 return TensorAccessor<T, N, index_t>(this->data<T>(), this->shape_.dims().data(), this->shape_.strides().data());
514 }
515 template<typename T, size_t N, typename index_t = int>
517
525 void sync(const Tensor& rhs);
526
535 Tensor operator[] (const int& index) const;
536
537 explicit operator bool() const {
538 return this->NumElements() > 0;
539 }
540
541 template<typename T>
542 void set_value(T value) {
543 TEMPLATE_ALL_2(this->data_type_, this->device_,
544 kernels::set_memory<T, DEVICE_>()(this->data<T>(), value, this->NumElements()))
545 }
546
547protected:
548
553
558
563
568
581 template <typename... Indices>
582 size_t calculateLinearIndex(Indices... indices) const {
583 size_t stride = 1;
584 size_t linearIndex = 0;
585 size_t indexArray[] = { static_cast<size_t>(indices)... };
586
587 for (int ii = static_cast<int>(shape_.ndim()) - 1; ii >= 0; --ii) {
588 linearIndex += indexArray[ii] * stride;
589 stride *= shape_.dim_size(ii);
590 }
591 return linearIndex;
592 }
593
594 // This function is used to copy data and properties from another Tensor instance, 'other', into the current Tensor instance.
595 // The 'shape' parameter specifies the new shape for the current Tensor.
596 inline void CopyFromInternal(const Tensor& other, const TensorShape& shape) {
597 // Copy the data type and device from the 'other' Tensor.
598 data_type_ = other.data_type_;
599 device_ = other.device_;
600 // Set the shape of the current Tensor to the provided 'shape'.
601 shape_ = shape;
602 // Check if the buffer of the current Tensor is different from the buffer of the 'other' Tensor.
603 if (buffer_ != other.buffer_) {
604 // If the current Tensor has a buffer, decrease its reference count.
605 // Note this could indicate a deleted of current buffer_
606 if (buffer_) buffer_->unref();
607 // Assign the buffer of the 'other' Tensor to the current Tensor's buffer.
608 buffer_ = other.buffer_;
609 // Increase the reference count of the buffer to indicate shared ownership.
610 if (buffer_) buffer_->ref();
611 }
612 }
613
614};
615
626std::ostream& operator<<(std::ostream& os, const Tensor& tensor);
627
628} // namespace container
629
630#endif // ATEN_CORE_TENSOR_H_
An abstract base class for memory allocators.
Definition allocator.h:17
Definition tensor_accessor.h:72
Interface to access the raw ref-counted data buffer.
Definition tensor_buffer.h:13
A class for representing the shape of a tensor.
Definition tensor_shape.h:13
A multi-dimensional array of elements of a single data type.
Definition tensor.h:32
Tensor()
Creates a 1-dimentional, 0-element float tensor.
Definition tensor.cpp:10
Tensor cast() const
Method to transform data from a given tensor object to the output tensor with a given data type.
Definition tensor.h:289
Tensor to_device() const
Method to transform data from a given tensor object to the output tensor with a given device type.
Definition tensor.h:231
void * data() const
Get a pointer to the data buffer of the tensor.
Definition tensor.cpp:73
static base::core::Allocator * GetAllocator(DeviceType device)
Get the Allocator object according to the given device type.
Definition tensor.cpp:79
size_t calculateLinearIndex(Indices... indices) const
Calculates the linear index corresponding to the given indices.
Definition tensor.h:582
T & get_value(Indices... indices) const
Get the element at the specified indices.
Definition tensor.h:374
T * inner_most_ptr(const int &index) const
Get the pointer to the specified row.
Definition tensor.h:398
int64_t NumElements() const
Get the total number of elements in the tensor.
Definition tensor.cpp:70
void sync(const Tensor &rhs)
Synchronize the current Tensor with another Tensor.
Definition tensor.cpp:296
void zero()
Set all elements in current tensor object to zero.
Definition tensor.cpp:97
bool AllocateFrom(const Tensor &other, const TensorShape &shape)
Copies data from another Tensor with memory allocation and specified shape.
Definition tensor.cpp:286
TensorAccessor< T, N, index_t > accessor() &&=delete
DeviceType device_type() const
Get the data type of the tensor.
Definition tensor.cpp:64
void reshape(TensorShape shape)
Set all elements in current tensor object to zero.
Definition tensor.cpp:103
bool operator==(const Tensor &other) const
Equality comparison operator for tensors.
Definition tensor.cpp:253
void resize(const TensorShape &new_shape)
Resize the tensor to the new shape.
Definition tensor.cpp:207
TensorBuffer * buffer_
The TensorBuffer object that holds the data of the tensor.
Definition tensor.h:567
TensorAccessor< T, N, index_t > accessor() const &
Accessor function for a multi-dimensional tensor.
Definition tensor.h:505
const TensorBuffer & buffer() const
Get the TensorBuffer object that holds the data of the tensor.
Definition tensor.cpp:76
DataType data_type() const
Get the data type of the tensor.
Definition tensor.cpp:61
Tensor slice(const std::vector< int > &start, const std::vector< int > &size) const
Return a new Tensor slice starting at the specified indices with the given size.
Definition tensor.cpp:147
static size_t SizeOfType(DataType data_type)
Returns the size of a single element for a given data type.
Definition tensor.h:196
void set_value(T value)
Definition tensor.h:542
Tensor shaped(const TensorShape &shape) const
Set all elements in current tensor object to zero.
Definition tensor.cpp:139
void copy_from_device(const T *data, int64_t num_elements=-1)
Copies data from a given device to the current tensor object.
Definition tensor.h:269
Tensor(std::initializer_list< T > values, DeviceType device=DeviceType::CpuDevice)
Constructor for the Tensor class using an initializer list of values.
Definition tensor.h:108
DataType data_type_
The data type of the tensor.
Definition tensor.h:552
Tensor & operator=(const Tensor &other)
Assignment operator overload for the Tensor class.
Definition tensor.cpp:220
Tensor operator[](const int &index) const
Access a sub-Tensor based on an index.
Definition tensor.cpp:313
~Tensor()
Definition tensor.cpp:55
TensorShape shape_
The shape of the tensor.
Definition tensor.h:562
DeviceType device_
The device type of the tensor.
Definition tensor.h:557
bool CopyFrom(const Tensor &other)
Copy the data from another tensor into this tensor.
Definition tensor.cpp:273
T * data() const
Get a typed pointer to the data buffer of the tensor.
Definition tensor.h:164
const TensorShape & shape() const
Get the shape of the tensor.
Definition tensor.cpp:67
void CopyFromInternal(const Tensor &other, const TensorShape &shape)
Definition tensor.h:596
Definition output.h:13
#define N
Definition exp.cpp:24
#define T
Definition exp.cpp:237
#define REQUIRES_OK(expr,...)
Definition macros.h:67
#define TEMPLATE_CZ_2(TYPE_ENUM, DEVICE_ENUM,...)
Definition macros.h:234
#define TEMPLATE_ALL_2(TYPE_ENUM, DEVICE_ENUM,...)
Definition macros.h:221
Definition tensor.cpp:8
DataType
Definition tensor_enums.h:15
@ DT_COMPLEX
Definition tensor_enums.h:21
@ DT_INT64
Definition tensor_enums.h:20
@ DT_FLOAT
Definition tensor_enums.h:17
@ DT_COMPLEX_DOUBLE
Definition tensor_enums.h:22
@ DT_INT
Definition tensor_enums.h:19
@ DT_DOUBLE
Definition tensor_enums.h:18
DeviceType
Definition tensor_enums.h:28
@ CpuDevice
Definition tensor_enums.h:30
std::ostream & operator<<(std::ostream &os, const Tensor &tensor)
Overloaded operator<< for the Tensor class.
Definition tensor.cpp:330
Definition tensor_enums.h:60
static constexpr DataType value
Definition tensor_enums.h:61
static constexpr DeviceType value
Definition tensor_enums.h:36
Casts memory between devices.
Definition memory.h:107
A functor to set memory to a constant value.
Definition memory.h:37
Synchronizes memory between devices.
Definition memory.h:58
This file contains the definition of the DataType enum class.
std::string output
Definition test_io_sys_var.cpp:60
iclock::time_point start
Definition test_partition.cpp:22