tensor.h 27.6 KB
Newer Older
1
// Copyright 2019-2020 Yan Yan
tusimple's avatar
tusimple committed
2
3
4
5
6
7
8
9
10
11
12
13
14
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

15
16
17
18
19
20
21
22
23
/*
tv::Tensor is a lightweight header-only tensor container
without template and annoying dependencies. no algorithm is implemented.
it should only be used when you want a no-template simple container but
dont want to link with libtorch.

If you can use libtorch, dont use tv::Tensor.
*/

tusimple's avatar
tusimple committed
24
#pragma once
25
#include "mp_helper.h"
tusimple's avatar
tusimple committed
26
#include "tensorview.h"
27
28
#include <cstring>
#include <iomanip>
tusimple's avatar
tusimple committed
29
#include <memory>
30
31
32
#include <type_traits>
#ifdef TV_CUDA
#include <cuda_fp16.h>
tusimple's avatar
tusimple committed
33
34
35
36
#include <cuda_runtime.h>
#include <cuda_runtime_api.h>
#endif

37
38
namespace tv {
enum DType {
tusimple's avatar
tusimple committed
39
40
41
42
43
44
45
46
47
48
49
50
51
52
  float32,
  int32,
  int16,
  int8,
  float64,
  bool_,
  uint8,
  float16,
  int64,
  uint16,
  uint32,
  uint64
};

53
namespace detail {
tusimple's avatar
tusimple committed
54

Yan Yan's avatar
Yan Yan committed
55
56
57
58
using dtype_collection_t =
    tv::mp_list_c<int, float32, int32, int16, int8, float64, bool_, uint8,
                  float16, int64, uint16, uint32, uint64>;

59
60
61
62
63
using all_tensor_types_t =
    std::tuple<float, double, int8_t, int16_t, int32_t, int64_t, uint8_t,
               uint16_t, uint32_t, uint64_t, bool>;

template <typename T> class TensorStorage {
tusimple's avatar
tusimple committed
64
public:
65
66
67
68
  TensorStorage(size_t size, int device = -1, bool managed = false,
                bool pinned = false)
      : mSize(size), device_(device), managed_(managed), pinned_(pinned) {
    if (size == 0) {
tusimple's avatar
tusimple committed
69
      mPtr = nullptr;
70
71
72
73
74
    } else {
      if (device == -1) {
        if (pinned_) {
#ifdef TV_CUDA
          checkCudaErrors(cudaMallocHost(&mPtr, size * sizeof(T)));
tusimple's avatar
tusimple committed
75
#else
76
          TV_THROW_INVALID_ARG("you need to define TV_CUDA to use pinned");
tusimple's avatar
tusimple committed
77
#endif
78
79
80
81
82
        } else {
          mPtr = new T[size];
        }
      } else {
#ifdef TV_CUDA
yanyan's avatar
yanyan committed
83
84
        // we should select device in external
        /*
tusimple's avatar
tusimple committed
85
86
        int deviceCount;
        cudaGetDeviceCount(&deviceCount);
87
88
89
        if (device >= deviceCount) {
          TV_THROW_INVALID_ARG("you provide device ", device,
                               " but you only have ", deviceCount, " device.");
tusimple's avatar
tusimple committed
90
91
        }
        cudaSetDevice(device);
yanyan's avatar
yanyan committed
92
        */
93
        if (managed) {
tusimple's avatar
tusimple committed
94
          checkCudaErrors(cudaMallocManaged(&this->mPtr, size * sizeof(T)));
95
        } else {
tusimple's avatar
tusimple committed
96
97
98
          checkCudaErrors(cudaMalloc(&mPtr, size * sizeof(T)));
        }
#else
99
        TV_THROW_INVALID_ARG("don't compiled with cuda");
tusimple's avatar
tusimple committed
100
101
102
103
104
105
106
#endif
      }
    }
  }
  TensorStorage(T *ptr, size_t size, int device)
      : mSize(size), mPtr(ptr), from_blob_(true), device_(device) {}

107
108
  virtual ~TensorStorage() {
    if (empty()) {
tusimple's avatar
tusimple committed
109
110
      return;
    }
111
    if (from_blob_) {
tusimple's avatar
tusimple committed
112
113
      return;
    }
114
115
116
117
    if (device_ == -1) {
      if (pinned_) {
#ifdef TV_CUDA
        cudaFreeHost(mPtr);
tusimple's avatar
tusimple committed
118
#endif
119
120
121
122
123
      } else {
        delete[] mPtr;
      }
    } else {
#ifdef TV_CUDA
tusimple's avatar
tusimple committed
124
125
126
127
128
129
130
131
132
133
134
135
      cudaFree(mPtr);
#endif
    }
  };

  inline size_t size() const { return mSize; }

  T *data() { return mPtr; }
  const T *data() const { return mPtr; }

  bool empty() const { return mPtr == nullptr || mSize == 0; }
  bool managed() const { return managed_; }
136
137
  bool pinned() const { return pinned_; }

tusimple's avatar
tusimple committed
138
  int device() const { return device_; }
139
140
  void zero_() {
    if (device_ == -1) {
tusimple's avatar
tusimple committed
141
142
      std::memset(data(), 0, mSize);
      // std::fill(data(), data() + mSize, 0);
143
144
    } else {
#ifdef TV_CUDA
tusimple's avatar
tusimple committed
145
146
      checkCudaErrors(cudaMemset(data(), 0, mSize / sizeof(T)));
#else
147
      TV_THROW_INVALID_ARG("don't compiled with cuda");
tusimple's avatar
tusimple committed
148
149
150
151
152
153
#endif
    }
  }

private:
  size_t mSize = 0;
154
  T *mPtr = nullptr;
tusimple's avatar
tusimple committed
155
  bool from_blob_ = false;
156
  int device_ = -1;
tusimple's avatar
tusimple committed
157
  bool managed_ = false;
158
  bool pinned_ = false;
tusimple's avatar
tusimple committed
159
160
};

161
162
template <typename T> size_t sizeof_dtype(T dtype) {
  switch (dtype) {
tusimple's avatar
tusimple committed
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
  case float32:
    return sizeof(float);
  case int8:
    return sizeof(int8_t);
  case int16:
    return sizeof(int16_t);
  case int32:
    return sizeof(int32_t);
  case float64:
    return sizeof(double);
  case int64:
    return sizeof(int64_t);
  case bool_:
    return sizeof(bool);
  case uint8:
    return sizeof(uint8_t);
  case uint16:
    return sizeof(uint16_t);
  case uint32:
    return sizeof(uint32_t);
  case uint64:
    return sizeof(uint64_t);
  case float16:
186
    return 2;
tusimple's avatar
tusimple committed
187
188
189
190
191
192
  default:
    TV_THROW_RT_ERR("unsupported dtype");
  }
  return 0;
}

193
194
template <typename T> std::string typeString(T t) {
  switch (t) {
tusimple's avatar
tusimple committed
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
  case DType::bool_:
    return "bool";
  case DType::float32:
    return "float32";
  case DType::int8:
    return "int8";
  case DType::int16:
    return "int16";
  case DType::int32:
    return "int32";
  case DType::float64:
    return "float64";
  case DType::int64:
    return "int64";
  case DType::uint8:
    return "uint8";
  case DType::uint16:
    return "uint16";
  case DType::uint32:
    return "uint32";
  case DType::uint64:
    return "uint64";
  case DType::float16:
    return "half";
  default:
    return "";
  }
}

224
225
226
227
228
229
230
231
232
233
234
template <typename T> struct TypeToDtypeTraits;

template <> struct TypeToDtypeTraits<int32_t> {
  static constexpr DType dtype = int32;
};

#ifdef TV_CUDA
template <> struct TypeToDtypeTraits<__half> {
  static constexpr DType dtype = float16;
};
#endif
tusimple's avatar
tusimple committed
235

236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
template <> struct TypeToDtypeTraits<float> {
  static constexpr DType dtype = float32;
};
template <> struct TypeToDtypeTraits<double> {
  static constexpr DType dtype = float64;
};
template <> struct TypeToDtypeTraits<int16_t> {
  static constexpr DType dtype = int16;
};
template <> struct TypeToDtypeTraits<int8_t> {
  static constexpr DType dtype = int8;
};
template <> struct TypeToDtypeTraits<int64_t> {
  static constexpr DType dtype = int64;
};
template <> struct TypeToDtypeTraits<uint8_t> {
  static constexpr DType dtype = uint8;
};
template <> struct TypeToDtypeTraits<uint16_t> {
  static constexpr DType dtype = uint16;
};
template <> struct TypeToDtypeTraits<uint32_t> {
  static constexpr DType dtype = uint32;
};
template <> struct TypeToDtypeTraits<uint64_t> {
  static constexpr DType dtype = uint64;
};
template <> struct TypeToDtypeTraits<bool> {
  static constexpr DType dtype = bool_;
};
template <> struct TypeToDtypeTraits<const int32_t> {
tusimple's avatar
tusimple committed
267
268
269
  static constexpr DType dtype = int32;
};

270
271
#ifdef TV_CUDA
template <> struct TypeToDtypeTraits<const __half> {
tusimple's avatar
tusimple committed
272
273
274
275
  static constexpr DType dtype = float16;
};
#endif

276
template <> struct TypeToDtypeTraits<const float> {
tusimple's avatar
tusimple committed
277
278
  static constexpr DType dtype = float32;
};
279
template <> struct TypeToDtypeTraits<const double> {
tusimple's avatar
tusimple committed
280
281
  static constexpr DType dtype = float64;
};
282
template <> struct TypeToDtypeTraits<const int16_t> {
tusimple's avatar
tusimple committed
283
284
  static constexpr DType dtype = int16;
};
285
template <> struct TypeToDtypeTraits<const int8_t> {
tusimple's avatar
tusimple committed
286
287
  static constexpr DType dtype = int8;
};
288
template <> struct TypeToDtypeTraits<const int64_t> {
tusimple's avatar
tusimple committed
289
290
  static constexpr DType dtype = int64;
};
291
template <> struct TypeToDtypeTraits<const uint8_t> {
tusimple's avatar
tusimple committed
292
293
  static constexpr DType dtype = uint8;
};
294
template <> struct TypeToDtypeTraits<const uint16_t> {
tusimple's avatar
tusimple committed
295
296
  static constexpr DType dtype = uint16;
};
297
template <> struct TypeToDtypeTraits<const uint32_t> {
tusimple's avatar
tusimple committed
298
299
  static constexpr DType dtype = uint32;
};
300
template <> struct TypeToDtypeTraits<const uint64_t> {
tusimple's avatar
tusimple committed
301
302
  static constexpr DType dtype = uint64;
};
303
304
305
template <> struct TypeToDtypeTraits<const bool> {
  static constexpr DType dtype = bool_;
};
tusimple's avatar
tusimple committed
306
307
308

} // namespace detail

309
template <class T> constexpr DType type_v = detail::TypeToDtypeTraits<T>::dtype;
tusimple's avatar
tusimple committed
310

311
template <class... Ts, typename F> bool dispatch_noexcept(DType t, F &&f) {
312
313
314
  static_assert(sizeof...(Ts) > 0, "you need to provide at least one type");
  bool notFound = true;
  mp_for_each<mp_list<Ts...>>([=, &notFound, &f](auto I) {
Yan Yan's avatar
Yan Yan committed
315
    if (type_v<decltype(I)> == t && notFound) {
316
317
318
319
      std::forward<F>(f)(decltype(I)());
      notFound = false;
    }
  });
320
321
322
323
324
  return !notFound;
}

template <class... Ts, typename F> void dispatch(DType t, F &&f) {
  if (!dispatch_noexcept<Ts...>(t, std::forward<F>(f))) {
325
326
327
328
329
330
331
332
333
334
335
336
337
338
    std::stringstream ss;
    mp_for_each<mp_list<Ts...>>([=, &ss](auto I) {
      ss << detail::TypeToString<decltype(I)>::value << " ";
    });
    TV_THROW_RT_ERR("unknown type", detail::typeString(t),
                    ", available:", ss.str());
  }
}

template <typename T, T... Is, typename F> void dispatch_scalar(T idx, F &&f) {
  static_assert(sizeof...(Is) > 0,
                "you need to provide at least one candidate");
  bool notFound = true;
  mp_for_each<mp_list_c<T, Is...>>([=, &notFound, &f](auto I) {
Yan Yan's avatar
Yan Yan committed
339
    if (T(I) == idx && notFound) {
340
341
342
343
344
345
346
347
348
349
350
      std::forward<F>(f)(I);
      notFound = false;
    }
  });
  if (notFound) {
    std::stringstream ss;
    mp_for_each<mp_list_c<T, Is...>>([=, &ss](auto I) { ss << T(I) << " "; });
    TV_THROW_RT_ERR("unknown value", idx, ", available:", ss.str());
  }
}

351
template <int... Is, typename F> bool dispatch_int_noexcept(int idx, F &&f) {
352
353
354
355
  static_assert(sizeof...(Is) > 0,
                "you need to provide at least one candidate");
  bool notFound = true;
  mp_for_each<mp_list_c<int, Is...>>([=, &notFound, &f](auto I) {
Yan Yan's avatar
Yan Yan committed
356
357
358
359
360
    if (decltype(I)::value == idx && notFound) {
      std::forward<F>(f)(I);
      notFound = false;
    }
  });
361
  return !notFound;
Yan Yan's avatar
Yan Yan committed
362
363
364
}

template <int... Is, typename F, class BinaryPredicate>
365
bool dispatch_int_noexcept(int idx, BinaryPredicate p, F &&f) {
Yan Yan's avatar
Yan Yan committed
366
367
368
369
370
  static_assert(sizeof...(Is) > 0,
                "you need to provide at least one candidate");
  bool notFound = true;
  mp_for_each<mp_list_c<int, Is...>>([=, &notFound, &f](auto I) {
    if (p(idx, decltype(I)::value) && notFound) {
371
372
373
374
      std::forward<F>(f)(I);
      notFound = false;
    }
  });
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
  return !notFound;
}

template <int... Is, typename F> void dispatch_int(int idx, F &&f) {
  if (!dispatch_int_noexcept<Is...>(idx, std::forward<F>(f))) {
    std::stringstream ss;
    mp_for_each<mp_list_c<int, Is...>>(
        [=, &ss](auto I) { ss << decltype(I)::value << " "; });
    TV_THROW_RT_ERR("unknown value", idx, ", available:", ss.str());
  }
}

template <int... Is, typename F, class BinaryPredicate>
void dispatch_int(int idx, BinaryPredicate p, F &&f) {
  // BinaryPredicate: BinaryPredicate(idx, candidate)
  if (!dispatch_int_noexcept<Is...>(idx, p, std::forward<F>(f))) {
391
392
    std::stringstream ss;
    mp_for_each<mp_list_c<int, Is...>>(
Yan Yan's avatar
Yan Yan committed
393
        [=, &ss](auto I) { ss << decltype(I)::value << " "; });
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
    TV_THROW_RT_ERR("unknown value", idx, ", available:", ss.str());
  }
}

/*
template <int... Is, typename F> void dispatch_int(int idx, F &&f) {
  return dispatch_scalar<int, Is...>(idx, f);
}
*/

template <class T> struct Dispatch;

template <template <class...> class T, class... Args>
struct Dispatch<T<Args...>> {
  template <typename F> inline void operator()(DType t, F &&f) {
    return dispatch<Args...>(t, std::forward<F>(f));
  }
};

template <class T> struct DispatchInt;

415
416
417
418
419
420
// Args should be std::integral_constant<int, value>
// you need to use type_container<std::integral_constant<int, value>...>
// as template parameter of DispatchInt.
// tv::mp_list_c is ok.
template <template <class...> class T, class... Args>
struct DispatchInt<T<Args...>> {
421
  template <typename F> inline void operator()(int t, F &&f) {
422
    return dispatch_int<Args::value...>(t, std::forward<F>(f));
423
  }
424
425
426
  template <typename F, typename BinaryPredicate>
  inline void operator()(int t, BinaryPredicate p, F &&f) {
    return dispatch_int<Args::value...>(t, p, std::forward<F>(f));
Yan Yan's avatar
Yan Yan committed
427
  }
428
};
Yan Yan's avatar
Yan Yan committed
429

430
431
432
433
constexpr size_t kTensorMaxDim = 10;
using TensorShape = ShapeBase<kTensorMaxDim, int64_t>;

struct Tensor {
tusimple's avatar
tusimple committed
434
  Tensor() {}
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
  Tensor(TensorShape shape, TensorShape stride, DType dtype, int device = -1,
         bool pinned = false, bool managed = false)
      : dtype_(dtype) {
    TV_ASSERT_INVALID_ARG(!shape.empty(), "dont support empty shape");
    storage_ = std::make_shared<detail::TensorStorage<uint8_t>>(
        shape.size() * detail::sizeof_dtype(dtype), device, managed, pinned);
    shape_ = shape;
    stride_ = stride;
  }

