Torch graph merging with cuda graph does not work

M_T1: <p>I am trying to merge a large cuda graph with an inference (and eventually) a training cuda graph.</p>
<p>To do so I am using a local version of libtorch that is slightly modified from v2.0.1.</p>
<p>I delete the following:</p>
<pre><code class="lang-auto">  // check if debug path is set
  if (!_cuda_graphs_debug) {
    // Now that we've instantiated graph_ into graph_exec_,
    // we don't need graph_ anymore.
    AT_CUDA_CHECK(cudaGraphDestroy(graph_));
    has_graph_ = false;
  } else {
    TORCH_WARN("DEBUG: TORCH_CUDAGRAPHS_DEBUG_PATH detected. graph_ will not be freed until debug_dump is called.");
  }
</code></pre>
<p>in aten/src/Aten/cuda/CUDAGraph.cpp<br>
and make the following public in CUDAGraph.h</p>
<pre><code class="lang-auto">  cudaGraph_t graph_ = NULL;
  cudaGraphExec_t graph_exec_ = NULL;
</code></pre>
<p>To test the graph merge and execution outside of the traditional structure I have a relatively short script.</p>
<pre><code class="lang-auto">#include &lt;ATen/cuda/CUDAGraph.h&gt;
#include &lt;c10/cuda/CUDAStream.h&gt;
#include &lt;torch/torch.h&gt;

#include &lt;iostream&gt;

#include "helper_cuda.h"

void printTensorSize(torch::Tensor&amp; tensor) {
    std::cout &lt;&lt; "Size: [";
    for (size_t i = 0; i &lt; tensor.sizes().size(); ++i) {
        std::cout &lt;&lt; tensor.sizes()[i];
        if (i &lt; tensor.sizes().size() - 1) {
            std::cout &lt;&lt; ", ";
        }
    }
    std::cout &lt;&lt; "]" &lt;&lt; std::endl;
}

void printTensor(torch::Tensor&amp; tensor) {
    if (tensor.dim() != 2) {
        std::cout &lt;&lt; "Error: Tensor is not 2-dimensional." &lt;&lt; std::endl;
        return;
    }

    for (int64_t i = 0; i &lt; tensor.size(0); ++i) {
        for (int64_t j = 0; j &lt; tensor.size(1); ++j) {
            std::cout &lt;&lt; std::setw(10) &lt;&lt; std::setprecision(4)
                      &lt;&lt; tensor[i][j].item&lt;float&gt;() &lt;&lt; " ";
        }
        std::cout &lt;&lt; std::endl;
    }
    std::cout &lt;&lt; "Address of the data: " &lt;&lt; tensor.data_ptr() &lt;&lt; std::endl;
}

struct Net : torch::nn::Module {
    torch::nn::Linear linear1, linear2, linear3;
    torch::Tensor preallocated_output_tensor;
    Net(int64_t input, int64_t hidden1, int64_t hidden2, int64_t output, int num_av, float* output_arr, torch::TensorOptions&amp; options)
        : linear1(
              register_module("linear1", torch::nn::Linear(input, hidden1))),
          linear2(
              register_module("linear2", torch::nn::Linear(hidden1, hidden2))),
          linear3(
              register_module("linear3", torch::nn::Linear(hidden2, output))) {
                preallocated_output_tensor = torch::from_blob(output_arr, {num_av, output}, options);
              }

    // TODO: make in place version
    torch::Tensor forward(torch::Tensor x) {
        x = linear1-&gt;forward(x);
        torch::relu_(x);

        x = linear2-&gt;forward(x);
        torch::relu_(x);

        x = linear3-&gt;forward(x);

        auto batch_size = x.size(0);
        x = torch::arange(0, 4, torch::dtype(torch::kFloat32)).repeat({batch_size, 1});
        preallocated_output_tensor = x;
        return x;
    }
};

__global__ void printOutput(int num_avs,float4* output){
    const int tid = threadIdx.x + blockIdx.x * (blockDim.x);
    if(tid == 0){
        printf("cudaptr: 0x%p\n", output);
    }
    if(tid &lt; num_avs){
        printf("tid: %d, Agent Output: %f %f %f %f\n ", tid, output[tid].x, output[tid].y, output[tid].z, output[tid].w);
    }
}

__global__ void generateData(int num_avs, int set,float4* input){
    const int tid = threadIdx.x + blockIdx.x * (blockDim.x);
    if(tid &lt; num_avs){
        input[tid].x = set;
        input[tid].y = set;
        input[tid].z = set;
        input[tid].w = set;
    }
}

