14 #include <type_traits>
50 Tensor(
const std::vector<T>& init_vals,
54 :
Tensor(shape, dtype, device) {
58 "Tensor initialization values' size {} does not match the "
64 AssertTemplateDtype<T>();
65 if (!(std::is_standard_layout<T>::value && std::is_trivial<T>::value)) {
67 "Object must be a StandardLayout and TrivialType type.");
73 init_vals.size() * dtype.
ByteSize());
82 :
Tensor(shape, dtype, device) {
84 AssertTemplateDtype<T>();
99 const std::shared_ptr<Blob>& blob)
116 template <
typename T>
120 shape_ = {
static_cast<int64_t
>(vec.size())};
126 "Tensor initialization values' size {} does not match the "
131 auto sp_vec = std::make_shared<std::vector<T>>();
133 data_ptr_ =
static_cast<void*
>(sp_vec->data());
139 [sp_vec](
void*) { (void)sp_vec; });
172 blob_ = std::make_shared<Blob>(device, (
void*)
data_ptr_, [](
void*) {});
204 template <
typename T>
219 template <
typename Object>
223 "Assignment with scalar only works for scalar Tensor of "
226 AssertTemplateDtype<Object>();
234 template <
typename S>
237 template <
typename Object>
252 template <
typename T>
274 template <
typename T>
277 std::vector<T> ele_list{val};
284 template <
typename T>
287 return InitWithInitializerList<T, 1>(in_list, device);
292 template <
typename T>
294 const std::initializer_list<std::initializer_list<T>>& in_list,
296 return InitWithInitializerList<T, 2>(in_list, device);
301 template <
typename T>
303 const std::initializer_list<
304 std::initializer_list<std::initializer_list<T>>>& in_list,
306 return InitWithInitializerList<T, 3>(in_list, device);
479 Tensor Flatten(int64_t start_dim = 0, int64_t end_dim = -1)
const;
527 std::string
ToString(
bool with_suffix =
true,
528 const std::string& indent =
"")
const;
546 int64_t step = 1)
const;
576 void IndexSet(
const std::vector<Tensor>& index_tensors,
577 const Tensor& src_tensor);
617 template <
typename T>
621 "Tensor::Item() only works for Tensor with exactly one "
624 AssertTemplateDtype<T>();
955 bool keepdim =
false)
const;
960 bool keepdim =
false)
const;
994 double atol = 1e-8)
const;
1016 double atol = 1e-8)
const;
1024 template <
typename T>
1026 AssertTemplateDtype<T>();
1064 std::tuple<Tensor, Tensor, Tensor>
LU(
const bool permute_l =
false)
const;
1078 std::tuple<Tensor, Tensor>
LUIpiv()
const;
1113 std::tuple<Tensor, Tensor>
Triul(
const int diagonal = 0)
const;
1121 std::tuple<Tensor, Tensor, Tensor>
SVD()
const;
1143 template <
typename T>
1145 return const_cast<T*
>(
const_cast<const Tensor*
>(
this)->GetDataPtr<T>());
1148 template <
typename T>
1152 "Requested values have type {} but Tensor has type {}. "
1153 "Please use non templated GetDataPtr() with manual "
1174 template <
typename T>
1178 "Requested values have type {} but Tensor has type {}",
1194 std::function<
void(
void*)> deleter =
nullptr);
1198 std::function<
void(
void*)> deleter =
nullptr);
1201 void Save(
const std::string& file_name)
const;
1204 static Tensor Load(
const std::string& file_name);
1230 std::unique_ptr<Impl> impl_;
1257 std::unique_ptr<Impl> impl_;
1297 template <
typename T,
size_t D>
1298 static Tensor InitWithInitializerList(
1302 std::vector<T> values =
1303 tensor_init::ToFlatVector<T, D>(shape, nested_list);
1304 return Tensor(values, shape, Dtype::FromType<T>(), device);
1347 :
Tensor(shape, dtype, device) {
1351 "Tensor initialization values' size {} does not match the "
1357 AssertTemplateDtype<bool>();
1361 std::vector<uint8_t> init_vals_uchar(init_vals.size());
1362 std::transform(init_vals.begin(), init_vals.end(), init_vals_uchar.begin(),
1363 [](
bool v) -> uint8_t { return static_cast<uint8_t>(v); });
1366 init_vals_uchar.data(),
1367 init_vals_uchar.size() * dtype.
ByteSize());
1372 AssertTemplateDtype<bool>();
1381 std::transform(values_uchar.begin(), values_uchar.end(), values.begin(),
1382 [](uint8_t v) ->
bool { return static_cast<bool>(v); });
1390 "Tensor::Item only works for Tensor with one element.");
1392 AssertTemplateDtype<bool>();
1396 return static_cast<bool>(value);
1399 template <
typename S>
1402 scalar_t casted_v =
static_cast<scalar_t
>(v);
1409 template <
typename Object>
1416 template <
typename T>
1418 return rhs + scalar_lhs;
1421 template <
typename T>
1426 template <
typename T>
1428 return rhs * scalar_lhs;
1431 template <
typename T>
#define DISPATCH_DTYPE_TO_TEMPLATE_WITH_BOOL(DTYPE,...)
bool IsSYCL() const
Returns true iff device type is SYCL GPU.
std::string ToString() const
static void MemcpyFromHost(void *dst_ptr, const Device &dst_device, const void *host_ptr, size_t num_bytes)
Same as Memcpy, but with host (CPU:0) as default src_device.
static void MemcpyToHost(void *host_ptr, const void *src_ptr, const Device &src_device, size_t num_bytes)
Same as Memcpy, but with host (CPU:0) as default dst_device.
int64_t NumElements() const
int64_t GetLength() const
TensorKey is used to represent single index, slice or advanced indexing on a Tensor.
Tensor LogicalOr_(const Tensor &value)
bool AllClose(const Tensor &other, double rtol=1e-5, double atol=1e-8) const
Tensor & operator=(const Tensor &other) &
double Det() const
Compute the determinant of a 2D square tensor.
Tensor Reverse() const
Reverse a Tensor's elements by viewing the tensor as a 1D array.
Tensor(std::vector< T > &&vec, const SizeVector &shape={})
Take ownership of data in std::vector<T>
Tensor Abs_()
Element-wise absolute value of a tensor, in-place.
Tensor Solve(const Tensor &rhs) const
Tensor Sqrt() const
Element-wise square root of a tensor, returns a new tensor.
Tensor Contiguous() const
Tensor Matmul(const Tensor &rhs) const
SizeVector shape_
SizeVector of the Tensor. shape_[i] is the length of dimension i.
void IndexSet(const std::vector< Tensor > &index_tensors, const Tensor &src_tensor)
Advanced indexing getter.
std::tuple< Tensor, Tensor > Triul(const int diagonal=0) const
Returns the tuple of upper and lower triangular matrix of the 2D tensor, above and below the given di...
bool IsContiguous() const
Tensor operator-() const
Unary minus of a tensor, returning a new tensor.
static Tensor EmptyLike(const Tensor &other)
Tensor AsStrided(const SizeVector &new_shape, const SizeVector &new_strides) const
Create a Tensor view of specified shape and strides. The underlying buffer and data_ptr offsets remai...
Tensor Neg() const
Element-wise negation of a tensor, returning a new tensor.
Tensor Append(const Tensor &other, const utility::optional< int64_t > &axis=utility::nullopt) const
Appends the other tensor, along the given axis and returns a copy of the tensor. The other tensors mu...
void CopyFrom(const Tensor &other)
Copy Tensor values to current tensor from the source tensor.
Tensor(Tensor &&other)=default
Tensor Triu(const int diagonal=0) const
Returns the upper triangular matrix of the 2D tensor, above the given diagonal index....
Tensor operator<(const Tensor &value) const
DLManagedTensorVersioned * ToDLPackVersioned() const
Convert the Tensor to DLManagedTensorVersioned (DLPack v1.x).
Tensor(const SizeVector &shape, Dtype dtype, const Device &device=Device("CPU:0"))
Constructor for creating a contiguous Tensor.
Tensor Sum(const SizeVector &dims, bool keepdim=false) const
Tensor operator/(const Tensor &value) const
void Save(const std::string &file_name) const
Save tensor to numpy's npy format.
void AssertTemplateDtype() const
Tensor Gt(const Tensor &value) const
Element-wise greater-than of tensors, returning a new boolean tensor.
Tensor operator+(const Tensor &value) const
Tensor operator*(const Tensor &value) const
Tensor operator/=(const Tensor &value)
std::vector< Tensor > NonZeroNumpy() const
Tensor ArgMax(const SizeVector &dims) const
Tensor Broadcast(const SizeVector &dst_shape) const
Broadcast Tensor to a new broadcastable shape.
Tensor(void *data_ptr, Dtype dtype, const SizeVector &shape, const SizeVector &strides={}, const Device &device=Device("CPU:0"))
Tensor wrapper constructor from raw host buffer.
Tensor LogicalAnd(const Tensor &value) const
Tensor IndexExtract(int64_t dim, int64_t idx) const
Tensor Ge(const Tensor &value) const
Tensor Eq(const Tensor &value) const
Element-wise equals-to of tensors, returning a new boolean tensor.
Tensor operator>=(const Tensor &value) const
static Tensor Arange(const Scalar start, const Scalar stop, const Scalar step=1, const Dtype dtype=core::Int64, const Device &device=core::Device("CPU:0"))
Create a 1D tensor with evenly spaced values in the given interval.
Tensor operator*=(Scalar value)
static Tensor Init(const std::initializer_list< std::initializer_list< T >> &in_list, const Device &device=Device("CPU:0"))
Tensor Expand(const SizeVector &dst_shape) const
Tensor Transpose(int64_t dim0, int64_t dim1) const
Transpose a Tensor by swapping dimension dim0 and dim1.
Tensor Neg_()
Element-wise negation of a tensor, in-place.
ConstIterator cend() const
Tensor Ge_(const Tensor &value)
int64_t GetLength() const
Tensor operator>(const Tensor &value) const
Tensor Ne(const Tensor &value) const
Element-wise not-equals-to of tensors, returning a new boolean tensor.
Tensor Round() const
Element-wise round value of a tensor, returning a new tensor.
Tensor Trunc() const
Element-wise trunc value of a tensor, returning a new tensor.
Tensor LogicalXor(const Tensor &value) const
void IndexAdd_(int64_t dim, const Tensor &index, const Tensor &src)
Advanced in-place reduction by index.
std::tuple< Tensor, Tensor > LUIpiv() const
Computes LU factorisation of the 2D square tensor, using A = P * L * U; where P is the permutation ma...
Tensor Any(const utility::optional< SizeVector > &dims=utility::nullopt, bool keepdim=false) const
Tensor LogicalNot() const
int64_t GetShape(int64_t dim) const
Tensor Tril(const int diagonal=0) const
Returns the lower triangular matrix of the 2D tensor, above the given diagonal index....
ConstIterator end() const
Tensor operator&&(const Tensor &value) const
Tensor operator*=(const Tensor &value)
Tensor Clip_(Scalar min_val, Scalar max_val)
static Tensor FromDLPack(const DLManagedTensor *dlmt, std::function< void(void *)> deleter=nullptr)
Convert DLManagedTensor to Tensor (DLPack v0.x).
const SizeVector & GetStridesRef() const
const Tensor AsRvalue() const
Convert to constant rvalue.
Tensor Exp() const
Element-wise exponential of a tensor, returning a new tensor.
Tensor Cos() const
Element-wise cosine of a tensor, returning a new tensor.
Tensor GetItem(const TensorKey &tk) const
std::vector< T > ToFlatVector() const
Retrieve all values as an std::vector, for debugging and testing.
static Tensor Load(const std::string &file_name)
Load tensor from numpy's npy format.
Tensor LogicalAnd_(const Tensor &value)
Tensor Prod(const SizeVector &dims, bool keepdim=false) const
const T * GetDataPtr() const
Tensor Sub_(const Tensor &value)
Tensor Permute(const SizeVector &dims) const
Permute (dimension shuffle) the Tensor, returns a view.
std::tuple< Tensor, Tensor, Tensor > LU(const bool permute_l=false) const
Computes LU factorisation of the 2D square tensor, using A = P * L * U; where P is the permutation ma...
ConstIterator begin() const
Tensor Sub(const Tensor &value) const
Substracts a tensor and returns the resulting tensor.
static Tensor Eye(int64_t n, Dtype dtype, const Device &device)
Create an identity matrix of size n x n.
Tensor operator-(const Tensor &value) const
static Tensor Init(const std::initializer_list< std::initializer_list< std::initializer_list< T >>> &in_list, const Device &device=Device("CPU:0"))
Tensor operator||(const Tensor &value) const
Tensor operator<=(const Tensor &value) const
Tensor Abs() const
Element-wise absolute value of a tensor, returning a new tensor.
Tensor SetItem(const Tensor &value)
Set all items. Equivalent to tensor[:] = value in Python.
Tensor Max(const SizeVector &dims, bool keepdim=false) const
static Tensor Init(const T val, const Device &device=Device("CPU:0"))
Tensor operator-=(const Tensor &value)
Tensor IndexGet(const std::vector< Tensor > &index_tensors) const
Advanced indexing getter. This will always allocate a new Tensor.
Tensor Flatten(int64_t start_dim=0, int64_t end_dim=-1) const
Tensor Sin() const
Element-wise sine of a tensor, returning a new tensor.
Tensor operator-=(Scalar value)
int64_t NumElements() const
Tensor Mul_(const Tensor &value)
Tensor All(const utility::optional< SizeVector > &dims=utility::nullopt, bool keepdim=false) const
Tensor Le(const Tensor &value) const
SizeVector GetStrides() const
Tensor & AssignObject(const Object &v) &&
int64_t GetStride(int64_t dim) const
Tensor Clip(Scalar min_val, Scalar max_val) const
static Tensor Zeros(const SizeVector &shape, Dtype dtype, const Device &device=Device("CPU:0"))
Create a tensor fill with zeros.
Tensor Ceil() const
Element-wise ceil value of a tensor, returning a new tensor.
static Tensor Init(const std::initializer_list< T > &in_list, const Device &device=Device("CPU:0"))
Tensor operator+=(Scalar value)
Tensor operator+=(const Tensor &value)
Tensor Add(const Tensor &value) const
Adds a tensor and returns the resulting tensor.
Tensor Sqrt_()
Element-wise square root of a tensor, in-place.
static Tensor Diag(const Tensor &input)
Create a square matrix with specified diagonal elements in input.
Tensor View(const SizeVector &dst_shape) const
Tensor LogicalOr(const Tensor &value) const
Tensor Lt_(const Tensor &value)
const void * GetDataPtr() const
Tensor Gt_(const Tensor &value)
Tensor Ne_(const Tensor &value)
Tensor IsClose(const Tensor &other, double rtol=1e-5, double atol=1e-8) const
static Tensor FromDLPackVersioned(const DLManagedTensorVersioned *dlmt, std::function< void(void *)> deleter=nullptr)
Convert DLManagedTensorVersioned to Tensor (DLPack v1.x).
Tensor Add_(const Tensor &value)
Device GetDevice() const override
std::shared_ptr< Blob > blob_
Underlying memory buffer for Tensor.
Tensor operator-(Scalar value) const
Tensor ReinterpretCast(const core::Dtype &dtype) const
Tensor LeastSquares(const Tensor &rhs) const
Tensor Min(const SizeVector &dims, bool keepdim=false) const
Tensor Reshape(const SizeVector &dst_shape) const
Tensor operator/=(Scalar value)
Tensor operator/(Scalar value) const
Tensor & operator=(const T v) &&
Tensor Clone() const
Copy Tensor to the same device.
Tensor operator+(Scalar value) const
Tensor operator==(const Tensor &value) const
Tensor operator[](int64_t i) const
Extract the i-th Tensor along the first axis, returning a new view.
std::string ToString(bool with_suffix=true, const std::string &indent="") const
std::string ScalarPtrToString(const void *ptr) const
Tensor Mean(const SizeVector &dims, bool keepdim=false) const
static Tensor Empty(const SizeVector &shape, Dtype dtype, const Device &device=Device("CPU:0"))
Create a tensor with uninitialized values.
static Tensor Ones(const SizeVector &shape, Dtype dtype, const Device &device=Device("CPU:0"))
Create a tensor fill with ones.
void FillObject(const Object &v)
Tensor Div_(const Tensor &value)
bool IsSame(const Tensor &other) const
Tensor(const SizeVector &shape, const SizeVector &strides, void *data_ptr, Dtype dtype, const std::shared_ptr< Blob > &blob)
Tensor Cos_()
Element-wise cosine of a tensor, in-place.
Tensor Le_(const Tensor &value)
SizeVector GetShape() const
std::tuple< Tensor, Tensor, Tensor > SVD() const
Tensor Sin_()
Element-wise sine of a tensor, in-place.
Tensor(const T *init_vals, const SizeVector &shape, Dtype dtype, const Device &device=Device("CPU:0"))
Constructor from raw host buffer. The memory will be copied.
void Fill(S v)
Fill the whole Tensor with a scalar value, the scalar will be casted to the Tensor's Dtype.
Tensor T() const
Expects input to be <= 2-D Tensor by swapping dimension 0 and 1.
Tensor(const std::vector< T > &init_vals, const SizeVector &shape, Dtype dtype, const Device &device=Device("CPU:0"))
Constructor for creating a contiguous Tensor with initial values.
Tensor ArgMin(const SizeVector &dims) const
Tensor Mul(const Tensor &value) const
Multiplies a tensor and returns the resulting tensor.
Tensor Slice(int64_t dim, int64_t start, int64_t stop, int64_t step=1) const
Tensor operator!=(const Tensor &value) const
Tensor Div(const Tensor &value) const
Divides a tensor and returns the resulting tensor.
Tensor To(Dtype dtype, bool copy=false) const
DLManagedTensor * ToDLPack() const
Convert the Tensor to DLManagedTensor (DLPack v0.x).
Tensor Floor() const
Element-wise floor value of a tensor, returning a new tensor.
Tensor(const Tensor &other)=default
const SizeVector & GetShapeRef() const
Tensor Lt(const Tensor &value) const
Element-wise less-than of tensors, returning a new boolean tensor.
Tensor LogicalXor_(const Tensor &value)
static Tensor Full(const SizeVector &shape, T fill_value, Dtype dtype, const Device &device=Device("CPU:0"))
Create a tensor fill with specified value.
std::shared_ptr< Blob > GetBlob() const
ConstIterator cbegin() const
Tensor operator*(Scalar value) const
bool AllEqual(const Tensor &other) const
Tensor Exp_()
Element-wise base-e exponential of a tensor, in-place.
Tensor Eq_(const Tensor &value)
int64_t WrapDim(int64_t dim, int64_t max_dim, bool inclusive)
Wrap around negative dim.
SizeVector DefaultStrides(const SizeVector &shape)
Compute default strides for a shape when a tensor is contiguous.
typename NestedInitializerImpl< T, D >::type NestedInitializerList
SizeVector InferShape(const L &list)
void AssertNotSYCL(const Tensor &tensor)
Tensor operator-(T scalar_lhs, const Tensor &rhs)
Tensor operator*(T scalar_lhs, const Tensor &rhs)
Tensor operator+(T scalar_lhs, const Tensor &rhs)
Tensor operator/(T scalar_lhs, const Tensor &rhs)
constexpr nullopt_t nullopt
Generic file read and write utility for python interface.
A versioned and managed C Tensor object, manage memory of DLTensor.
C Tensor object, manage memory of DLTensor. This data structure is intended to facilitate the borrowi...
Const iterator for Tensor.
std::ptrdiff_t difference_type
bool operator!=(const ConstIterator &other) const
ConstIterator(pointer tensor, int64_t index)
pointer operator->() const
reference operator*() const
std::forward_iterator_tag iterator_category
ConstIterator & operator++()
bool operator==(const ConstIterator &other) const
std::forward_iterator_tag iterator_category
pointer operator->() const
Iterator(pointer tensor, int64_t index)
bool operator==(const Iterator &other) const
std::ptrdiff_t difference_type
reference operator*() const
bool operator!=(const Iterator &other) const