Skip to content

Commit

Permalink
[fbsync] use from_blob to avoid memcpy (#4118)
Browse files Browse the repository at this point in the history
Summary:

Reviewed By: NicolasHug

Differential Revision: D29516853

fbshipit-source-id: 88d8c3962204071883317d1b2eb383900d90d430

Co-authored-by: Nicolas Hug <nicolashug@fb.com>
Co-authored-by: Vasilis Vryniotis <datumbox@users.noreply.github.com>
  • Loading branch information
3 people authored and facebook-github-bot committed Jul 1, 2021
1 parent e529d56 commit d8bd397
Showing 1 changed file with 8 additions and 14 deletions.
22 changes: 8 additions & 14 deletions torchvision/csrc/io/image/cpu/encode_jpeg.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@ using namespace detail;

torch::Tensor encode_jpeg(const torch::Tensor& data, int64_t quality) {
// Define compression structures and error handling
struct jpeg_compress_struct cinfo;
struct torch_jpeg_error_mgr jerr;
struct jpeg_compress_struct cinfo {};
struct torch_jpeg_error_mgr jerr {};

// Define buffer to write JPEG information to and its size
unsigned long jpegSize = 0;
uint8_t* jpegBuf = NULL;
uint8_t* jpegBuf = nullptr;

cinfo.err = jpeg_std_error(&jerr.pub);
jerr.pub.error_exit = torch_jpeg_error_exit;
Expand All @@ -34,7 +34,7 @@ torch::Tensor encode_jpeg(const torch::Tensor& data, int64_t quality) {
* We need to clean up the JPEG object and the buffer.
*/
jpeg_destroy_compress(&cinfo);
if (jpegBuf != NULL) {
if (jpegBuf != nullptr) {
free(jpegBuf);
}

Expand Down Expand Up @@ -92,16 +92,10 @@ torch::Tensor encode_jpeg(const torch::Tensor& data, int64_t quality) {
jpeg_destroy_compress(&cinfo);

torch::TensorOptions options = torch::TensorOptions{torch::kU8};
auto outTensor = torch::empty({(long)jpegSize}, options);

// Copy memory from jpeg buffer, since torch cannot get ownership of it via
// `from_blob`
auto outPtr = outTensor.data_ptr<uint8_t>();
std::memcpy(outPtr, jpegBuf, sizeof(uint8_t) * outTensor.numel());

free(jpegBuf);

return outTensor;
auto out_tensor =
torch::from_blob(jpegBuf, {(long)jpegSize}, ::free, options);
jpegBuf = nullptr;
return out_tensor;
}
#endif

Expand Down

0 comments on commit d8bd397

Please sign in to comment.