  Tensor(TensorShape shape, DType dtype, int device = -1, bool pinned = false,
         bool managed = false)
      : dtype_(dtype) {
    TV_ASSERT_INVALID_ARG(!shape.empty(), "dont support empty shape");
    storage_ = std::make_shared<detail::TensorStorage<uint8_t>>(
        shape.size() * detail::sizeof_dtype(dtype), device, managed, pinned);
    shape_ = shape;
    stride_ = shape.stride_rowmajor();
  }
  Tensor(void *ptr, TensorShape shape, TensorShape stride, DType dtype,
         int device = -1)
      : dtype_(dtype) {
    TV_ASSERT_INVALID_ARG(!shape.empty(), "dont support empty shape");
tusimple's avatar
tusimple committed
458
    storage_ = std::make_shared<detail::TensorStorage<uint8_t>>(
459
460
        reinterpret_cast<uint8_t *>(ptr),
        shape.size() * detail::sizeof_dtype(dtype), device);
tusimple's avatar
tusimple committed
461
    shape_ = shape;
462
    stride_ = stride;
tusimple's avatar
tusimple committed
463
  }
464
465
466
  Tensor(void *ptr, TensorShape shape, DType dtype, int device = -1)
      : dtype_(dtype) {
    TV_ASSERT_INVALID_ARG(!shape.empty(), "dont support empty shape");
tusimple's avatar
tusimple committed
467
468
469
470
    storage_ = std::make_shared<detail::TensorStorage<uint8_t>>(
        reinterpret_cast<uint8_t *>(ptr),
        shape.size() * detail::sizeof_dtype(dtype), device);
    shape_ = shape;
471
    stride_ = shape.stride_rowmajor();
tusimple's avatar
tusimple committed
472
473
  }

474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
  Tensor(const void *ptr, TensorShape shape, TensorShape stride, DType dtype,
         int device = -1)
      : dtype_(dtype), writeable_(false) {
    TV_ASSERT_INVALID_ARG(!shape.empty(), "dont support empty shape");
    storage_ = std::make_shared<detail::TensorStorage<uint8_t>>(
        reinterpret_cast<uint8_t *>(const_cast<void *>(ptr)),
        shape.size() * detail::sizeof_dtype(dtype), device);
    shape_ = shape;
    stride_ = stride;
  }
  Tensor(const void *ptr, TensorShape shape, DType dtype, int device = -1)
      : dtype_(dtype), writeable_(false) {
    TV_ASSERT_INVALID_ARG(!shape.empty(), "dont support empty shape");
    storage_ = std::make_shared<detail::TensorStorage<uint8_t>>(
        reinterpret_cast<uint8_t *>(const_cast<void *>(ptr)),
        shape.size() * detail::sizeof_dtype(dtype), device);
    shape_ = shape;
    stride_ = shape.stride_rowmajor();
  }