int main() {
    torch::Device device(torch::kCUDA);
    int num_av = 10;
    int input_size = 40; // must be divisible by 4
    int output_size = 4; // must be divisible by 4
    float* input_arr, *output_arr;

    // allocate input and output arrays for underlying data in Tensors
    cudaError_t cudaStatus = cudaMallocManaged(&amp;input_arr, input_size*num_av*sizeof(float));
    cudaMemset(input_arr, 0, input_size*num_av*sizeof(float));
    cudaStatus = cudaMallocManaged(&amp;output_arr, output_size*num_av*sizeof(float));
    cudaMemset(output_arr, 0, output_size*num_av*sizeof(float));

    // allocate input and output tensors based on constant address internal arrays
    auto options = torch::TensorOptions().dtype(torch::kFloat32).device(device);
    torch::Tensor input_tensor = torch::from_blob(input_arr, {num_av, input_size}, options);
    torch::Tensor output_tensor = torch::from_blob(output_arr, {num_av, output_size}, options);

    // create network
    Net model(input_size, 120, 20, output_size, num_av, output_arr, options);
    model.to(device);

    // warm start
    torch::Tensor _;
    for (int i = 0; i &lt; 6; i++) {
		_ = model.forward(input_tensor);
        printTensor(output_tensor);
	}

    // capture forward
    at::cuda::CUDAStream torchStream = at::cuda::getStreamFromPool(true);
    at::cuda::setCurrentCUDAStream(torchStream);
    at::cuda::CUDAGraph forward_graph;
	forward_graph.capture_begin();
    _ = model.forward(input_tensor);
    forward_graph.capture_end();

    void* kernelArgs2[2];
	void* kernelArgs3[3];
    cudaGraph_t graph;
    cudaGraphCreate(&amp;graph, 0);
    cudaGraphNode_t model_forward_node, set_input_node, print_output_node;
    cudaKernelNodeParams kernelNodeParams;
    int set_num = 1;

	kernelNodeParams.func = (void*) generateData;
	kernelNodeParams.gridDim = dim3(num_av, 1, 1);
	kernelNodeParams.blockDim = dim3(1, 1, 1);
	kernelNodeParams.sharedMemBytes = 0;
    kernelArgs3[0] = (void*)&amp;num_av;
	kernelArgs3[1] = (void*)&amp;set_num;
	kernelArgs3[2] = (void*)&amp;input_arr;
	kernelNodeParams.kernelParams = kernelArgs3;
	kernelNodeParams.extra = NULL;
	cudaGraphAddKernelNode(&amp;set_input_node, graph,nullptr,0, &amp;kernelNodeParams);

    checkCudaErrors(cudaGraphAddChildGraphNode(&amp;model_forward_node, graph, &amp;set_input_node, 1, forward_graph.graph_));

	kernelNodeParams.func = (void*) printOutput;
	kernelNodeParams.gridDim = dim3(num_av, 1, 1);
	kernelNodeParams.blockDim = dim3(1, 1, 1);
	kernelNodeParams.sharedMemBytes = 0;
    kernelArgs2[0] = (void*)&amp;num_av;
	kernelArgs2[1] = (void*)&amp;output_arr;
	kernelNodeParams.kernelParams = kernelArgs2;
	kernelNodeParams.extra = NULL;
	cudaGraphAddKernelNode(&amp;print_output_node, graph,&amp;model_forward_node,1, &amp;kernelNodeParams);

    // Launch the graph
    cudaGraphExec_t graphExec;
    cudaGraphInstantiate(&amp;graphExec, graph, NULL, NULL, 0);
    cudaGraphLaunch(graphExec, 0);
    cudaDeviceSynchronize();
    printTensor(output_tensor);

    // Launch the graph a second time
    cudaGraphLaunch(graphExec, 0);
    cudaDeviceSynchronize();
    printTensor(output_tensor);

    // Cleanup
    cudaGraphExecDestroy(graphExec);
    cudaGraphDestroy(graph);
    cudaFree(input_arr);
    cudaFree(output_arr);

    return 0;
}
</code></pre>
<p>I set a preallocated tensor to try and make sure we have a constant address for the rest of the cuda graph and the underlying data in output_arr. However, the output seems to always be zero or some garbage data.</p>
<p><strong>How would I successfully merge cuda graphs?</strong><br>
<strong>Is there a better way to do this without source changes?</strong><br>
<strong>How may I better help the community address this? (More Info, PR, etc)</strong></p>
<p>For more context, the graph recording seems to work, if I don’t merge graphs.</p>
<p>This Mnist example works for me (with the torch source changes) . (More involved)</p>
<pre><code class="lang-auto">#include &lt;ATen/cuda/CUDAGraph.h&gt;
#include &lt;c10/cuda/CUDAStream.h&gt;
#include &lt;torch/torch.h&gt;

#include "helper_cuda.h"

/**
 * Simple example showing how to capture MLP in a cuda graph,
 * running it through training and evaluation on MNIST data
 */

struct Net : torch::nn::Module {
    torch::nn::Linear linear1, linear2, linear3;

    Net(int64_t input, int64_t hidden1, int64_t hidden2, int64_t output)
        : linear1(register_module("linear1", torch::nn::Linear(input, hidden1))),
          linear2(register_module("linear2", torch::nn::Linear(hidden1, hidden2))),
          linear3(register_module("linear3", torch::nn::Linear(hidden2, output))) {}

    torch::Tensor forward(torch::Tensor x) {
        x = torch::relu(linear1-&gt;forward(x));
        x = torch::relu(linear2-&gt;forward(x));
        return linear3-&gt;forward(x);
    }
};

