Performing Inference with input already in GPU

username: solarflarefx
cooked: <p>Hi all,</p>
<p>I have a trained model in Python but ultimately want to run inference in C++.  I followed the procedure to save a serialized model with Torchscript.  I then load the model and then put it into the GPU.</p>
<p>I am working in a pipeline where all data resides in the GPU.  Now my question is if it is possible to take advantage of the fact that the data is already in the GPU and somehow convert this to a PyTorch GPU tensor, without having to perform and host/device copies.  I believe I have found an example of something similar: <a href="https://github.com/pytorch/pytorch/issues/19786" rel="nofollow noopener">https://github.com/pytorch/pytorch/issues/19786</a></p>
<p>The link references a post that shows how to convert a cv::cuda::GpuMat of type 32F to a torch::Tensor.  This isn’t exactly what I would like to do as I am not working with cv::cuda::GpuMat types, but the data resides in Cuda memory and I believe the concept is similar.  Essentially the method torch::from_blob is used for the conversion.</p>
<p>I have also found another post: <a href="https://discuss.pytorch.org/t/constructing-pytorchs-cuda-tensor-from-c-with-image-data-already-on-gpu/3124" class="inline-onebox">Constructing PyTorch's CUDA tensor from C++ with image data already on GPU</a></p>
<p>However, this post does not seem to reference torch::from_blob.  Rather, talks about using pointer references and using the cudaMemCpyAsync method.  However, unless I am mistaken I believe this does do a host/device copy.</p>
<p>Am I on the right track here?</p>

username: solarflarefx
cooked: <p>Ok so I experimented a bit with this, but I got different results when using Mat vs. GpuMat.</p>
<p>Mat code:</p>
<pre><code class="lang-auto">#include &lt;torch/script.h&gt;
#include &lt;torch/torch.h&gt;
#include &lt;opencv2/opencv.hpp&gt;
#include &lt;opencv2/imgproc/imgproc.hpp&gt;
#include &lt;opencv2/core/core.hpp&gt;
#include &lt;opencv2/highgui/highgui.hpp&gt;
#include &lt;iostream&gt;
#include &lt;memory&gt;
#include &lt;iomanip&gt;

std::string type2str(int type) {
    std::string r;

    uchar depth = type &amp; CV_MAT_DEPTH_MASK;
    uchar chans = 1 + (type &gt;&gt; CV_CN_SHIFT);

    switch (depth) {
    case CV_8U:  r = "8U"; break;
    case CV_8S:  r = "8S"; break;
    case CV_16U: r = "16U"; break;
    case CV_16S: r = "16S"; break;
    case CV_32S: r = "32S"; break;
    case CV_32F: r = "32F"; break;
    case CV_64F: r = "64F"; break;
    default:     r = "User"; break;
    }

    r += "C";
    r += (chans + '0');

    return r;
}