  Tensor(std::initializer_list<int32_t> init)
      : Tensor({int(init.size())}, tv::int32) {
    std::copy(init.begin(), init.end(), data<int32_t>());
  }
  Tensor(std::initializer_list<int64_t> init)
      : Tensor({int(init.size())}, tv::int64) {
    std::copy(init.begin(), init.end(), data<int64_t>());
  }
  Tensor(std::initializer_list<float> init)
      : Tensor({int(init.size())}, tv::float32) {
    std::copy(init.begin(), init.end(), data<float>());
  }
  Tensor(std::initializer_list<double> init)
      : Tensor({int(init.size())}, tv::float64) {
    std::copy(init.begin(), init.end(), data<double>());
  }

  template <typename T, int Rank = -1,
            template <class> class PtrTraits = DefaultPtrTraits,
            typename Tindex = int,
            typename std::enable_if<(Rank > 0), int>::type = 0>
  TensorView<T, Rank, PtrTraits, Tindex> tview() {
    using tv_shape_t =
        typename TensorView<T, Rank, PtrTraits, Tindex>::tv_shape_t;
    writable_check();
    static_assert(Rank == -1 || Rank > 0, "error");
tusimple's avatar
tusimple committed
520
    TV_ASSERT_RT_ERR(dtype_ == type_v<T>, "error");
521
522
523
524
525
526
527
    tv_shape_t shape(Rank), stride(Rank);
    for (int i = 0; i < Rank; ++i) {
      shape[i] = shape_[i];
      stride[i] = stride_[i];
    }
    return TensorView<T, Rank, PtrTraits, Tindex>(
        reinterpret_cast<T *>(data<T>()), shape, stride);
tusimple's avatar
tusimple committed
528
  }
529
530
531
532
533
534
535
536
537
  template <typename T, int Rank = -1,
            template <class> class PtrTraits = DefaultPtrTraits,
            typename Tindex = int,
            typename std::enable_if<Rank == -1, int>::type = 0>
  TensorView<T, Rank, PtrTraits, Tindex> tview() {
    using tv_shape_t =
        typename TensorView<T, Rank, PtrTraits, Tindex>::tv_shape_t;
    writable_check();
    static_assert(Rank == -1 || Rank > 0, "error");
tusimple's avatar
tusimple committed
538
    TV_ASSERT_RT_ERR(dtype_ == type_v<T>, "error");
539
540
541
542
543
544
545
    ShapeBase<TV_MAX_DIM, Tindex> shape(ndim()), stride(ndim());
    for (int i = 0; i < ndim(); ++i) {
      shape[i] = shape_[i];
      stride[i] = stride_[i];
    }
    return TensorView<T, Rank, PtrTraits, Tindex>(
        reinterpret_cast<T *>(data<T>()), shape, stride);
tusimple's avatar
tusimple committed
546
  }
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661