int main() {
    // ============================ constants ============================ //
    int64_t kBatchSize = 32;
    int64_t kNumberOfEpochs = 10;
    const double learning_rate = 0.001;

    const int input_size = 28 * 28;
    const int hidden1_size = 50;
    const int hidden2_size = 50;
    const int output_size = 10;
    // ========================== end constants ========================== //

    // instantiate network and move to GPU
    torch::Device device(torch::kCUDA);
    Net net(input_size, hidden1_size, hidden2_size, output_size);
    net.to(device);

    // loss function and optimizer
    torch::nn::CrossEntropyLoss loss_fn;
    torch::optim::SGD optimizer(net.parameters(), learning_rate);

    at::cuda::CUDAStream torchStream = at::cuda::getStreamFromPool(true);
    at::cuda::setCurrentCUDAStream(torchStream);
    torchStream.synchronize();

    // =========== DO NOT REMOVE: Necessary to warm start torch! =========== //
    c10::optional&lt;bool&gt; yes = true;
    c10::TensorOptions type = torch::TensorOptions().device(torch::kCUDA).dtype(torch::kInt64);
    c10::TensorOptions option = torch::TensorOptions().device(torch::kCUDA);
    
    // Input and output must exist outside of the scope of capturing and running
    // the graph a side stream must be created to capture cudaGraph
    torch::Tensor warmup = at::randn({kBatchSize, input_size});

    torch::Tensor input_shared = torch::empty_like(warmup, option);

    torch::Tensor target_shared = torch::ones({kBatchSize}, type);

    torch::Tensor output_shared = torch::empty({warmup.size(0), 10}, option);  // Assuming you have 10 output classes

    torch::Tensor output_before = torch::empty({warmup.size(0), 10}, option);

	torch::Tensor loss = torch::empty_like(warmup, option);

    for (int i = 0; i &lt; 3; i++) {
        optimizer.zero_grad(true);
        torch::Tensor warmup_output = net.forward(input_shared);

        torch::Tensor warmup_loss = loss_fn(warmup_output, target_shared);
        warmup_loss.backward();
        optimizer.step();
    }

    torchStream.synchronize();
    // ============================ end warmup ============================ //

    // ======================= capture libtorch graph ======================= //
    at::cuda::CUDAGraph graph;
    optimizer.zero_grad(true);

    graph.capture_begin();

    output_shared = net.forward(input_shared);
    loss = loss_fn(output_shared, target_shared);
    loss.backward();
    optimizer.step();

    graph.capture_end();
    // ============================= end capture ============================= //

    // Load mnist datasets
    auto train_dataset = torch::data::datasets::MNIST(
            "../data", 
            torch::data::datasets::MNIST::Mode::kTrain
        )
        .map(torch::data::transforms::Normalize&lt;&gt;(0.5, 0.5))
        .map(torch::data::transforms::Stack&lt;&gt;());

    auto test_dataset = torch::data::datasets::MNIST(
            "../data", 
            torch::data::datasets::MNIST::Mode::kTest
        )
        .map(torch::data::transforms::Normalize&lt;&gt;(0.5, 0.5))
        .map(torch::data::transforms::Stack&lt;&gt;());
    
    // instantiate mnist data loaders
    auto train_loader = torch::data::make_data_loader(
        std::move(train_dataset),
        torch::data::DataLoaderOptions()
            .batch_size(kBatchSize)
            .drop_last(true) // skip the last partial batch and prevent size mismatch
            .workers(1)
        );

    auto test_loader = torch::data::make_data_loader(
        std::move(test_dataset),
        torch::data::DataLoaderOptions()
            .batch_size(kBatchSize)
            .drop_last(true) // skip the last partial batch and prevent size mismatch
            .workers(1)
        );

    // ============================= mnist training ============================= //
    for (int64_t epoch = 1; epoch &lt;= kNumberOfEpochs; ++epoch) {
        int64_t batch_index = 0;

        for (torch::data::Example&lt;&gt;&amp; batch : *train_loader) {
            output_before = output_shared.clone();
        
            input_shared.copy_(batch.data.view({-1, input_size}));
            target_shared.copy_(batch.target);

            graph.replay();

            printf("loss: %.4f\n", loss.item&lt;float&gt;());
            // std::cout &lt;&lt; "Output after: \n" &lt;&lt; output_shared.slice(0,0,5) &lt;&lt; std::endl;
            if (torch::equal(output_before, output_shared)) {
                std::cout &lt;&lt; "Warning: output_shared is not updated!" &lt;&lt; std::endl;
            } else {
                std::cout &lt;&lt; "output_shared is updated." &lt;&lt; std::endl;
            }
        }
    }
    // ============================= end training ============================= //

    net.eval();

    // ============================= mnist test ============================= //
    for (int64_t epoch = 1; epoch &lt;= kNumberOfEpochs; ++epoch) {
        int64_t batch_index = 0;
        
        for (torch::data::Example&lt;&gt;&amp; batch : *test_loader) {
            torch::Tensor output = net.forward(batch.data.view({-1, input_size}).to(device));
            auto pred = output.argmax(1);
            
            int64_t total = batch.data.size(0);
            int64_t correct = pred.eq(batch.target.to(device)).sum().item&lt;int64_t&gt;();
            std::cout &lt;&lt; "Total: " &lt;&lt; total &lt;&lt; ", Correct: " &lt;&lt; correct &lt;&lt; std::endl;
        }
    }
    // ============================= end test ============================= //

    return 0;
}

