| 305 | } |
| 306 | |
| 307 | void Tensor::FromProto(const singa::TensorProto &proto) { |
| 308 | if (block_ != nullptr && block_->DecRefCount() == 0) |
| 309 | device_->FreeBlock(block_); |
| 310 | block_ = nullptr; |
| 311 | for (uint32_t s : proto.shape()) shape_.push_back(s); |
| 312 | data_type_ = proto.data_type(); |
| 313 | block_ = device_->NewBlock((int)(Product(shape()) * SizeOf(data_type_))); |
| 314 | // transpose_ = proto.transpose(); |
| 315 | stride_.clear(); |
| 316 | for (int32_t s : proto.stride()) stride_.push_back(s); |
| 317 | switch (data_type_) { |
| 318 | case kFloat32: { |
| 319 | std::unique_ptr<float[]> data_ptr(new float[Product(shape_)]); |
| 320 | for (size_t i = 0; i < Product(shape_); ++i) |
| 321 | data_ptr[i] = static_cast<float>(proto.float_data((int)i)); |
| 322 | CopyDataFromHostPtr<float>(data_ptr.get(), Product(shape_)); |
| 323 | break; |
| 324 | } |
| 325 | case kDouble: { |
| 326 | std::unique_ptr<double[]> data(new double[Product(shape_)]); |
| 327 | for (size_t i = 0; i < Product(shape_); ++i) |
| 328 | data[i] = proto.double_data((int)i); |
| 329 | CopyDataFromHostPtr<double>(data.get(), Product(shape_)); |
| 330 | break; |
| 331 | } |
| 332 | case kInt: { |
| 333 | std::unique_ptr<int[]> data(new int[Product(shape_)]); |
| 334 | for (size_t i = 0; i < Product(shape_); ++i) |
| 335 | data[i] = proto.int_data((int)i); |
| 336 | CopyDataFromHostPtr<int>(data.get(), Product(shape_)); |
| 337 | break; |
| 338 | } |
| 339 | /// TODO(wangji): Implement to support C++ type char using bytes type in |
| 340 | /// protobuf |
| 341 | /// which is equivalent to string type is different from the other cases. |
| 342 | /// The kchar |
| 343 | /// and kUChar case is to be implemented. |
| 344 | /* |
| 345 | case kChar: { |
| 346 | std::unique_ptr<char[]> data(new char[Product(shape_)]); |
| 347 | for (size_t i = 0; i < Product(shape_); ++i) |
| 348 | data[i] = static_cast<char>(proto.bytes_data(i)); |
| 349 | break; |
| 350 | } |
| 351 | case kUChar: { |
| 352 | std::unique_ptr<unsigned char[]> data(new unsigned char[Product(shape_)]); |
| 353 | for (size_t i = 0; i < Product(shape_); ++i) |
| 354 | data[i] = static_cast<unsigned char>(proto.bytes_data(i)); |
| 355 | break; |
| 356 | } |
| 357 | */ |
| 358 | default: { |
| 359 | LOG(FATAL) << "Unsupported Type" << DataType_Name(data_type_); |
| 360 | } |
| 361 | } |
| 362 | } |
| 363 | |
| 364 | void Tensor::to_proto(singa::TensorProto *proto) const { |