  template <typename T, int Rank = -1,
            template <class> class PtrTraits = DefaultPtrTraits,
            typename Tindex = int,
            typename std::enable_if<(Rank > 0), int>::type = 0>
  TensorView<const std::remove_const_t<T>, Rank, PtrTraits, Tindex>
  tview() const {
    static_assert(Rank == -1 || Rank > 0, "error");
    if (Rank > 0) {
      TV_ASSERT_RT_ERR(Rank == ndim(), "error");
    }
    TV_ASSERT_RT_ERR(dtype_ == type_v<T>, "error");

    ShapeBase<Rank == -1 ? TV_MAX_DIM : Rank, Tindex> shape(Rank), stride(Rank);
    for (int i = 0; i < Rank; ++i) {
      shape[i] = shape_[i];
      stride[i] = stride_[i];
    }
    return TensorView<const std::remove_const_t<T>, Rank, PtrTraits, Tindex>(
        reinterpret_cast<const std::remove_const_t<T> *>(data<T>()), shape,
        stride);
  }
  template <typename T, int Rank = -1,
            template <class> class PtrTraits = DefaultPtrTraits,
            typename Tindex = int,
            typename std::enable_if<Rank == -1, int>::type = 0>
  TensorView<const std::remove_const_t<T>, Rank, PtrTraits, Tindex>
  tview() const {
    static_assert(Rank == -1 || Rank > 0, "error");
    if (Rank > 0) {
      TV_ASSERT_RT_ERR(Rank == ndim(), "error");
    }
    TV_ASSERT_RT_ERR(dtype_ == type_v<T>, "error");

    ShapeBase<TV_MAX_DIM, Tindex> shape(ndim()), stride(ndim());
    for (int i = 0; i < ndim(); ++i) {
      shape[i] = shape_[i];
      stride[i] = stride_[i];
    }
    return TensorView<const std::remove_const_t<T>, Rank, PtrTraits, Tindex>(
        reinterpret_cast<const std::remove_const_t<T> *>(data<T>()), shape,
        stride);
  }