int main(int argc, const char* argv[]) {


    // Load up GPU stuff
    torch::DeviceType device_type;
    if (torch::cuda::is_available()) {
        std::cout &lt;&lt; "CUDA available! Training on GPU." &lt;&lt; std::endl;
        device_type = torch::kCUDA;
    }
    else {
        std::cout &lt;&lt; "Training on CPU." &lt;&lt; std::endl;
        device_type = torch::kCPU;
    }
    torch::Device device(device_type);
    torch::data::transforms::Normalize&lt;&gt; normalize_transform({ 0.485, 0.456, 0.406 }, { 0.229, 0.224, 0.225 });
    torch::jit::script::Module module;
    std::cout &lt;&lt; "Attempting to load resnet model.." &lt;&lt; std::endl;
    try {
        // Deserialize the ScriptModule from a file using torch::jit::load().
        module = torch::jit::load("C:\\PyTorchPictureTest\\Model\\traced_resnet_model_pretrained.pt");
        std::cout &lt;&lt; "Successfully loaded resnet model" &lt;&lt; std::endl;

        module.to(at::kCUDA);
        std::cout &lt;&lt; "Moved model to gpu" &lt;&lt; std::endl;

        // load image and transform
        cv::Mat image;
        image = cv::imread("C:\\PyTorchPictureTest\\dog.jpg", cv::IMREAD_COLOR);
        cv::cvtColor(image, image, cv::COLOR_BGR2RGB);
        cv::Mat img_float;
        image.convertTo(img_float, CV_32FC3, 1.0f / 255.0f);


        // Scale image down
        int scaledown_factor = 256;
        cv::resize(img_float, img_float, cv::Size(img_float.cols / (img_float.rows / (float)scaledown_factor), scaledown_factor), cv::INTER_NEAREST);

        // Emulate transforms.CenterCrop(224)
        cv::Rect roi;
        int new_width = 224;
        int new_height = 224;
        roi.x = img_float.size().width / 2 - new_width / 2;
        roi.width = new_width;
        roi.y = img_float.size().height / 2 - new_height / 2;
        roi.height = new_height;
        cv::Mat img_cropped = img_float(roi);

        // Convert to tensor
        auto img_tensor = torch::from_blob(img_cropped.data, { img_cropped.rows, img_cropped.cols, 3 });
        img_tensor = img_tensor.permute({ 2, 0, 1 });
        img_tensor[0][0] = img_tensor[0][0].sub(0.485).div(0.229);
        img_tensor[0][1] = img_tensor[0][1].sub(0.456).div(0.224);
        img_tensor[0][2] = img_tensor[0][2].sub(0.406).div(0.225);
        auto img_var = torch::autograd::make_variable(img_tensor, false);
        std::cout &lt;&lt; img_tensor.sizes() &lt;&lt; '\n';

        std::vector&lt;torch::jit::IValue&gt; inputs;
        inputs.push_back(img_tensor.unsqueeze_(0).to(at::kCUDA));

        // forward pass
        torch::Tensor out_tensor = module.forward(inputs).toTensor();

        // print output
        std::cout &lt;&lt; out_tensor &lt;&lt; '\n';

        // Write tensor to file
        std::ofstream myfile("OutputfromMatProcessing.txt");
        if (myfile.is_open())
        {
            for (int i = 0; i &lt; out_tensor.sizes()[1] - 1; i++) {
                myfile &lt;&lt; out_tensor[0][i].item&lt;float_t&gt;() &lt;&lt; "\n";
            }
            myfile &lt;&lt; out_tensor[0][out_tensor.sizes()[1] - 1].item&lt;float_t&gt;() &lt;&lt; "\n";
            myfile.close();
        }
        else std::cout &lt;&lt; "Unable to open file";


    }
    catch (const c10::Error &amp; e) {
        std::cerr &lt;&lt; "error loading the model\n";
        return -1;
    }

    std::cout &lt;&lt; "ok\n";
}
</code></pre>
<p>GpuMat Code:</p>
<pre><code class="lang-auto">#include &lt;torch/script.h&gt;
#include &lt;torch/torch.h&gt;
#include &lt;opencv2/opencv.hpp&gt;
#include &lt;opencv2/imgproc/imgproc.hpp&gt;
#include &lt;opencv2/core/core.hpp&gt;
#include &lt;opencv2/highgui/highgui.hpp&gt;
#include &lt;iostream&gt;
#include &lt;memory&gt;
#include &lt;iomanip&gt;

std::string type2str(int type) {
    std::string r;

    uchar depth = type &amp; CV_MAT_DEPTH_MASK;
    uchar chans = 1 + (type &gt;&gt; CV_CN_SHIFT);

    switch (depth) {
    case CV_8U:  r = "8U"; break;
    case CV_8S:  r = "8S"; break;
    case CV_16U: r = "16U"; break;
    case CV_16S: r = "16S"; break;
    case CV_32S: r = "32S"; break;
    case CV_32F: r = "32F"; break;
    case CV_64F: r = "64F"; break;
    default:     r = "User"; break;
    }

    r += "C";
    r += (chans + '0');

    return r;
}

void deleter(void* arg) {};