</code></pre>

eqy: <p>I haven’t looked into the node manipulation part of the CUDA Graphs API, so I’m not sure if there are any additional requirements there—were you able to get a single node example (without merging) working either with PyTorch or with a standalone CUDA kernel?</p>

M_T1: <p>I don’t understand what you mean by node manipulation. Do you mean the graph api instead of stream capture?<br>
With the graph api (and I believe stream capture as well) the pointers have to be known at graph creation(/capture) time. So when torch returns an output tensor with a different internal address for the Tensor::data_ptr(), I seem to not be able to work with it, as I believe the cuda graph is just looking at the address that I give it in the graph (which will change in the next forward). Is there a way to do all inplace operations? Or use a preallocated tensor properly? I have tried many iterations of the code.</p>
<p>My updated code is as follows (for context). I am currently trying to copy from the inconsistent address to a consistent address within the stream capture to try and get it to be compatible with the printOutput function’s need for a constant address, however I believe on 1st  graph invocation, the copyOutput fails as it is still trying to copy from the old data_ptr. There are other oddities in that the first copyOutput does not print.</p>
<pre><code class="lang-auto">#include &lt;ATen/cuda/CUDAGraph.h&gt;
#include &lt;c10/cuda/CUDAStream.h&gt;
#include &lt;torch/torch.h&gt;

#include &lt;iostream&gt;

#include "helper_cuda.h"

void printTensorSize(torch::Tensor&amp; tensor) {
    std::cout &lt;&lt; "Size: [";
    for (size_t i = 0; i &lt; tensor.sizes().size(); ++i) {
        std::cout &lt;&lt; tensor.sizes()[i];
        if (i &lt; tensor.sizes().size() - 1) {
            std::cout &lt;&lt; ", ";
        }
    }
    std::cout &lt;&lt; "]" &lt;&lt; std::endl;
}

void printTensor(torch::Tensor&amp; tensor) {
    if (tensor.dim() != 2) {
        std::cout &lt;&lt; "Error: Tensor is not 2-dimensional." &lt;&lt; std::endl;
        return;
    }

    for (int64_t i = 0; i &lt; tensor.size(0); ++i) {
        for (int64_t j = 0; j &lt; tensor.size(1); ++j) {
            std::cout &lt;&lt; std::setw(10) &lt;&lt; std::setprecision(4)
                      &lt;&lt; tensor[i][j].item&lt;float&gt;() &lt;&lt; " ";
        }
        std::cout &lt;&lt; std::endl;
    }
    std::cout &lt;&lt; "Address of the data: " &lt;&lt; tensor.data_ptr() &lt;&lt; std::endl;
}

struct Net : torch::nn::Module {
    torch::nn::Linear linear1, linear2, linear3;
    torch::Tensor preallocated_output_tensor;
    Net(int64_t input, int64_t hidden1, int64_t hidden2, int64_t output, int num_av, float* output_arr, torch::TensorOptions&amp; options)
        : linear1(
              register_module("linear1", torch::nn::Linear(input, hidden1))),
          linear2(
              register_module("linear2", torch::nn::Linear(hidden1, hidden2))),
          linear3(
              register_module("linear3", torch::nn::Linear(hidden2, output))) {
                preallocated_output_tensor = torch::from_blob(output_arr, {num_av, output}, options);
              }

    // TODO: make in place version
    torch::Tensor forward(torch::Tensor x) {
        x = linear1-&gt;forward(x);
        torch::relu_(x);

        x = linear2-&gt;forward(x);
        torch::relu_(x);

        x = linear3-&gt;forward(x);

        auto batch_size = x.size(0);
        x = torch::arange(0, 4, torch::dtype(torch::kFloat32)).repeat({batch_size, 1});
        preallocated_output_tensor = x;
        return x;
    }
};

__global__ void copyOutput(int num_avs,float4* input, float4* output){
    const int tid = threadIdx.x + blockIdx.x * (blockDim.x);
    // auto f4_input = (float4*) input;
    printf("copying: 0x%p to 0x%p\n", input, output);
    if(tid &lt; num_avs){
        output[tid].x=input[tid].x;
        output[tid].y=input[tid].y;
        output[tid].z=input[tid].z;
        output[tid].w=input[tid].w;
    }
}

__global__ void printOutput(int num_avs,float4 * output){
    const int tid = threadIdx.x + blockIdx.x * (blockDim.x);
    if(tid == 0){
        printf("cudaptr: 0x%p\n", output);
    }
    if(tid &lt; num_avs){
        printf("tid: %d, Agent Output: %f %f %f %f\n ", tid, 
            output[tid].x,
            output[tid].y,
            output[tid].z,
            output[tid].w);
    }
}