  template <class... Inds> Tensor view(Inds... newShapes) const {
    static_assert(sizeof...(newShapes) > 0, "dont support empty for now");
    TensorShape shape{int(newShapes)...};
    bool found_minus_1 = false;
    for (size_t i = 0; i < shape.ndim(); ++i) {
      if (!found_minus_1) {
        if (shape[i] == -1) {
          shape[i] = 1;
          shape[i] = size() / shape.size();
          found_minus_1 = true;
        } else {
          TV_ASSERT_INVALID_ARG(shape[i] > 0,
                                "shape except -1 must larger than 0");
        }
      } else {
        TV_ASSERT_INVALID_ARG(shape[i] > 0, "multiple -1 in your argument.");
      }
    }
    TV_ASSERT_RT_ERR(shape.size() == size(), "error");
    Tensor res(*this);
    res.shape_ = shape;
    res.stride_ = shape.stride_rowmajor();
    return res;
  }

  Tensor view(TensorShape shape) const {
    TV_ASSERT_RT_ERR(shape.size() == size(), "error");
    Tensor res(*this);
    res.shape_ = shape;
    res.stride_ = shape.stride_rowmajor();
    return res;
  }

  Tensor squeeze() const { return view(shape_.squeeze()); }

  Tensor squeeze(int axis) const {
    if (axis < 0) {
      axis = ndim() + axis;
    }
    return view(shape_.squeeze(axis));
  }