int main(int argc, const char* argv[]) {


    // Load up GPU stuff
    torch::DeviceType device_type;
    if (torch::cuda::is_available()) {
        std::cout &lt;&lt; "CUDA available! Training on GPU." &lt;&lt; std::endl;
        device_type = torch::kCUDA;
    }
    else {
        std::cout &lt;&lt; "Training on CPU." &lt;&lt; std::endl;
        device_type = torch::kCPU;
    }
    torch::Device device(device_type);
    torch::data::transforms::Normalize&lt;&gt; normalize_transform({ 0.485, 0.456, 0.406 }, { 0.229, 0.224, 0.225 });
    torch::jit::script::Module module;
    std::cout &lt;&lt; "Attempting to load resnet model.." &lt;&lt; std::endl;
    try {
        // Deserialize the ScriptModule from a file using torch::jit::load().
        module = torch::jit::load("C:\\PyTorchPictureTest\\Model\\traced_resnet_model_pretrained.pt");
        std::cout &lt;&lt; "Successfully loaded resnet model" &lt;&lt; std::endl;

        module.to(at::kCUDA);
        std::cout &lt;&lt; "Moved model to gpu" &lt;&lt; std::endl;

        // load image and transform
        cv::Mat image;
        image = cv::imread("C:\\PyTorchPictureTest\\dog.jpg", cv::IMREAD_COLOR);
        cv::cvtColor(image, image, cv::COLOR_BGR2RGB);
        cv::Mat img_float;
        image.convertTo(img_float, CV_32FC3, 1.0f / 255.0f);


        // Scale image down
        int scaledown_factor = 256;
        cv::resize(img_float, img_float, cv::Size(img_float.cols / (img_float.rows / (float)scaledown_factor), scaledown_factor), cv::INTER_NEAREST);

        // Emulate transforms.CenterCrop(224)
        cv::Rect roi;
        int new_width = 224;
        int new_height = 224;
        roi.x = img_float.size().width / 2 - new_width / 2;
        roi.width = new_width;
        roi.y = img_float.size().height / 2 - new_height / 2;
        roi.height = new_height;
        cv::Mat img_cropped = img_float(roi);

        cv::cuda::GpuMat gpu_image;
        gpu_image.upload(img_cropped);

        std::vector&lt;int64_t&gt; dims = { gpu_image.rows, gpu_image.cols, 3 };
        long long step = gpu_image.step / sizeof(float);
        std::vector&lt;int64_t&gt; strides = { step, 3, 1 };
        auto img_tensor = torch::from_blob(gpu_image.data, dims, strides, deleter, torch::kCUDA);

        // Convert to tensor;
        img_tensor = img_tensor.permute({ 2, 0, 1 });
        img_tensor[0][0] = img_tensor[0][0].sub(0.485).div(0.229);
        img_tensor[0][1] = img_tensor[0][1].sub(0.456).div(0.224);
        img_tensor[0][2] = img_tensor[0][2].sub(0.406).div(0.225);
        std::cout &lt;&lt; img_tensor.sizes() &lt;&lt; '\n';

        std::vector&lt;torch::jit::IValue&gt; inputs;
        inputs.push_back(img_tensor.unsqueeze_(0).to(at::kCUDA));

        // forward pass
        torch::Tensor out_tensor = module.forward(inputs).toTensor();

        // print output
        std::cout &lt;&lt; out_tensor &lt;&lt; '\n';

        // Write tensor to file
        std::ofstream myfile("OutputfromGpuMatProcessing.txt");
        if (myfile.is_open())
        {
            for (int i = 0; i &lt; out_tensor.sizes()[1] - 1; i++) {
                myfile &lt;&lt; out_tensor[0][i].item&lt;float_t&gt;() &lt;&lt; "\n";
            }
            myfile &lt;&lt; out_tensor[0][out_tensor.sizes()[1] - 1].item&lt;float_t&gt;() &lt;&lt; "\n";
            myfile.close();
        }
        else std::cout &lt;&lt; "Unable to open file";


    }
    catch (const c10::Error &amp; e) {
        std::cerr &lt;&lt; "error loading the model\n";
        return -1;
    }

    std::cout &lt;&lt; "ok\n";
}
</code></pre>
<p>However, I do not seem to be getting the same outputs.</p>
<p>Fore example, first 10 outputs in Mat version:<br>
-0.630255<br>
-0.562184<br>
-0.558607<br>
-1.53902<br>
-0.712656<br>
-0.198479<br>
-0.437339<br>
0.591292<br>
0.491775<br>
-0.71214</p>
<p>First 10 outputs in GpuMat version:<br>
-0.598255<br>
-0.585769<br>
-0.610221<br>
-1.58523<br>
-0.771842<br>
-0.215817<br>
-0.574213<br>
0.463584<br>
0.402193<br>
-0.723421</p>
<p>Am I using the from_blob function incorrectly?</p>

username: solarflarefx
cooked: <p><a class="mention" href="/u/tom">@tom</a> Do you have any insight on this?  Also when you use the from_blob method with the source data already in the GPU, does this change the way the object is referenced, or does it do a copy inside the GPU?</p>

username: tom
cooked: <p>No, all I’m doing is <a href="http://lernapparat.de/epidemiology-sir/" rel="nofollow noopener">layman epidemiology</a> this week. But so what happens if you cut the model from this and compare the inputs?<br>
Is the result random or is it somehow connected to the image?<br>
The one time I did look at tensors already on the GPU was when I worked on DLPack-based interoperability of CuPy and PyTorch a long time ago. That seemed to work well, so one could look at what DLPack does.</p>
<p>Best regards</p>
<p>Thomas</p>