__global__ void generateData(int num_avs, int set,float4* input){
    const int tid = threadIdx.x + blockIdx.x * (blockDim.x);
    printf("generating: 0x%p\n", input);
    if(tid &lt; num_avs){
        input[tid].x = set;
        input[tid].y = set;
        input[tid].z = set;
        input[tid].w = set;
    }
}

int main() {
    torch::Device device(torch::kCUDA);
    int num_av = 10;
    int input_size = 40; // must be divisible by 4
    int output_size = 4; // must be divisible by 4
    float* input_arr, *output_arr;

    // allocate input and output arrays for underlying data in Tensors
    cudaError_t cudaStatus = cudaMallocManaged(&amp;input_arr, input_size*num_av*sizeof(float));
    cudaMemset(input_arr, 0, input_size*num_av*sizeof(float));
    cudaStatus = cudaMallocManaged(&amp;output_arr, output_size*num_av*sizeof(float));
    cudaMemset(output_arr, 0, output_size*num_av*sizeof(float));

    // allocate input and output tensors based on constant address internal arrays
    auto options = torch::TensorOptions().dtype(torch::kFloat32).device(device);
    torch::Tensor input_tensor = torch::from_blob(input_arr, {num_av, input_size}, options);
    torch::Tensor output_tensor = torch::from_blob(output_arr, {num_av, output_size}, options);
    printTensor(output_tensor);

    // create network
    Net model(input_size, 120, 20, output_size, num_av, output_arr, options);
    model.to(device);

    // warm start
    for (int i = 0; i &lt; 1; i++) {
		output_tensor = model.forward(input_tensor);
	}

    // capture forward
    at::cuda::CUDAStream torchStream = at::cuda::getStreamFromPool(true);
    at::cuda::setCurrentCUDAStream(torchStream);
    at::cuda::CUDAGraph forward_graph;
	forward_graph.capture_begin();
    output_tensor = model.forward(input_tensor);
    copyOutput&lt;&lt;&lt;dim3(1,1,1),dim3(num_av,1,1), 0, torchStream&gt;&gt;&gt;(num_av, (float4*)output_tensor.data_ptr(), (float4*)output_arr);
    forward_graph.capture_end();
    cudaDeviceSynchronize();

    void* kernelArgs2[2];
	void* kernelArgs3[3];
    cudaGraph_t graph;
    cudaGraphCreate(&amp;graph, 0);
    cudaGraphNode_t model_forward_node, set_input_node, print_output_node;
    cudaKernelNodeParams kernelNodeParams;
    int set_num = 1;

	kernelNodeParams.func = (void*) generateData;
	kernelNodeParams.gridDim = dim3(1, 1, 1);
	kernelNodeParams.blockDim = dim3(num_av, 1, 1);
	kernelNodeParams.sharedMemBytes = 0;
    kernelArgs3[0] = (void*)&amp;num_av;
	kernelArgs3[1] = (void*)&amp;set_num;
	kernelArgs3[2] = (void*)&amp;input_arr;
	kernelNodeParams.kernelParams = kernelArgs3;
	kernelNodeParams.extra = NULL;
	cudaGraphAddKernelNode(&amp;set_input_node, graph,nullptr,0, &amp;kernelNodeParams);

    checkCudaErrors(cudaGraphAddChildGraphNode(&amp;model_forward_node, graph, &amp;set_input_node, 1, forward_graph.graph_));

	kernelNodeParams.func = (void*) printOutput;
	kernelNodeParams.gridDim = dim3(1, 1, 1);
	kernelNodeParams.blockDim = dim3(num_av, 1, 1);
	kernelNodeParams.sharedMemBytes = 0;
    kernelArgs2[0] = (void*)&amp;num_av;
	kernelArgs2[1] = (void*)&amp;output_arr;
	kernelNodeParams.kernelParams = kernelArgs2;
	kernelNodeParams.extra = NULL;
	cudaGraphAddKernelNode(&amp;print_output_node, graph,&amp;model_forward_node,1, &amp;kernelNodeParams);

    // Launch the graph
    cudaGraphExec_t graphExec;
    cudaGraphInstantiate(&amp;graphExec, graph, NULL, NULL, 0);
    cudaGraphLaunch(graphExec, 0);
    cudaDeviceSynchronize();
    // printTensor(output_tensor);

    // Launch the graph a second time
    cudaGraphLaunch(graphExec, 0);
    cudaDeviceSynchronize();
    // printTensor(output_tensor);

    // Cleanup
    cudaGraphExecDestroy(graphExec);
    cudaGraphDestroy(graph);
    cudaFree(input_arr);
    cudaFree(output_arr);

    return 0;
}
</code></pre>

eqy: <p>Yes, I mean explicit adding of nodes vs. graph capture. In the graph capture scenario, allocations done by PyTorch happen on a private memory pool to ensure that they are not recycled by the caching allocator after the graph capture. Without the private memory pool if you had any new allocations (e.g., for new inputs) the memory addresses could go stale. You might get lucky with more warmup iterations? A litmus test for this could be to see if any of your visible tensors have changing <code>data_ptr()</code>s, if they are changing, it could mean that the addresses would be going stale without a private memory pool.</p>
<p>Maybe this defeats the purpose of what you are trying to achieve, but I wonder if your approach could work with nodes that were produced by separate graph captures.</p>