  Tensor unsqueeze(int axis) const {
    if (axis < 0) {
      axis = ndim() + axis;
    }
    return view(shape_.unsqueeze(axis));
  }

  bool pinned() const { return storage_->pinned(); }

  Tensor slice_first_axis(int start, int end) const {
    TV_ASSERT_INVALID_ARG(contiguous_, "only support contiguous for now");
    if (start < 0) {
      start = shape_[0] + start;
    }
    if (end < 0) {
      end = shape_[0] + end;
    }
    TV_ASSERT_INVALID_ARG(start < shape_[0], "start must small than dim 0");
    TV_ASSERT_INVALID_ARG(start < end, "start must small than end");
    size_t new_offset = start * shape_.prod(1) * itemsize();
    Tensor res(*this);
    TensorShape newshape(shape_);
    newshape[0] = end - start;
    res.shape_ = newshape;
    res.stride_ = stride_;
    res.offset_ = new_offset;
    return res;
  }

tusimple's avatar
tusimple committed
662
663
664
  bool empty() const { return storage_->empty(); }
  DType dtype() const { return dtype_; }
  int device() const { return storage_->device(); }
665
666
667
668
669
670
671
672
673
674
675
676
677
  size_t ndim() const { return shape_.ndim(); }

  const TensorShape &shape() const { return shape_; }
  const TensorShape &stride() const { return stride_; }

