{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# For tips on running notebooks in Google Colab, see\n",
    "# https://docs.pytorch.org/tutorials/beginner/colab\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# A guide on good usage of `non_blocking` and `pin_memory()` in PyTorch\n",
    "\n",
    "**Author**: [Vincent Moens](https://github.com/vmoens)\n",
    "\n",
    "## Introduction\n",
    "\n",
    "Transferring data from the CPU to the GPU is fundamental in many PyTorch\n",
    "applications. It\\'s crucial for users to understand the most effective\n",
    "tools and options available for moving data between devices. This\n",
    "tutorial examines two key methods for device-to-device data transfer in\n",
    "PyTorch: `~torch.Tensor.pin_memory`{.interpreted-text role=\"meth\"} and\n",
    "`~torch.Tensor.to`{.interpreted-text role=\"meth\"} with the\n",
    "`non_blocking=True` option.\n",
    "\n",
    "### What you will learn\n",
    "\n",
    "Optimizing the transfer of tensors from the CPU to the GPU can be\n",
    "achieved through asynchronous transfers and memory pinning. However,\n",
    "there are important considerations:\n",
    "\n",
    "-   Using `tensor.pin_memory().to(device, non_blocking=True)` can be up\n",
    "    to twice as slow as a straightforward `tensor.to(device)`.\n",
    "-   Generally, `tensor.to(device, non_blocking=True)` is an effective\n",
    "    choice for enhancing transfer speed.\n",
    "-   While `cpu_tensor.to(\"cuda\", non_blocking=True).mean()` executes\n",
    "    correctly, attempting\n",
    "    `cuda_tensor.to(\"cpu\", non_blocking=True).mean()` will result in\n",
    "    erroneous outputs.\n",
    "\n",
    "### Preamble\n",
    "\n",
    "The performance reported in this tutorial are conditioned on the system\n",
    "used to build the tutorial. Although the conclusions are applicable\n",
    "across different systems, the specific observations may vary slightly\n",
    "depending on the hardware available, especially on older hardware. The\n",
    "primary objective of this tutorial is to offer a theoretical framework\n",
    "for understanding CPU to GPU data transfers. However, any design\n",
    "decisions should be tailored to individual cases and guided by\n",
    "benchmarked throughput measurements, as well as the specific\n",
    "requirements of the task at hand.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "\n",
    "assert torch.cuda.is_available(), \"A cuda device is required to run this tutorial\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This tutorial requires tensordict to be installed. If you don\\'t have\n",
    "tensordict in your environment yet, install it by running the following\n",
    "command in a separate cell:\n",
    "\n",
    "``` bash\n",
    "# Install tensordict with the following command\n",
    "!pip3 install tensordict\n",
    "```\n",
    "\n",
    "We start by outlining the theory surrounding these concepts, and then\n",
    "move to concrete test examples of the features.\n",
    "\n",
    "# Background\n",
    "\n",
    "## Memory management basics\n",
    "\n",
    "When one creates a CPU tensor in PyTorch, the content of this tensor\n",
    "needs to be placed in memory. The memory we talk about here is a rather\n",
    "complex concept worth looking at carefully. We distinguish two types of\n",
    "memory that are handled by the Memory Management Unit: the RAM (for\n",
    "simplicity) and the swap space on disk (which may or may not be the hard\n",
    "drive). Together, the available space in disk and RAM (physical memory)\n",
    "make up the virtual memory, which is an abstraction of the total\n",
    "resources available. In short, the virtual memory makes it so that the\n",
    "available space is larger than what can be found on RAM in isolation and\n",
    "creates the illusion that the main memory is larger than it actually is.\n",
    "\n",
    "In normal circumstances, a regular CPU tensor is pageable which means\n",
    "that it is divided in blocks called pages that can live anywhere in the\n",
    "virtual memory (both in RAM or on disk). As mentioned earlier, this has\n",
    "the advantage that the memory seems larger than what the main memory\n",
    "actually is.\n",
    "\n",
    "Typically, when a program accesses a page that is not in RAM, a \\\"page\n",
    "fault\\\" occurs and the operating system (OS) then brings back this page\n",
    "into RAM (\\\"swap in\\\" or \\\"page in\\\"). In turn, the OS may have to swap\n",
    "out (or \\\"page out\\\") another page to make room for the new page.\n",
    "\n",
    "In contrast to pageable memory, a pinned (or page-locked or\n",
    "non-pageable) memory is a type of memory that cannot be swapped out to\n",
    "disk. It allows for faster and more predictable access times, but has\n",
    "the downside that it is more limited than the pageable memory (aka the\n",
    "main memory).\n",
    "\n",
    "![/\\_static/img/pinmem/pinmem.png](https://pytorch.org/tutorials/_static/img/pinmem/pinmem.png)\n",
    "\n",
    "## CUDA and (non-)pageable memory\n",
    "\n",
    "To understand how CUDA copies a tensor from CPU to CUDA, let\\'s consider\n",
    "the two scenarios above:\n",
    "\n",
    "-   If the memory is page-locked, the device can access the memory\n",
    "    directly in the main memory. The memory addresses are well defined\n",
    "    and functions that need to read these data can be significantly\n",
    "    accelerated.\n",
    "-   If the memory is pageable, all the pages will have to be brought to\n",
    "    the main memory before being sent to the GPU. This operation may\n",
    "    take time and is less predictable than when executed on page-locked\n",
    "    tensors.\n",
    "\n",
    "More precisely, when CUDA sends pageable data from CPU to GPU, it must\n",
    "first create a page-locked copy of that data before making the transfer.\n",
    "\n",
    "## Asynchronous vs. Synchronous Operations with `non_blocking=True` (CUDA `cudaMemcpyAsync`)\n",
    "\n",
    "When executing a copy from a host (such as, CPU) to a device (such as,\n",
    "GPU), the CUDA toolkit offers modalities to do these operations\n",
    "synchronously or asynchronously with respect to the host.\n",
    "\n",
    "In practice, when calling `~torch.Tensor.to`{.interpreted-text\n",
    "role=\"meth\"}, PyTorch always makes a call to\n",
    "[cudaMemcpyAsync](https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__MEMORY.html#group__CUDART__MEMORY_1g85073372f776b4c4d5f89f7124b7bf79).\n",
    "If `non_blocking=False` (default), a `cudaStreamSynchronize` will be\n",
    "called after each and every `cudaMemcpyAsync`, making the call to\n",
    "`~torch.Tensor.to`{.interpreted-text role=\"meth\"} blocking in the main\n",
    "thread. If `non_blocking=True`, no synchronization is triggered, and the\n",
    "main thread on the host is not blocked. Therefore, from the host\n",
    "perspective, multiple tensors can be sent to the device simultaneously,\n",
    "as the thread does not need to wait for one transfer to be completed to\n",
    "initiate the other.\n",
    "\n",
    "<div style=\"background-color: #54c7ec; color: #fff; font-weight: 700; padding-left: 10px; padding-top: 5px; padding-bottom: 5px\"><strong>NOTE:</strong></div>\n",
    "\n",
    "<div style=\"background-color: #f3f4f7; padding-left: 10px; padding-top: 10px; padding-bottom: 10px; padding-right: 10px\">\n",
    "\n",
    "<p>In general, the transfer is blocking on the device side (even if it isn't on the host side):the copy on the device cannot occur while another operation is being executed.However, in some advanced scenarios, a copy and a kernel execution can be done simultaneously on the GPU side.As the following example will show, three requirements must be met to enable this:We demonstrate this by running profiles on the following script.</p>\n",
    "\n",
    "</div>\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import contextlib\n",
    "\n",
    "from torch.cuda import Stream\n",
    "\n",
    "\n",
    "s = Stream()\n",
    "\n",
    "torch.manual_seed(42)\n",
    "t1_cpu_pinned = torch.randn(1024**2 * 5, pin_memory=True)\n",
    "t2_cpu_paged = torch.randn(1024**2 * 5, pin_memory=False)\n",
    "t3_cuda = torch.randn(1024**2 * 5, device=\"cuda:0\")\n",
    "\n",
    "assert torch.cuda.is_available()\n",
    "device = torch.device(\"cuda\", torch.cuda.current_device())\n",
    "\n",
    "\n",
    "# The function we want to profile\n",
    "def inner(pinned: bool, streamed: bool):\n",
    "    with torch.cuda.stream(s) if streamed else contextlib.nullcontext():\n",
    "        if pinned:\n",
    "            t1_cuda = t1_cpu_pinned.to(device, non_blocking=True)\n",
    "        else:\n",
    "            t2_cuda = t2_cpu_paged.to(device, non_blocking=True)\n",
    "        t_star_cuda_h2d_event = s.record_event()\n",
    "    # This operation can be executed during the CPU to GPU copy if and only if the tensor is pinned and the copy is\n",
    "    #  done in the other stream\n",
    "    t3_cuda_mul = t3_cuda * t3_cuda * t3_cuda\n",
    "    t3_cuda_h2d_event = torch.cuda.current_stream().record_event()\n",
    "    t_star_cuda_h2d_event.synchronize()\n",
    "    t3_cuda_h2d_event.synchronize()\n",
    "\n",
    "\n",
    "# Our profiler: profiles the `inner` function and stores the results in a .json file\n",
    "def benchmark_with_profiler(\n",
    "    pinned,\n",
    "    streamed,\n",
    ") -> None:\n",
    "    torch._C._profiler._set_cuda_sync_enabled_val(True)\n",
    "    wait, warmup, active = 1, 1, 2\n",
    "    num_steps = wait + warmup + active\n",
    "    rank = 0\n",
    "    with torch.profiler.profile(\n",
    "        activities=[\n",
    "            torch.profiler.ProfilerActivity.CPU,\n",
    "            torch.profiler.ProfilerActivity.CUDA,\n",
    "        ],\n",
    "        schedule=torch.profiler.schedule(\n",
    "            wait=wait, warmup=warmup, active=active, repeat=1, skip_first=1\n",
    "        ),\n",
    "    ) as prof:\n",
    "        for step_idx in range(1, num_steps + 1):\n",
    "            inner(streamed=streamed, pinned=pinned)\n",
    "            if rank is None or rank == 0:\n",
    "                prof.step()\n",
    "    prof.export_chrome_trace(f\"trace_streamed{int(streamed)}_pinned{int(pinned)}.json\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Loading these profile traces in chrome (`chrome://tracing`) shows the\n",
    "following results: first, let\\'s see what happens if both the arithmetic\n",
    "operation on `t3_cuda` is executed after the pageable tensor is sent to\n",
    "GPU in the main stream:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "benchmark_with_profiler(streamed=False, pinned=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![/\\_static/img/pinmem/trace_streamed0_pinned0.png](https://pytorch.org/tutorials/_static/img/pinmem/trace_streamed0_pinned0.png)\n",
    "\n",
    "Using a pinned tensor doesn\\'t change the trace much, both operations\n",
    "are still executed consecutively:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "benchmark_with_profiler(streamed=False, pinned=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![/\\_static/img/pinmem/trace_streamed0_pinned1.png](https://pytorch.org/tutorials/_static/img/pinmem/trace_streamed0_pinned1.png)\n",
    "\n",
    "Sending a pageable tensor to GPU on a separate stream is also a blocking\n",
    "operation:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "benchmark_with_profiler(streamed=True, pinned=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![/\\_static/img/pinmem/trace_streamed1_pinned0.png](https://pytorch.org/tutorials/_static/img/pinmem/trace_streamed1_pinned0.png)\n",
    "\n",
    "Only pinned tensors copies to GPU on a separate stream overlap with\n",
    "another cuda kernel executed on the main stream:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "benchmark_with_profiler(streamed=True, pinned=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![/\\_static/img/pinmem/trace_streamed1_pinned1.png](https://pytorch.org/tutorials/_static/img/pinmem/trace_streamed1_pinned1.png)\n",
    "\n",
    "# A PyTorch perspective\n",
    "\n",
    "## `pin_memory()`\n",
    "\n",
    "PyTorch offers the possibility to create and send tensors to page-locked\n",
    "memory through the `~torch.Tensor.pin_memory`{.interpreted-text\n",
    "role=\"meth\"} method and constructor arguments. CPU tensors on a machine\n",
    "where CUDA is initialized can be cast to pinned memory through the\n",
    "`~torch.Tensor.pin_memory`{.interpreted-text role=\"meth\"} method.\n",
    "Importantly, `pin_memory` is blocking on the main thread of the host: it\n",
    "will wait for the tensor to be copied to page-locked memory before\n",
    "executing the next operation. New tensors can be directly created in\n",
    "pinned memory with functions like `~torch.zeros`{.interpreted-text\n",
    "role=\"func\"}, `~torch.ones`{.interpreted-text role=\"func\"} and other\n",
    "constructors.\n",
    "\n",
    "Let us check the speed of pinning memory and sending tensors to CUDA:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "import gc\n",
    "from torch.utils.benchmark import Timer\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "\n",
    "def timer(cmd):\n",
    "    median = (\n",
    "        Timer(cmd, globals=globals())\n",
    "        .adaptive_autorange(min_run_time=1.0, max_run_time=20.0)\n",
    "        .median\n",
    "        * 1000\n",
    "    )\n",
    "    print(f\"{cmd}: {median: 4.4f} ms\")\n",
    "    return median\n",
    "\n",
    "\n",
    "# A tensor in pageable memory\n",
    "pageable_tensor = torch.randn(1_000_000)\n",
    "\n",
    "# A tensor in page-locked (pinned) memory\n",
    "pinned_tensor = torch.randn(1_000_000, pin_memory=True)\n",
    "\n",
    "# Runtimes:\n",
    "pageable_to_device = timer(\"pageable_tensor.to('cuda:0')\")\n",
    "pinned_to_device = timer(\"pinned_tensor.to('cuda:0')\")\n",
    "pin_mem = timer(\"pageable_tensor.pin_memory()\")\n",
    "pin_mem_to_device = timer(\"pageable_tensor.pin_memory().to('cuda:0')\")\n",
    "\n",
    "# Ratios:\n",
    "r1 = pinned_to_device / pageable_to_device\n",
    "r2 = pin_mem_to_device / pageable_to_device\n",
    "\n",
    "# Create a figure with the results\n",
    "fig, ax = plt.subplots()\n",
    "\n",
    "xlabels = [0, 1, 2]\n",
    "bar_labels = [\n",
    "    \"pageable_tensor.to(device) (1x)\",\n",
    "    f\"pinned_tensor.to(device) ({r1:4.2f}x)\",\n",
    "    f\"pageable_tensor.pin_memory().to(device) ({r2:4.2f}x)\"\n",
    "    f\"\\npin_memory()={100*pin_mem/pin_mem_to_device:.2f}% of runtime.\",\n",
    "]\n",
    "values = [pageable_to_device, pinned_to_device, pin_mem_to_device]\n",
    "colors = [\"tab:blue\", \"tab:red\", \"tab:orange\"]\n",
    "ax.bar(xlabels, values, label=bar_labels, color=colors)\n",
    "\n",
    "ax.set_ylabel(\"Runtime (ms)\")\n",
    "ax.set_title(\"Device casting runtime (pin-memory)\")\n",
    "ax.set_xticks([])\n",
    "ax.legend()\n",
    "\n",
    "plt.show()\n",
    "\n",
    "# Clear tensors\n",
    "del pageable_tensor, pinned_tensor\n",
    "_ = gc.collect()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can observe that casting a pinned-memory tensor to GPU is indeed much\n",
    "faster than a pageable tensor, because under the hood, a pageable tensor\n",
    "must be copied to pinned memory before being sent to GPU.\n",
    "\n",
    "However, contrary to a somewhat common belief, calling\n",
    "`~torch.Tensor.pin_memory()`{.interpreted-text role=\"meth\"} on a\n",
    "pageable tensor before casting it to GPU should not bring any\n",
    "significant speed-up, on the contrary this call is usually slower than\n",
    "just executing the transfer. This makes sense, since we\\'re actually\n",
    "asking Python to execute an operation that CUDA will perform anyway\n",
    "before copying the data from host to device.\n",
    "\n",
    "<div style=\"background-color: #54c7ec; color: #fff; font-weight: 700; padding-left: 10px; padding-top: 5px; padding-bottom: 5px\"><strong>NOTE:</strong></div>\n",
    "\n",
    "<div style=\"background-color: #f3f4f7; padding-left: 10px; padding-top: 10px; padding-bottom: 10px; padding-right: 10px\">\n",
    "\n",
    "<p>The PyTorch implementation of<a href=\"https://github.com/pytorch/pytorch/blob/5298acb5c76855bc5a99ae10016efc86b27949bd/aten/src/ATen/native/Memory.cpp#L58\">pin_memory</a>which relies on creating a brand new storage in pinned memory through <a href=\"https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__MEMORY.html#group__CUDART__MEMORY_1gb65da58f444e7230d3322b6126bb4902\">cudaHostAlloc</a>could be, in rare cases, faster than transitioning data in chunks as <code>cudaMemcpy</code> does.Here too, the observation may vary depending on the available hardware, the size of the tensors being sent orthe amount of available RAM.</p>\n",
    "\n",
    "</div>\n",
    "\n",
    "# `non_blocking=True`\n",
    "\n",
    "As mentioned earlier, many PyTorch operations have the option of being\n",
    "executed asynchronously with respect to the host through the\n",
    "`non_blocking` argument.\n",
    "\n",
    "Here, to account accurately of the benefits of using `non_blocking`, we\n",
    "will design a slightly more complex experiment since we want to assess\n",
    "how fast it is to send multiple tensors to GPU with and without calling\n",
    "`non_blocking`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# A simple loop that copies all tensors to cuda\n",
    "def copy_to_device(*tensors):\n",
    "    result = []\n",
    "    for tensor in tensors:\n",
    "        result.append(tensor.to(\"cuda:0\"))\n",
    "    return result\n",
    "\n",
    "\n",
    "# A loop that copies all tensors to cuda asynchronously\n",
    "def copy_to_device_nonblocking(*tensors):\n",
    "    result = []\n",
    "    for tensor in tensors:\n",
    "        result.append(tensor.to(\"cuda:0\", non_blocking=True))\n",
    "    # We need to synchronize\n",
    "    torch.cuda.synchronize()\n",
    "    return result\n",
    "\n",
    "\n",
    "# Create a list of tensors\n",
    "tensors = [torch.randn(1000) for _ in range(1000)]\n",
    "to_device = timer(\"copy_to_device(*tensors)\")\n",
    "to_device_nonblocking = timer(\"copy_to_device_nonblocking(*tensors)\")\n",
    "\n",
    "# Ratio\n",
    "r1 = to_device_nonblocking / to_device\n",
    "\n",
    "# Plot the results\n",
    "fig, ax = plt.subplots()\n",
    "\n",
    "xlabels = [0, 1]\n",
    "bar_labels = [f\"to(device) (1x)\", f\"to(device, non_blocking=True) ({r1:4.2f}x)\"]\n",
    "colors = [\"tab:blue\", \"tab:red\"]\n",
    "values = [to_device, to_device_nonblocking]\n",
    "\n",
    "ax.bar(xlabels, values, label=bar_labels, color=colors)\n",
    "\n",
    "ax.set_ylabel(\"Runtime (ms)\")\n",
    "ax.set_title(\"Device casting runtime (non-blocking)\")\n",
    "ax.set_xticks([])\n",
    "ax.legend()\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To get a better sense of what is happening here, let us profile these\n",
    "two functions:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from torch.profiler import profile, ProfilerActivity\n",
    "\n",
    "\n",
    "def profile_mem(cmd):\n",
    "    with profile(activities=[ProfilerActivity.CPU]) as prof:\n",
    "        exec(cmd)\n",
    "    print(cmd)\n",
    "    print(prof.key_averages().table(row_limit=10))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let\\'s see the call stack with a regular `to(device)` first:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "print(\"Call to `to(device)`\", profile_mem(\"copy_to_device(*tensors)\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "and now the `non_blocking` version:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "print(\n",
    "    \"Call to `to(device, non_blocking=True)`\",\n",
    "    profile_mem(\"copy_to_device_nonblocking(*tensors)\"),\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The results are without any doubt better when using `non_blocking=True`,\n",
    "as all transfers are initiated simultaneously on the host side and only\n",
    "one synchronization is done.\n",
    "\n",
    "The benefit will vary depending on the number and the size of the\n",
    "tensors as well as depending on the hardware being used.\n",
    "\n",
    "<div style=\"background-color: #54c7ec; color: #fff; font-weight: 700; padding-left: 10px; padding-top: 5px; padding-bottom: 5px\"><strong>NOTE:</strong></div>\n",
    "\n",
    "<div style=\"background-color: #f3f4f7; padding-left: 10px; padding-top: 10px; padding-bottom: 10px; padding-right: 10px\">\n",
    "\n",
    "<p>Interestingly, the blocking <code>to(&quot;cuda&quot;)</code> actually performs the same asynchronous device casting operation(<code>cudaMemcpyAsync</code>) as the one with <code>non_blocking=True</code> with a synchronization point after each copy.</p>\n",
    "\n",
    "</div>\n",
    "\n",
    "# Synergies\n",
    "\n",
    "Now that we have made the point that data transfer of tensors already in\n",
    "pinned memory to GPU is faster than from pageable memory, and that we\n",
    "know that doing these transfers asynchronously is also faster than\n",
    "synchronously, we can benchmark combinations of these approaches. First,\n",
    "let\\'s write a couple of new functions that will call `pin_memory` and\n",
    "`to(device)` on each tensor:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def pin_copy_to_device(*tensors):\n",
    "    result = []\n",
    "    for tensor in tensors:\n",
    "        result.append(tensor.pin_memory().to(\"cuda:0\"))\n",
    "    return result\n",
    "\n",
    "\n",
    "def pin_copy_to_device_nonblocking(*tensors):\n",
    "    result = []\n",
    "    for tensor in tensors:\n",
    "        result.append(tensor.pin_memory().to(\"cuda:0\", non_blocking=True))\n",
    "    # We need to synchronize\n",
    "    torch.cuda.synchronize()\n",
    "    return result"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The benefits of using `~torch.Tensor.pin_memory`{.interpreted-text\n",
    "role=\"meth\"} are more pronounced for somewhat large batches of large\n",
    "tensors:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "tensors = [torch.randn(1_000_000) for _ in range(1000)]\n",
    "page_copy = timer(\"copy_to_device(*tensors)\")\n",
    "page_copy_nb = timer(\"copy_to_device_nonblocking(*tensors)\")\n",
    "\n",
    "tensors_pinned = [torch.randn(1_000_000, pin_memory=True) for _ in range(1000)]\n",
    "pinned_copy = timer(\"copy_to_device(*tensors_pinned)\")\n",
    "pinned_copy_nb = timer(\"copy_to_device_nonblocking(*tensors_pinned)\")\n",
    "\n",
    "pin_and_copy = timer(\"pin_copy_to_device(*tensors)\")\n",
    "pin_and_copy_nb = timer(\"pin_copy_to_device_nonblocking(*tensors)\")\n",
    "\n",
    "# Plot\n",
    "strategies = (\"pageable copy\", \"pinned copy\", \"pin and copy\")\n",
    "blocking = {\n",
    "    \"blocking\": [page_copy, pinned_copy, pin_and_copy],\n",
    "    \"non-blocking\": [page_copy_nb, pinned_copy_nb, pin_and_copy_nb],\n",
    "}\n",
    "\n",
    "x = torch.arange(3)\n",
    "width = 0.25\n",
    "multiplier = 0\n",
    "\n",
    "\n",
    "fig, ax = plt.subplots(layout=\"constrained\")\n",
    "\n",
    "for attribute, runtimes in blocking.items():\n",
    "    offset = width * multiplier\n",
    "    rects = ax.bar(x + offset, runtimes, width, label=attribute)\n",
    "    ax.bar_label(rects, padding=3, fmt=\"%.2f\")\n",
    "    multiplier += 1\n",
    "\n",
    "# Add some text for labels, title and custom x-axis tick labels, etc.\n",
    "ax.set_ylabel(\"Runtime (ms)\")\n",
    "ax.set_title(\"Runtime (pin-mem and non-blocking)\")\n",
    "ax.set_xticks([0, 1, 2])\n",
    "ax.set_xticklabels(strategies)\n",
    "plt.setp(ax.get_xticklabels(), rotation=45, ha=\"right\", rotation_mode=\"anchor\")\n",
    "ax.legend(loc=\"upper left\", ncols=3)\n",
    "\n",
    "plt.show()\n",
    "\n",
    "del tensors, tensors_pinned\n",
    "_ = gc.collect()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Other copy directions (GPU -\\> CPU, CPU -\\> MPS)\n",
    "\n",
    "Until now, we have operated under the assumption that asynchronous\n",
    "copies from the CPU to the GPU are safe. This is generally true because\n",
    "CUDA automatically handles synchronization to ensure that the data being\n",
    "accessed is valid at read time \\_\\_whenever the tensor is in pageable\n",
    "memory\\_\\_.\n",
    "\n",
    "However, in other cases we cannot make the same assumption: when a\n",
    "tensor is placed in pinned memory, mutating the original copy after\n",
    "calling the host-to-device transfer may corrupt the data received on\n",
    "GPU. Similarly, when a transfer is achieved in the opposite direction,\n",
    "from GPU to CPU, or from any device that is not CPU or GPU to any device\n",
    "that is not a CUDA-handled GPU (such as, MPS), there is no guarantee\n",
    "that the data read on GPU is valid without explicit synchronization.\n",
    "\n",
    "In these scenarios, these transfers offer no assurance that the copy\n",
    "will be complete at the time of data access. Consequently, the data on\n",
    "the host might be incomplete or incorrect, effectively rendering it\n",
    "garbage.\n",
    "\n",
    "Let\\'s first demonstrate this with a pinned-memory tensor:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "DELAY = 100000000\n",
    "try:\n",
    "    i = -1\n",
    "    for i in range(100):\n",
    "        # Create a tensor in pin-memory\n",
    "        cpu_tensor = torch.ones(1024, 1024, pin_memory=True)\n",
    "        torch.cuda.synchronize()\n",
    "        # Send the tensor to CUDA\n",
    "        cuda_tensor = cpu_tensor.to(\"cuda\", non_blocking=True)\n",
    "        torch.cuda._sleep(DELAY)\n",
    "        # Corrupt the original tensor\n",
    "        cpu_tensor.zero_()\n",
    "        assert (cuda_tensor == 1).all()\n",
    "    print(\"No test failed with non_blocking and pinned tensor\")\n",
    "except AssertionError:\n",
    "    print(f\"{i}th test failed with non_blocking and pinned tensor. Skipping remaining tests\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Using a pageable tensor always works:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "i = -1\n",
    "for i in range(100):\n",
    "    # Create a tensor in pageable memory\n",
    "    cpu_tensor = torch.ones(1024, 1024)\n",
    "    torch.cuda.synchronize()\n",
    "    # Send the tensor to CUDA\n",
    "    cuda_tensor = cpu_tensor.to(\"cuda\", non_blocking=True)\n",
    "    torch.cuda._sleep(DELAY)\n",
    "    # Corrupt the original tensor\n",
    "    cpu_tensor.zero_()\n",
    "    assert (cuda_tensor == 1).all()\n",
    "print(\"No test failed with non_blocking and pageable tensor\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now let\\'s demonstrate that CUDA to CPU also fails to produce reliable\n",
    "outputs without synchronization:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "tensor = (\n",
    "    torch.arange(1, 1_000_000, dtype=torch.double, device=\"cuda\")\n",
    "    .expand(100, 999999)\n",
    "    .clone()\n",
    ")\n",
    "torch.testing.assert_close(\n",
    "    tensor.mean(), torch.tensor(500_000, dtype=torch.double, device=\"cuda\")\n",
    "), tensor.mean()\n",
    "try:\n",
    "    i = -1\n",
    "    for i in range(100):\n",
    "        cpu_tensor = tensor.to(\"cpu\", non_blocking=True)\n",
    "        torch.testing.assert_close(\n",
    "            cpu_tensor.mean(), torch.tensor(500_000, dtype=torch.double)\n",
    "        )\n",
    "    print(\"No test failed with non_blocking\")\n",
    "except AssertionError:\n",
    "    print(f\"{i}th test failed with non_blocking. Skipping remaining tests\")\n",
    "try:\n",
    "    i = -1\n",
    "    for i in range(100):\n",
    "        cpu_tensor = tensor.to(\"cpu\", non_blocking=True)\n",
    "        torch.cuda.synchronize()\n",
    "        torch.testing.assert_close(\n",
    "            cpu_tensor.mean(), torch.tensor(500_000, dtype=torch.double)\n",
    "        )\n",
    "    print(\"No test failed with synchronize\")\n",
    "except AssertionError:\n",
    "    print(f\"One test failed with synchronize: {i}th assertion!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Generally, asynchronous copies to a device are safe without explicit\n",
    "synchronization only when the target is a CUDA-enabled device and the\n",
    "original tensor is in pageable memory.\n",
    "\n",
    "In summary, copying data from CPU to GPU is safe when using\n",
    "`non_blocking=True`, but for any other direction, `non_blocking=True`\n",
    "can still be used but the user must make sure that a device\n",
    "synchronization is executed before the data is accessed.\n",
    "\n",
    "# Practical recommendations\n",
    "\n",
    "We can now wrap up some early recommendations based on our observations:\n",
    "\n",
    "In general, `non_blocking=True` will provide good throughput, regardless\n",
    "of whether the original tensor is or isn\\'t in pinned memory. If the\n",
    "tensor is already in pinned memory, the transfer can be accelerated, but\n",
    "sending it to pin memory manually from python main thread is a blocking\n",
    "operation on the host, and hence will annihilate much of the benefit of\n",
    "using `non_blocking=True` (as CUDA does the [pin_memory]{.title-ref}\n",
    "transfer anyway).\n",
    "\n",
    "One might now legitimately ask what use there is for the\n",
    "`~torch.Tensor.pin_memory`{.interpreted-text role=\"meth\"} method. In the\n",
    "following section, we will explore further how this can be used to\n",
    "accelerate the data transfer even more.\n",
    "\n",
    "# Additional considerations\n",
    "\n",
    "PyTorch notoriously provides a\n",
    "`~torch.utils.data.DataLoader`{.interpreted-text role=\"class\"} class\n",
    "whose constructor accepts a `pin_memory` argument. Considering our\n",
    "previous discussion on `pin_memory`, you might wonder how the\n",
    "`DataLoader` manages to accelerate data transfers if memory pinning is\n",
    "inherently blocking.\n",
    "\n",
    "The key lies in the DataLoader\\'s use of a separate thread to handle the\n",
    "transfer of data from pageable to pinned memory, thus preventing any\n",
    "blockage in the main thread.\n",
    "\n",
    "To illustrate this, we will use the TensorDict primitive from the\n",
    "homonymous library. When invoking\n",
    "`~tensordict.TensorDict.to`{.interpreted-text role=\"meth\"}, the default\n",
    "behavior is to send tensors to the device asynchronously, followed by a\n",
    "single call to `torch.device.synchronize()` afterwards.\n",
    "\n",
    "Additionally, `TensorDict.to()` includes a `non_blocking_pin` option\n",
    "which initiates multiple threads to execute `pin_memory()` before\n",
    "proceeding with to `to(device)`. This approach can further accelerate\n",
    "data transfers, as demonstrated in the following example.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from tensordict import TensorDict\n",
    "import torch\n",
    "from torch.utils.benchmark import Timer\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "# Create the dataset\n",
    "td = TensorDict({str(i): torch.randn(1_000_000) for i in range(1000)})\n",
    "\n",
    "# Runtimes\n",
    "copy_blocking = timer(\"td.to('cuda:0', non_blocking=False)\")\n",
    "copy_non_blocking = timer(\"td.to('cuda:0')\")\n",
    "copy_pin_nb = timer(\"td.to('cuda:0', non_blocking_pin=True, num_threads=0)\")\n",
    "copy_pin_multithread_nb = timer(\"td.to('cuda:0', non_blocking_pin=True, num_threads=4)\")\n",
    "\n",
    "# Rations\n",
    "r1 = copy_non_blocking / copy_blocking\n",
    "r2 = copy_pin_nb / copy_blocking\n",
    "r3 = copy_pin_multithread_nb / copy_blocking\n",
    "\n",
    "# Figure\n",
    "fig, ax = plt.subplots()\n",
    "\n",
    "xlabels = [0, 1, 2, 3]\n",
    "bar_labels = [\n",
    "    \"Blocking copy (1x)\",\n",
    "    f\"Non-blocking copy ({r1:4.2f}x)\",\n",
    "    f\"Blocking pin, non-blocking copy ({r2:4.2f}x)\",\n",
    "    f\"Non-blocking pin, non-blocking copy ({r3:4.2f}x)\",\n",
    "]\n",
    "values = [copy_blocking, copy_non_blocking, copy_pin_nb, copy_pin_multithread_nb]\n",
    "colors = [\"tab:blue\", \"tab:red\", \"tab:orange\", \"tab:green\"]\n",
    "\n",
    "ax.bar(xlabels, values, label=bar_labels, color=colors)\n",
    "\n",
    "ax.set_ylabel(\"Runtime (ms)\")\n",
    "ax.set_title(\"Device casting runtime\")\n",
    "ax.set_xticks([])\n",
    "ax.legend()\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this example, we are transferring many large tensors from the CPU to\n",
    "the GPU. This scenario is ideal for utilizing multithreaded\n",
    "`pin_memory()`, which can significantly enhance performance. However, if\n",
    "the tensors are small, the overhead associated with multithreading may\n",
    "outweigh the benefits. Similarly, if there are only a few tensors, the\n",
    "advantages of pinning tensors on separate threads become limited.\n",
    "\n",
    "As an additional note, while it might seem advantageous to create\n",
    "permanent buffers in pinned memory to shuttle tensors from pageable\n",
    "memory before transferring them to the GPU, this strategy does not\n",
    "necessarily expedite computation. The inherent bottleneck caused by\n",
    "copying data into pinned memory remains a limiting factor.\n",
    "\n",
    "Moreover, transferring data that resides on disk (whether in shared\n",
    "memory or files) to the GPU typically requires an intermediate step of\n",
    "copying the data into pinned memory (located in RAM). Utilizing\n",
    "non_blocking for large data transfers in this context can significantly\n",
    "increase RAM consumption, potentially leading to adverse effects.\n",
    "\n",
    "In practice, there is no one-size-fits-all solution. The effectiveness\n",
    "of using multithreaded `pin_memory` combined with `non_blocking`\n",
    "transfers depends on a variety of factors, including the specific\n",
    "system, operating system, hardware, and the nature of the tasks being\n",
    "executed. Here is a list of factors to check when trying to speed-up\n",
    "data transfers between CPU and GPU, or comparing throughput\\'s across\n",
    "scenarios:\n",
    "\n",
    "-   **Number of available cores**\n",
    "\n",
    "    How many CPU cores are available? Is the system shared with other\n",
    "    users or processes that might compete for resources?\n",
    "\n",
    "-   **Core utilization**\n",
    "\n",
    "    Are the CPU cores heavily utilized by other processes? Does the\n",
    "    application perform other CPU-intensive tasks concurrently with data\n",
    "    transfers?\n",
    "\n",
    "-   **Memory utilization**\n",
    "\n",
    "    How much pageable and page-locked memory is currently being used? Is\n",
    "    there sufficient free memory to allocate additional pinned memory\n",
    "    without affecting system performance? Remember that nothing comes\n",
    "    for free, for instance `pin_memory` will consume RAM and may impact\n",
    "    other tasks.\n",
    "\n",
    "-   **CUDA Device Capabilities**\n",
    "\n",
    "    Does the GPU support multiple DMA engines for concurrent data\n",
    "    transfers? What are the specific capabilities and limitations of the\n",
    "    CUDA device being used?\n",
    "\n",
    "-   **Number of tensors to be sent**\n",
    "\n",
    "    How many tensors are transferred in a typical operation?\n",
    "\n",
    "-   **Size of the tensors to be sent**\n",
    "\n",
    "    What is the size of the tensors being transferred? A few large\n",
    "    tensors or many small tensors may not benefit from the same transfer\n",
    "    program.\n",
    "\n",
    "-   **System Architecture**\n",
    "\n",
    "    How is the system\\'s architecture influencing data transfer speeds\n",
    "    (for example, bus speeds, network latency)?\n",
    "\n",
    "Additionally, allocating a large number of tensors or sizable tensors in\n",
    "pinned memory can monopolize a substantial portion of RAM. This reduces\n",
    "the available memory for other critical operations, such as paging,\n",
    "which can negatively impact the overall performance of an algorithm.\n",
    "\n",
    "# Conclusion\n",
    "\n",
    "Throughout this tutorial, we have explored several critical factors that\n",
    "influence transfer speeds and memory management when sending tensors\n",
    "from the host to the device. We\\'ve learned that using\n",
    "`non_blocking=True` generally accelerates data transfers, and that\n",
    "`~torch.Tensor.pin_memory`{.interpreted-text role=\"meth\"} can also\n",
    "enhance performance if implemented correctly. However, these techniques\n",
    "require careful design and calibration to be effective.\n",
    "\n",
    "Remember that profiling your code and keeping an eye on the memory\n",
    "consumption are essential to optimize resource usage and achieve the\n",
    "best possible performance.\n",
    "\n",
    "# Additional resources\n",
    "\n",
    "If you are dealing with issues with memory copies when using CUDA\n",
    "devices or want to learn more about what was discussed in this tutorial,\n",
    "check the following references:\n",
    "\n",
    "-   [CUDA toolkit memory management\n",
    "    doc](https://docs.nvidia.com/cuda/cuda-runtime-api/group__CUDART__MEMORY.html);\n",
    "-   [CUDA pin-memory\n",
    "    note](https://forums.developer.nvidia.com/t/pinned-memory/268474);\n",
    "-   [How to Optimize Data Transfers in CUDA\n",
    "    C/C++](https://developer.nvidia.com/blog/how-optimize-data-transfers-cuda-cc/);\n",
    "-   [tensordict doc](https://pytorch.org/tensordict/stable/index.html)\n",
    "    and [repo](https://github.com/pytorch/tensordict).\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