M_T1: <p>I have changed the code to warm start more and use graph capture and the torch api in a more traditional manner. However the printOutput is still not working. I believe that Tensor::data_ptr() might be a cpu address space pointer. Is it possible to get the GPU address space pointer and check if it is consistent?</p>
<p>Currently printOutput is still all zero. This might be because I am printing the underlying first allocation for the ::from_blob. If I try to print from .data_ptr() the graph replay fails with an Illegal Address. Which makes me think it is one of two potential problems.</p>
<ol>
<li>The allocator is giving me different data pointers.</li>
<li>The ::data_ptr function is not the address I am looking for.</li>
</ol>
<p>Note: when I print ::data_ptr during warmstart. That address still changes every iteration. Would I have to change the internal allocator? How else would I integrate torch inference into a cuda application?</p>
<p>Updated Code:</p>
<pre><code class="lang-auto">#include &lt;ATen/cuda/CUDAGraph.h&gt;
#include &lt;c10/cuda/CUDAStream.h&gt;
#include &lt;torch/torch.h&gt;

#include &lt;iostream&gt;

#include "helper_cuda.h"

void printTensorSize(torch::Tensor&amp; tensor) {
    std::cout &lt;&lt; "Size: [";
    for (size_t i = 0; i &lt; tensor.sizes().size(); ++i) {
        std::cout &lt;&lt; tensor.sizes()[i];
        if (i &lt; tensor.sizes().size() - 1) {
            std::cout &lt;&lt; ", ";
        }
    }
    std::cout &lt;&lt; "]" &lt;&lt; std::endl;
}

void printTensor(torch::Tensor&amp; tensor) {
    if (tensor.dim() != 2) {
        std::cout &lt;&lt; "Error: Tensor is not 2-dimensional." &lt;&lt; std::endl;
        return;
    }

    for (int64_t i = 0; i &lt; tensor.size(0); ++i) {
        for (int64_t j = 0; j &lt; tensor.size(1); ++j) {
            std::cout &lt;&lt; std::setw(10) &lt;&lt; std::setprecision(4)
                      &lt;&lt; tensor[i][j].item&lt;float&gt;() &lt;&lt; " ";
        }
        std::cout &lt;&lt; std::endl;
    }
    std::cout &lt;&lt; "Address of the data: " &lt;&lt; tensor.data_ptr() &lt;&lt; std::endl;
}

struct Net : torch::nn::Module {
    torch::nn::Linear linear1, linear2, linear3;
    Net(int64_t input, int64_t hidden1, int64_t hidden2, int64_t output, int num_av, float* output_arr, torch::TensorOptions&amp; options)
        : linear1(
              register_module("linear1", torch::nn::Linear(input, hidden1))),
          linear2(
              register_module("linear2", torch::nn::Linear(hidden1, hidden2))),
          linear3(
              register_module("linear3", torch::nn::Linear(hidden2, output))) {}

    // TODO: make in place version
    torch::Tensor forward(torch::Tensor x) {
        x = linear1-&gt;forward(x);
        torch::relu_(x);

        x = linear2-&gt;forward(x);
        torch::relu_(x);

        x = linear3-&gt;forward(x);

        auto batch_size = x.size(0);
        x = torch::arange(0, 4, torch::dtype(torch::kFloat32)).repeat({batch_size, 1});
        return x;
    }
};

__global__ void copyOutput(int num_avs,float4* input, float4* output){
    const int tid = threadIdx.x + blockIdx.x * (blockDim.x);
    // auto f4_input = (float4*) input;
    printf("copying: %p to 0x%p\n", input, output);
    if(tid &lt; num_avs){
        output[tid].x=input[tid].x;
        output[tid].y=input[tid].y;
        output[tid].z=input[tid].z;
        output[tid].w=input[tid].w;
    }
}

__global__ void printOutput(int num_avs,float4 * output){
    const int tid = threadIdx.x + blockIdx.x * (blockDim.x);
    if(tid == 0){
        printf("cudaptr: %p\n", output);
    }
    if(tid &lt; num_avs){
        printf("tid: %d, Agent Output: %f %f %f %f\n ", tid,
            output[tid].x,
            output[tid].y,
            output[tid].z,
            output[tid].w);
    }
}

__global__ void generateData(int limit, int set,float* input){
    const int tid = threadIdx.x + blockIdx.x * (blockDim.x);
    if(tid == 0){
        printf("generating: %p\n", input);
    }
    if(tid &lt; limit){
        input[tid] = set;
    }
}