  int dim(int idx) const {
    if (idx < 0) {
      TV_ASSERT_RT_ERR(shape_.size() + idx < shape_.size(), idx, shape_);
      return shape_[shape_.size() + idx];
    } else {
      TV_ASSERT_RT_ERR(idx < int(shape_.size()), idx, shape_);
      return shape_[idx];
    }
tusimple's avatar
tusimple committed
678
  }
679
680
  const uint8_t *raw_data() const { return storage_->data() + offset_; }
  size_t raw_size() const { return size() * itemsize(); }
tusimple's avatar
tusimple committed
681
  size_t size() const { return shape_.size(); }
682
683
684
  size_t itemsize() const { return detail::sizeof_dtype(dtype_); }
  Tensor &zero_() {
    writable_check();
tusimple's avatar
tusimple committed
685
686
687
    storage_->zero_();
    return *this;
  }
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
  uint8_t *raw_data() {
    writable_check();
    return storage_->data() + offset_;
  }
  template <typename T> Tensor &fill_(T value) {
    writable_check();
    TV_ASSERT_RT_ERR(device() == -1, "error");
    Dispatch<detail::all_tensor_types_t>()(dtype_, [&](auto I) {
      using Treal = decltype(I);
      if (std::is_convertible<T, Treal>::value) {
        auto ptr = reinterpret_cast<Treal *>(raw_data());
        std::fill(ptr, ptr + size(), Treal(value));
      } else {
        TV_THROW_INVALID_ARG("not convertable from", type_s<T>, "to",
                             type_s<Treal>);
      }
    });
tusimple's avatar
tusimple committed
705
706
707
    return *this;
  }

708
  template <typename T> T *data() {
tusimple's avatar
tusimple committed
709
    TV_ASSERT_RT_ERR(dtype_ == type_v<T>, "error");
710
    writable_check();
tusimple's avatar
tusimple committed
711
712
713
    return reinterpret_cast<T *>(raw_data());
  }

714
  template <typename T> const T *data() const {
tusimple's avatar
tusimple committed
715
716
717
718
    TV_ASSERT_RT_ERR(dtype_ == type_v<T>, "error");
    return reinterpret_cast<const T *>(raw_data());
  }

719
720
721
  void copy_(const Tensor &tensor) {
    writable_check();
    TV_ASSERT_INVALID_ARG(contiguous_, "only support contiguous for now");
tusimple's avatar
tusimple committed
722
723
    TV_ASSERT_RT_ERR(!empty() && !tensor.empty(), "must not empty");
    TV_ASSERT_RT_ERR(size() == tensor.size(), "must have same size");
724
725
726
727
728
    TV_ASSERT_RT_ERR(dtype() == tensor.dtype(), "must have same dtype",
                     detail::typeString(dtype()),
                     detail::typeString(tensor.dtype()));
    if (device() == -1 && tensor.device() == -1) {
#ifdef TV_CUDA
tusimple's avatar
tusimple committed
729
730
731
732
733
734
735
736
      host2host(storage_->data(), tensor.raw_data(),
                size() * detail::sizeof_dtype(dtype_));
#else
      std::copy(tensor.raw_data(),
                tensor.raw_data() + size() * detail::sizeof_dtype(dtype_),
                storage_->data());
#endif
    }
737
738
#ifdef TV_CUDA
    else if (device() >= 0 && tensor.device() == -1) {
tusimple's avatar
tusimple committed
739
740
      host2dev(storage_->data(), tensor.raw_data(),
               size() * detail::sizeof_dtype(dtype_));
741
    } else if (device() == -1 && tensor.device() >= 0) {
tusimple's avatar
tusimple committed
742
743
      dev2host(storage_->data(), tensor.raw_data(),
               size() * detail::sizeof_dtype(dtype_));
744
    } else if (device() >= 0 && tensor.device() >= 0) {
tusimple's avatar
tusimple committed
745
746
747
748
      dev2dev(storage_->data(), tensor.raw_data(),
              size() * detail::sizeof_dtype(dtype_));
    }
#endif
749
750
    else {
      TV_THROW_RT_ERR("only support cpu tensor");
tusimple's avatar
tusimple committed
751
752
753
    }
  }

754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
#ifdef TV_CUDA
  void copy_(const Tensor &tensor, cudaStream_t stream) {
    writable_check();
    TV_ASSERT_INVALID_ARG(contiguous_, "only support contiguous for now");
    TV_ASSERT_RT_ERR(!empty() && !tensor.empty(), "must not empty");
    TV_ASSERT_RT_ERR(size() == tensor.size(), "must have same size");
    TV_ASSERT_RT_ERR(dtype() == tensor.dtype(), "must have same dtype",
                     detail::typeString(dtype()),
                     detail::typeString(tensor.dtype()));
    if (device() == -1 && tensor.device() == -1) {
      host2host(storage_->data(), tensor.raw_data(),
                size() * detail::sizeof_dtype(dtype_), stream);
    } else if (device() >= 0 && tensor.device() == -1) {
      host2dev(storage_->data(), tensor.raw_data(),
               size() * detail::sizeof_dtype(dtype_), stream);
    } else if (device() == -1 && tensor.device() >= 0) {
      dev2host(storage_->data(), tensor.raw_data(),
               size() * detail::sizeof_dtype(dtype_), stream);
    } else if (device() >= 0 && tensor.device() >= 0) {
      dev2dev(storage_->data(), tensor.raw_data(),
              size() * detail::sizeof_dtype(dtype_), stream);
    } else {
      TV_THROW_RT_ERR("only support cpu tensor");
tusimple's avatar
tusimple committed
777
    }
778
779
780
781
782
783
784
785
786
  }
#endif