int main() {
    torch::Device device(torch::kCUDA);
    int num_av = 10;
    int input_size = 40; // must be divisible by 4
    int output_size = 4; // must be divisible by 4
    float* input_arr, *output_arr;

    // allocate input and output arrays for underlying data in Tensors
    cudaError_t cudaStatus = cudaMallocManaged(&amp;input_arr, input_size*num_av*sizeof(float));
    cudaMemset(input_arr, 0, input_size*num_av*sizeof(float));
    cudaStatus = cudaMallocManaged(&amp;output_arr, output_size*num_av*sizeof(float));
    cudaMemset(output_arr, 0, output_size*num_av*sizeof(float));

    // allocate input and output tensors based on constant address internal arrays
    auto options = torch::TensorOptions().dtype(torch::kFloat32).device(device);
    torch::Tensor input_tensor = torch::from_blob(input_arr, {num_av, input_size}, options);
    torch::Tensor output_tensor = torch::from_blob(output_arr, {num_av, output_size}, options);

    // create network
    Net model(input_size, 120, 20, output_size, num_av, output_arr, options);
    model.to(device);

    // warm start
    at::cuda::CUDAStream torchStream = at::cuda::getStreamFromPool(true);
    at::cuda::setCurrentCUDAStream(torchStream);
    // torch::Tensor _;
    for (int i = 0; i &lt; 10; i++) {
        generateData&lt;&lt;&lt;dim3(1,1,1), dim3(input_size,1,1), 0, torchStream&gt;&gt;&gt;(input_size, 1,input_arr);
		output_tensor = model.forward(input_tensor);
        std::cout &lt;&lt;"WARM: " &lt;&lt;  output_tensor.data_ptr() &lt;&lt; std::endl;
        printOutput&lt;&lt;&lt;dim3(1,1,1), dim3(num_av,1,1), 0, torchStream&gt;&gt;&gt;(num_av, (float4*)output_arr);
	}
    std::cout &lt;&lt; "Warm Start Finished" &lt;&lt;std::endl;

    // capture forward
    at::cuda::CUDAGraph forward_graph;
	forward_graph.capture_begin();
        generateData&lt;&lt;&lt;dim3(1,1,1), dim3(input_size,1,1), 0, torchStream&gt;&gt;&gt;(input_size, 1, input_arr);
		output_tensor = model.forward(input_tensor);
        printOutput&lt;&lt;&lt;dim3(1,1,1), dim3(num_av,1,1), 0, torchStream&gt;&gt;&gt;(num_av, (float4*)output_arr);
    forward_graph.capture_end();
    cudaDeviceSynchronize();

    std::cout &lt;&lt; "Graph Capture Finished" &lt;&lt;std::endl;

    forward_graph.replay();
    cudaDeviceSynchronize();
    forward_graph.replay();
    cudaDeviceSynchronize();
    return 0;
}
</code></pre>

M_T1: <p>Update here is a stream capture example that works. I might try to get the graph example working as well. I preallocated and made sure each tensor was on the GPU. I forgot that forward is a host function, and I cannot explicitly copy with GPU pointers, so I had forward invoke a kernel and it seemed to work.</p>
<pre><code class="lang-auto">#include &lt;ATen/cuda/CUDAGraph.h&gt;
#include &lt;c10/cuda/CUDAStream.h&gt;
#include &lt;torch/torch.h&gt;

#include &lt;iostream&gt;

#include "helper_cuda.h"

void printTensorSize(torch::Tensor&amp; tensor) {
    std::cout &lt;&lt; "Size: [";
    for (size_t i = 0; i &lt; tensor.sizes().size(); ++i) {
        std::cout &lt;&lt; tensor.sizes()[i];
        if (i &lt; tensor.sizes().size() - 1) {
            std::cout &lt;&lt; ", ";
        }
    }
    std::cout &lt;&lt; "]" &lt;&lt; std::endl;
}

void printTensor(torch::Tensor&amp; tensor) {
    if (tensor.dim() != 2) {
        std::cout &lt;&lt; "Error: Tensor is not 2-dimensional." &lt;&lt; std::endl;
        return;
    }

    for (int64_t i = 0; i &lt; tensor.size(0); ++i) {
        for (int64_t j = 0; j &lt; tensor.size(1); ++j) {
            std::cout &lt;&lt; std::setw(10) &lt;&lt; std::setprecision(4)
                      &lt;&lt; tensor[i][j].item&lt;float&gt;() &lt;&lt; " ";
        }
        std::cout &lt;&lt; std::endl;
    }
    std::cout &lt;&lt; "Address of the data: " &lt;&lt; tensor.data_ptr() &lt;&lt; std::endl;
}

__global__ void copyOutput(int num_avs,float4* input, float4* output){
    const int tid = threadIdx.x + blockIdx.x * (blockDim.x);
    // auto f4_input = (float4*) input;
    printf("copying: %p to 0x%p\n", input, output);
    if(tid &lt; num_avs){
        output[tid].x=input[tid].x;
        output[tid].y=input[tid].y;
        output[tid].z=input[tid].z;
        output[tid].w=input[tid].w;
    }
}

struct Net : torch::nn::Module {
    torch::nn::Linear linear1, linear2, linear3;
    torch::Tensor preallocated_output, preallocated_1, preallocated_2, preallocated_3, range;
    Net(int64_t input, int64_t hidden1, int64_t hidden2, int64_t output, int num_av, float* output_arr, torch::TensorOptions&amp; options)
        : linear1(
              register_module("linear1", torch::nn::Linear(input, hidden1))),
          linear2(
              register_module("linear2", torch::nn::Linear(hidden1, hidden2))),
          linear3(
              register_module("linear3", torch::nn::Linear(hidden2, output))) {
                preallocated_output = torch::from_blob(output_arr, {num_av, output}, options);
                preallocated_1 = torch::zeros({num_av, hidden1}, options); 
                preallocated_2 = torch::zeros({num_av, hidden2}, options); 
                preallocated_3 = torch::zeros({num_av, output}, options); 
                range = torch::arange(0,output, options).repeat({10,1});
              }

    // TODO: make in place version
    torch::Tensor forward(torch::Tensor x) {
        preallocated_1 = linear1-&gt;forward(x);
        torch::relu_(preallocated_1);

        preallocated_2 = linear2-&gt;forward(preallocated_1);
        torch::relu_(preallocated_2);

        preallocated_3 = linear3-&gt;forward(preallocated_2);

        auto batch_size = preallocated_3.size(0);
        auto options = torch::TensorOptions().dtype(torch::kFloat32);
        copyOutput&lt;&lt;&lt;dim3(1,1,1),dim3(10,1,1)&gt;&gt;&gt;(10, (float4*)(range.data_ptr()), (float4*)(preallocated_output.data_ptr())); 
        return preallocated_3;
    }
};



__global__ void printOutput(int num_avs,float4 * output){
    const int tid = threadIdx.x + blockIdx.x * (blockDim.x);
    if(tid == 0){
        printf("cudaptr: %p\n", output);
    }
    if(tid &lt; num_avs){
        printf("tid: %d, Agent Output: %f %f %f %f\n ", tid,
            output[tid].x,
            output[tid].y,
            output[tid].z,
            output[tid].w);
    }
}

__global__ void generateData(int limit, int set,float* input){
    const int tid = threadIdx.x + blockIdx.x * (blockDim.x);
    if(tid == 0){
        printf("generating: %p\n", input);
    }
    if(tid &lt; limit){
        input[tid] = set;
    }
}

int main() {
    torch::Device device(torch::kCUDA);
    int num_av = 10;
    int input_size = 40; // must be divisible by 4
    int output_size = 4; // must be divisible by 4
    float* input_arr, *output_arr;

    // allocate input and output arrays for underlying data in Tensors
    cudaError_t cudaStatus = cudaMallocManaged(&amp;input_arr, input_size*num_av*sizeof(float));
    cudaMemset(input_arr, 0, input_size*num_av*sizeof(float));
    cudaStatus = cudaMallocManaged(&amp;output_arr, output_size*num_av*sizeof(float));
    cudaMemset(output_arr, 0, output_size*num_av*sizeof(float));

    // allocate input and output tensors based on constant address internal arrays
    auto options = torch::TensorOptions().dtype(torch::kFloat32).device(device);
    torch::Tensor input_tensor = torch::from_blob(input_arr, {num_av, input_size}, options);

    // create network
    Net model(input_size, 120, 20, output_size, num_av, output_arr, options);
    model.to(device);

    // warm start
    at::cuda::CUDAStream torchStream = at::cuda::getStreamFromPool(true);
    at::cuda::setCurrentCUDAStream(torchStream);
    torch::Tensor _;
    for (int i = 0; i &lt; 10; i++) {
        generateData&lt;&lt;&lt;dim3(1,1,1), dim3(input_size,1,1), 0, torchStream&gt;&gt;&gt;(input_size, 2,input_arr);
        cudaDeviceSynchronize();
		_ = model.forward(input_tensor);
        cudaDeviceSynchronize();
        // std::cout &lt;&lt;"WARM: " &lt;&lt;  model.preallocated_output.data_ptr() &lt;&lt; std::endl;
        printTensor(model.preallocated_3);
        printTensor(model.preallocated_output);
        printOutput&lt;&lt;&lt;dim3(1,1,1), dim3(num_av,1,1), 0, torchStream&gt;&gt;&gt;(num_av, (float4*)output_arr);
        cudaDeviceSynchronize();
	}
    std::cout &lt;&lt; "Warm Start Finished" &lt;&lt;std::endl;

    // capture forward
    at::cuda::CUDAGraph forward_graph;
	forward_graph.capture_begin();
        generateData&lt;&lt;&lt;dim3(1,1,1), dim3(input_size,1,1), 0, torchStream&gt;&gt;&gt;(input_size, 3, input_arr);
		_ = model.forward(input_tensor);
        printOutput&lt;&lt;&lt;dim3(1,1,1), dim3(num_av,1,1), 0, torchStream&gt;&gt;&gt;(num_av, (float4*)output_arr);
    forward_graph.capture_end();
    cudaDeviceSynchronize();

    std::cout &lt;&lt; "Graph Capture Finished" &lt;&lt;std::endl;

    forward_graph.replay();
    cudaDeviceSynchronize();
    forward_graph.replay();
    cudaDeviceSynchronize();
    return 0;
}
</code></pre>