  Tensor cpu() const {
    if (storage_->device() == -1) {
      // cpu() should always copy tensor.
      return clone();
    }
    Tensor res(shape_, stride_, dtype_, -1, storage_->managed());
tusimple's avatar
tusimple committed
787
788
789
790
    res.copy_(*this);
    return res;
  }

791
792
793
  template <typename T> void copy_(const TensorView<T> &tensor, int device) {
    writable_check();
    TV_ASSERT_INVALID_ARG(contiguous_, "only support contiguous for now");
tusimple's avatar
tusimple committed
794
795
796
797
    Tensor src = from_blob(tensor, device);
    return copy_(src);
  }

798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
  Tensor &operator=(const Tensor &tensor) {
    dtype_ = tensor.dtype_;
    storage_ = tensor.storage_;
    shape_ = tensor.shape_;
    writeable_ = tensor.writeable_;
    offset_ = tensor.offset_;
    stride_ = tensor.stride_;
    return *this;
  }

  Tensor(const Tensor &tensor) {
    dtype_ = tensor.dtype_;
    storage_ = tensor.storage_;
    shape_ = tensor.shape_;
    writeable_ = tensor.writeable_;
    offset_ = tensor.offset_;
    stride_ = tensor.stride_;
  }

  Tensor clone(bool pinned = false) const {
    TV_ASSERT_RT_ERR(!empty(), "clone a empty tensor");
    TV_ASSERT_INVALID_ARG(contiguous_, "only support contiguous for now");
    Tensor newtensor(shape_, stride_, dtype_, device(), pinned,
                     storage_->managed());
    newtensor.copy_(*this);
    return newtensor;
  }

  Tensor astype(DType dtype) {
    if (dtype == dtype_) {
      return clone();
    }
    TV_ASSERT_INVALID_ARG(device() == -1, "only support cpu tensor");
    TV_ASSERT_INVALID_ARG(!empty(), "can't be used in empty tensor");
    TV_ASSERT_INVALID_ARG(contiguous_, "only support contiguous for now");
    auto tensor = Tensor();
    Dispatch<detail::all_tensor_types_t>()(dtype, [&](auto Idst) {
      using Tdst = decltype(Idst);
      Dispatch<detail::all_tensor_types_t>()(dtype_, [&](auto Icur) {
        using Tcur = decltype(Icur);
        if (std::is_convertible<Tcur, Tdst>::value) {
          auto ptr = data<Tcur>();
          tensor = Tensor(shape_, stride_, dtype, device(), pinned(),
                          storage_->managed());
          std::copy(ptr, ptr + size(), tensor.data<Tdst>());
        } else {
          TV_THROW_INVALID_ARG("not convertable from", type_s<Tcur>, "to",
                               type_s<Tdst>);
        }
      });
    });
    return tensor;
  }

  template <class... Ts, typename F> inline void dispatch(F &&f) {
    return tv::dispatch<Ts...>(dtype_, std::forward<F>(f));
  }

tusimple's avatar
tusimple committed
856
protected:
857
858
859
860
861
  inline void writable_check() {
    TV_ASSERT_RT_ERR(writeable_,
                     "you cant do non-const operation when not writable");
  }

tusimple's avatar
tusimple committed
862
863
  DType dtype_;
  std::shared_ptr<detail::TensorStorage<uint8_t>> storage_;
864
865
866
867
868
869
870
  TensorShape shape_;
  size_t offset_ = 0;
  TensorShape stride_;

private:
  bool writeable_ = true;
  bool contiguous_ = true;
tusimple's avatar
tusimple committed
871
872
};

873
874
875
876
877
878
879
880
881
882
883
template <typename Os> Os &operator<<(Os &os, const Tensor &tensor) {
  TV_ASSERT_INVALID_ARG(tensor.device() == -1, "must be cpu tensor");
  Dispatch<detail::all_tensor_types_t>()(tensor.dtype(), [&](auto I) {
    using T = decltype(I);
    std::stringstream ss;
    if (std::is_same<T, float>::value || std::is_same<T, double>::value) {
      ss << std::setprecision(4);
    }
    os << tensor.tview<T, -1, DefaultPtrTraits, int64_t>().repr(ss);
  });
  return os;
tusimple's avatar
tusimple committed
884
885
}

886
887
inline Tensor from_blob(void *ptr, TensorShape shape, DType dtype, int device) {
  return Tensor(ptr, shape, dtype, device);
tusimple's avatar
tusimple committed
888
889
}

890
891
892
inline Tensor from_blob(const void *ptr, TensorShape shape, DType dtype,
                        int device) {
  return Tensor(ptr, shape, dtype, device);
tusimple's avatar
tusimple committed
893
894
895
}

} // namespace tv