{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Chaim Rand",
  "title_listed": "Optimizing Data Transfer in Batched AI/ML Inference Workloads",
  "keywords": "",
  "domain": "数据处理",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/optimizing-data-transfer-in-batched-ai-ml-inference-workloads/",
  "publish_date": "2026-01-12",
  "corpus_stage": "",
  "notes": "",
  "id": "e04716433f71",
  "collected_at": "2026-10-02T11:01:15",
  "title": "Optimizing Data Transfer in Batched AI/ML Inference Workloads | Towards Data Science",
  "body_markdown": "![Revisit consent button](../images/body-df29beacd7496220cc94.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](../images/body-2159bb67f3de8ad870eb.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Data Engineering](https://towardsdatascience.com/category/data-science/data-engineering/)\n# Optimizing Data Transfer in Batched AI/ML Inference Workloads\nA deep dive on data transfer bottlenecks, their identification, and their resolution with the help of NVIDIA Nsight™ Systems - part 2\n[Chaim Rand](https://towardsdatascience.com/author/chaimrand/)\nJanuary 12, 202612 min read\n![](../images/000.jpeg)\n[Photo](https://unsplash.com/photos/landscape-photography-of-snowy-mountain-and-body-of-water-efuwb5eBDrI) by Joel & Jasmin Førestbird on Unsplash\nThis is a sequel post to [Optimizing Data Transfer in AI/ML Workloads](https://towardsdatascience.com/optimizing-data-transfer-in-ai-ml-workloads/) where we demonstrated the use of [NVIDIA Nsight™ Systems (nsys)](https://docs.nvidia.com/nsight-systems/index.html) in studying and solving the common data-loading bottleneck — occurrences where the GPU idles while it waits for input data from the CPU. In this post we focus our attention on data travelling in the opposite direction, from the GPU device to the CPU host. More specifically, we address AI/ML inference workloads where the size of the output being returned by the model is relatively high. Common examples include: 1) running a scene segmentation (per-pixel labeling) model on batches of high-resolution images and 2) capturing high dimensional feature embeddings of input sequences using an encoder model (e.g., to create a [vector database](https://en.wikipedia.org/wiki/Vector_database)). Both examples involve executing a model on an input batch and then copying the output tensor from the GPU to the CPU for additional processing, storage, and/or over-the-network communication.\nGPU-to-CPU memory copies of the model output typically receive much less attention in optimization tutorials than the CPU-to-GPU copies that feed the model (e.g., see [here](https://docs.pytorch.org/tutorials/recipes/recipes/tuning_guide.html)). But their potential impact on model efficiency and execution costs can be just as detrimental. Moreover, while optimizations to CPU-to-GPU data-loading are well documented and easy to implement, optimizing data copy in the opposite direction requires a bit more manual labor.\nIn this post we will apply the same strategy we used in our previous post: We will define a toy model and use nsys profiler to identify and solve performance bottlenecks. We will run our experiments on an [Amazon EC2 g6e.2xlarge](https://aws.amazon.com/ec2/instance-types/g6e/) instance (with an [NVIDIA L40S](https://www.nvidia.com/en-eu/data-center/l40s/) GPU) running an [AWS Deep Learning (Ubuntu 24.04) AMI](https://docs.aws.amazon.com/dlami/latest/devguide/appendix-ami-release-notes.html) with [PyTorch (2.8)](https://pytorch.org/get-started/locally/), [nsys-cli profiler](https://developer.nvidia.com/nsight-systems/get-started) (version 2025.6.1), and the [NVIDIA Tools Extension](https://docs.nvidia.com/tools-extension/index.html) (NVTX) library.\nLearn this step by step with the interactive [Data Engineer](https://roadmap.sh/data-engineer) roadmap.\n#### Disclaimers\nThe code we will share is intended for demonstrative purposes; please do not rely on its correctness or optimality. Please do not interpret our use of any library, tool, or platform, as an endorsement of its use. The impact of the optimizations we will cover can vary greatly based on the details of the model and the runtime environment. Please be sure to assess their effect on your own use case before integrating their use.\nMany thanks to [Yitzhak Levi](https://www.linkedin.com/in/yitzhak-levi-49a217201/) and [Gilad Wasserman](https://www.linkedin.com/in/gilad-wasserman-992530268/?originalSubdomain=il) for their contributions to this post.\n### A Toy PyTorch Model\nWe introduce a batched inference script that performs image segmentation on a synthetic dataset using a [DeepLabV3](https://docs.pytorch.org/vision/main/models/deeplabv3.html) model with a [ResNet-50](https://docs.pytorch.org/vision/main/models/generated/torchvision.models.resnet50.html#torchvision.models.resnet50) backbone. The model outputs are copied to the CPU for post processing and storage. We wrap the different portions of the inference step with color-coded [nvtx](https://nvtx.readthedocs.io/en/latest/index.html) annotations:\npython\n\n```\nimport time, torch, nvtx\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.cuda import profiler\nfrom torchvision.models.segmentation import deeplabv3_resnet50\n\nDEVICE = \"cuda\"\nWARMUP_STEPS = 10\nPROFILE_STEPS = 3\nCOOLDOWN_STEPS = 1\nTOTAL_STEPS = WARMUP_STEPS + PROFILE_STEPS + COOLDOWN_STEPS\nBATCH_SIZE = 64\nTOTAL_SAMPLES = TOTAL_STEPS * BATCH_SIZE\nIMG_SIZE = 512\nN_CLASSES = 21\nNUM_WORKERS = 8\nASYNC_DATALOAD = True\n\n\n# A synthetic Dataset with random images\nclass FakeDataset(Dataset):\n\n    def __len__(self):\n        return TOTAL_SAMPLES\n\n    def __getitem__(self, index):\n        img = torch.randn((3, IMG_SIZE, IMG_SIZE))\n        return img\n\n# utility class for prefetching data to GPU\nclass DataPrefetcher:\n    def __init__(self, loader):\n        self.loader = iter(loader)\n        self.stream = torch.cuda.Stream()\n        self.next_batch = None\n        self.preload()\n\n    def preload(self):\n        try:\n            data = next(self.loader)\n            with torch.cuda.stream(self.stream):\n                next_data = data.to(DEVICE, non_blocking=ASYNC_DATALOAD)\n            self.next_batch = next_data\n        except:\n            self.next_batch = None\n\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        torch.cuda.current_stream().wait_stream(self.stream)\n        data = self.next_batch\n        self.preload()\n        return data\n\nmodel = deeplabv3_resnet50(weights_backbone=None).to(DEVICE).eval()\n\ndata_loader = DataLoader(\n    FakeDataset(),\n    batch_size=BATCH_SIZE,\n    num_workers=NUM_WORKERS,\n    pin_memory=ASYNC_DATALOAD\n)\n\ndata_iter = DataPrefetcher(data_loader)\n\ndef synchronize_all():\n    torch.cuda.synchronize() \n\ndef to_cpu(output):\n    return output.cpu()\n\ndef process_output(batch_id, logits):\n    # do some post processing on output\n    with open('/dev/null', 'wb') as f:\n        f.write(logits.numpy().tobytes())\n\nwith torch.inference_mode():\n    for i in range(TOTAL_STEPS):\n        if i == WARMUP_STEPS:\n            synchronize_all()\n            start_time = time.perf_counter()\n            profiler.start()\n        elif i == WARMUP_STEPS + PROFILE_STEPS:\n            synchronize_all()\n            profiler.stop()\n            end_time = time.perf_counter()\n\n        with nvtx.annotate(f\"Batch {i}\", color=\"blue\"):\n            with nvtx.annotate(\"get batch\", color=\"red\"):\n                batch = next(data_iter)\n            with nvtx.annotate(\"compute\", color=\"green\"):\n                output = model(batch)\n            with nvtx.annotate(\"copy to CPU\", color=\"yellow\"):\n                output_cpu = to_cpu(output['out'])\n            with nvtx.annotate(\"process output\", color=\"cyan\"):\n                process_output(i, output_cpu)\n\ntotal_time = end_time - start_time\nthroughput = PROFILE_STEPS / total_time\nprint(f\"Throughput: {throughput:.2f} steps/sec\")\n```\n\nNote the inclusion of all of the CPU-to-GPU data-loading optimizations discussed in our previous post.\nWe run the following command to capture an nsys profile trace:\nbash\n\n```\nnsys profile \\\n  --capture-range=cudaProfilerApi \\\n  --trace=cuda,nvtx,osrt \\\n  --output=baseline \\\n  python batch_infer.py\n```\n\nThis results in a  _baseline.nsys-rep_ trace file that we copy over to our development machine for analysis.\nTo measure the inference throughput, we increase the number of steps to 100. The average throughput of our baseline experiment is 0.45 steps-per-second. In the following sections we will use the nsys profile traces to incrementally improve this result.\n#### Baseline Performance Analysis\nThe image below shows the nsys profile trace of our baseline experiment:\n![](../images/001.webp)\nBaseline Nsight Systems Profiler Trace (by Author)\nIn the GPU section we see the following recurring pattern:\n  1. A block of kernel compute (in light blue) that runs for ~520 milliseconds.\n  2. A small block of host-to-device memory copy (in green) that runs in parallel to the kernel compute. This concurrency was achieved using the optimizations discussed in our previous post.\n  3. A block of device-to-host memory copy (in red) that runs for ~750 milliseconds.\n  4. A long period (~940 milliseconds) of GPU idle time (white space) between every two steps.\n\n\nLooking at the NVTX bar of the CPU section, we can see that the whitespace aligns perfectly with the “process output” block (in cyan). In our initial implementation, both the model execution and the output storage function run in the same single process in a sequential manner. This leads to significant idle time on the GPU as the CPU waits for the storage function to return before feeding the GPU the next batch.\n### Optimization 1: Multi-Worker Output Processing\nThe first step we take is to run the output storage function in parallel worker processes. We took a similar step in our previous post when we moved the input batch preparation sequence to dedicated workers. However, whereas there we were able to automate [multi-process data loading](https://docs.pytorch.org/docs/stable/data.html#multi-process-data-loading) by simply setting the  _num_workers_ argument of the [DataLoader](https://docs.pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader) class to a non-zero value, applying multi-worker output-processing requires a manual implementation. Here we choose a simple solution for demonstrative purposes. This should be customized per your needs and design preferences.\n#### PyTorch Multiprocessing\nWe implement a producer-consumer strategy using PyTorch’s built-in multiprocessing package, [torch.multiprocessing](https://docs.pytorch.org/docs/stable/multiprocessing.html). We define a queue for storing output batches and multiple consumer workers that process the batches on the queue. We modify our inference loop to put the output buffers in the output queue. We also update the  _synchronize_all()_ utility to drain the queue and append a cleanup sequence at the end of the script.\nThe following block of code contains our initial implementation. As we will see in the next sections, this will require some tuning in order to reach maximum performance.\npython\n\n```\nimport torch.multiprocessing as mp\n\nPOSTPROC_WORKERS = 8 # tune for optimal throughput\n\noutput_queue = mp.JoinableQueue(maxsize=POSTPROC_WORKERS)\n\ndef output_worker(in_q):\n    while True:\n        item = in_q.get()\n        if item is None: break  # signal to shut down\n        batch_id, batch_preds = item\n        process_output(batch_id, batch_preds)\n        in_q.task_done()\n\nprocesses = []\nfor _ in range(POSTPROC_WORKERS):\n    p = mp.Process(target=output_worker, args=(output_queue,))\n    p.start()\n    processes.append(p)\n\ndef synchronize_all():\n    torch.cuda.synchronize() \n    output_queue.join() # drain queue\n\n\nwith torch.inference_mode():\n    for i in range(TOTAL_STEPS):\n        if i == WARMUP_STEPS:\n            synchronize_all()\n            start_time = time.perf_counter()\n            profiler.start()\n        elif i == WARMUP_STEPS + PROFILE_STEPS:\n            synchronize_all()\n            profiler.stop()\n            end_time = time.perf_counter()\n\n        with nvtx.annotate(f\"Batch {i}\", color=\"blue\"):\n            with nvtx.annotate(\"get batch\", color=\"red\"):\n                batch = next(data_iter)\n            with nvtx.annotate(\"compute\", color=\"green\"):\n                output = model(batch)\n            with nvtx.annotate(\"copy to CPU\", color=\"yellow\"):\n                output_cpu = to_cpu(output['out'])\n            with nvtx.annotate(\"queue output\", color=\"cyan\"):\n                output_queue.put((i, output_cpu))\n\n\ntotal_time = end_time - start_time\nthroughput = PROFILE_STEPS / total_time\nprint(f\"Throughput: {throughput:.2f} steps/sec\")\n# cleanup\nfor _ in range(POSTPROC_WORKERS):\n    output_queue.put(None)\n```\n\nThe multi-worker output processing optimization results in a throughput of 0.71 steps-per-second — a 58% increase over our baseline results.\nRerunning the nsys command results in the following profile trace:\n![](../images/body-0d6c89c1666062684ea5.webp)\nMulti-Worker Nsight Systems Profiler Timeline (by Author)\nWe can see that the size of the block of whitespace has dropped considerably (from ~940 milliseconds to ~50). Were we to zoom in on the remaining whitespace, we would find it aligned to an “munmap” operation. In our previous post, the same finding informed our asynchronous data copy optimization. But this time we take an intermediate memory-optimization step in the form of a pre-allocated pool of buffers.\n### Optimization 2: Buffer Pool Pre-allocation\nIn order to reduce the overhead of allocating and managing a new CPU tensor on every iteration, we initialize a pool of tensors pre-allocated in shared memory and define a second queue to manage their use.\nOur updated code appears below:\npython\n\n```\nshape = (BATCH_SIZE, N_CLASSES, IMG_SIZE, IMG_SIZE)\nbuffer_pool = [torch.empty(shape).share_memory_() \n               for _ in range(POSTPROC_WORKERS)]\n\nbuf_queue = mp.Queue()\nfor i in range(POSTPROC_WORKERS):\n    buf_queue.put(i)\n\ndef output_worker(buffer_pool, in_q, buf_q):\n    while True:\n        item = in_q.get()\n        if item is None: break  # signal to shut down\n        batch_id, buf_id = item\n        process_output(batch_id, buffer_pool[buf_id])\n        buf_q.put(buf_id)\n        in_q.task_done()\n\nprocesses = []\nfor _ in range(POSTPROC_WORKERS):\n    p = mp.Process(target=output_worker,\n                   args=(buffer_pool,output_queue,buf_queue))\n    p.start()\n    processes.append(p)\n\ndef to_cpu(output):\n    buf_id = buf_queue.get()\n    output_cpu = buffer_pool[buf_id]\n    output_cpu.copy_(output)\n    return output_cpu, buf_id\n\nwith torch.inference_mode():\n    for i in range(TOTAL_STEPS):\n        if i == WARMUP_STEPS:\n            synchronize_all()\n            start_time = time.perf_counter()\n            profiler.start()\n        elif i == WARMUP_STEPS + PROFILE_STEPS:\n            synchronize_all()\n            profiler.stop()\n            end_time = time.perf_counter()\n\n        with nvtx.annotate(f\"Batch {i}\", color=\"blue\"):\n            with nvtx.annotate(\"get batch\", color=\"red\"):\n                batch = next(data_iter)\n            with nvtx.annotate(\"compute\", color=\"green\"):\n                output = model(batch)\n            with nvtx.annotate(\"copy to CPU\", color=\"yellow\"):\n                output_cpu, buf_id = to_cpu(output['out'])\n            with nvtx.annotate(\"queue output\", color=\"cyan\"):\n                output_queue.put((i, buf_id))\n```\n\nFollowing these changes, the inference throughput jumps to 1.51 — a more than 2 _X_ speed-up over our previous result.\nThe new profile trace appears below:\n![](../images/body-8df664b520bbed8f069f.webp)\nBuffer Pool Nsight Systems Profiler Timeline (by Author)\nNot only has the whitespace all but disappeared, but the CUDA DtoH memory operation (in red) has dropped from ~750 milliseconds to ~110. Presumably, the large GPU-to-CPU data copy involved quite a bit of memory-management overhead that we have removed by implementing a dedicated buffer pool.\nDespite the considerable improvement, if we zoom in we will find that there remains around ~0.5 milliseconds of whitespace that is caused by the synchronicity of the GPU-to-CPU copy command — so long as the copy has not completed the CPU does not trigger the kernel computation of the next batch.\n### Optimization 3: Asynchronous Data Copy\nOur third optimization is to change the device-to-host copy to be asynchronous. As before, we will find that implementing this change is more difficult than in the CPU-to-GPU direction.\nThe first step is to pass `non_blocking=True` to the GPU-to-CPU copy command.\npython\n\n```\ndef to_cpu(output):\n    buf_id = buf_queue.get()\n    output_cpu = buffer_pool[buf_id]\n    output_cpu.copy_(output, non_blocking=True)\n    return output_cpu, buf_id\n```\n\nHowever, as we saw in our previous post, this change will not have a meaningful impact unless we modify our tensors to use pinned memory:\npython\n\n```\nshape = (BATCH_SIZE, N_CLASSES, IMG_SIZE, IMG_SIZE)\nbuffer_pool = [torch.empty(shape, pin_memory=True).share_memory_() \n               for _ in range(POSTPROC_WORKERS)]\n```\n\nCrucially, if we apply only these two changes to our script, the throughput would increase but the output may be corrupted (e.g., see [here](https://docs.pytorch.org/tutorials/intermediate/pinmem_nonblock.html#other-copy-directions-gpu-cpu-cpu-mps)). We need an event-based mechanism for identifying each time a GPU-to-CPU copy has been completed so that we can proceed with the output data processing. (Note, that this was not required when making the CPU-to-GPU copy asynchronous. Because a single GPU stream processes commands sequentially, the kernel computation only starts when the copy has completed. Synchronization was only required when introducing a second stream.)\nTo implement the notification mechanism, we define a pool of CUDA events and an additional queue for managing their use. We further define a listener thread for monitoring the state of events on the queue and populating the output queue once the copies are complete.\npython\n\n```\nimport threading, queue\n\nevent_pool = [torch.cuda.Event() for _ in range(POSTPROC_WORKERS)]\nevent_queue = queue.Queue()\n\ndef event_monitor(event_pool, event_queue, output_queue):\n    while True:\n        item = event_queue.get()\n        if item is None: break\n        batch_id, buf_idx = item\n        event_pool[buf_idx].synchronize()\n        output_queue.put((batch_id, buf_idx))\n        event_queue.task_done()\n\nmonitor = threading.Thread(target=event_monitor,\n                           args=(event_pool, event_queue, output_queue))\nmonitor.start()\n```\n\nThe updated inference sequence consists of the following steps:\n  1. Get an input batch that was prefetched to the GPU.\n  2. Execute the model on the input batch to get an output tensor on the GPU.\n  3. Request a vacant CPU buffer from the buffer queue and use it to trigger an asynchronous data copy. Configure an event to trigger when the copy is complete and push the event to the event-queue.\n  4. The monitor thread waits for the event to trigger and then pushes the output tensor to the output queue for processing.\n  5. A worker thread pulls the output tensor from the queue and saves it to disk. It then releases the buffer back to the buffer queue.\n\n\nThe updated code appears below.\npython\n\n```\ndef synchronize_all():\n    torch.cuda.synchronize()\n    event_queue.join()\n    output_queue.join()\n\n\nwith torch.inference_mode():\n    for i in range(TOTAL_STEPS):\n        if i == WARMUP_STEPS:\n            synchronize_all()\n            start_time = time.perf_counter()\n            profiler.start()\n        elif i == WARMUP_STEPS + PROFILE_STEPS:\n            synchronize_all()\n            profiler.stop()\n            end_time = time.perf_counter()\n\n        with nvtx.annotate(f\"Batch {i}\", color=\"blue\"):\n            with nvtx.annotate(\"get batch\", color=\"red\"):\n                batch = next(data_iter)\n            with nvtx.annotate(\"compute\", color=\"green\"):\n                output = model(batch)\n            with nvtx.annotate(\"copy to CPU\", color=\"yellow\"):\n                output_cpu, buf_id = to_cpu(output['out'])\n            with nvtx.annotate(\"queue CUDA event\", color=\"cyan\"):\n                event_pool[buf_id].record()\n                event_queue.put((i, buf_id))\n\ntotal_time = end_time - start_time\nthroughput = PROFILE_STEPS / total_time\nprint(f\"Throughput: {throughput:.2f} steps/sec\")\n# cleanup\nevent_queue.put(None)\nfor _ in range(POSTPROC_WORKERS):\n    output_queue.put(None)\n```\n\nThe resultant throughput is 1.55 steps-per-second.\nThe new profile trace appears below:\n![](../images/body-a0cb5efd5467a29a5237.webp)\nAsync Data Transfer Nsight Systems Profiler Timeline (by Author)\nIn the NVTX row of the CPU section we can see all of the operations in the inference loop bunched together on left side — implying that they all ran immediately and asynchronously. We also see the event synchronization calls (in light green) running on the dedicated monitor thread. In the GPU section we see that the kernel computation begins immediately after the device-to-host copy has completed.\nOur final optimization will focus on improving the parallelization of the kernel and memory operations on the GPU.\n### Optimization 4: Pipelining Using CUDA Streams\nAs in our previous post, we wish to take advantage of the independent engines for memory copying (the DMA) and kernel compute (the SMs). We do this by assigning the memory copy to a dedicated CUDA stream:\npython\n\n```\negress_stream = torch.cuda.Stream()\n\nwith torch.inference_mode():\n    for i in range(TOTAL_STEPS):\n        if i == WARMUP_STEPS:\n            synchronize_all()\n            start_time = time.perf_counter()\n            profiler.start()\n        elif i == WARMUP_STEPS + PROFILE_STEPS:\n            synchronize_all()\n            profiler.stop()\n            end_time = time.perf_counter()\n\n        with nvtx.annotate(f\"Batch {i}\", color=\"blue\"):\n            with nvtx.annotate(\"get batch\", color=\"red\"):\n                batch = next(data_iter)\n            with nvtx.annotate(\"compute\", color=\"green\"):\n                output = model(batch)\n            \n            # on separate stream\n            with torch.cuda.stream(egress_stream):\n                # wait for default stream to complete compute\n                egress_stream.wait_stream(torch.cuda.default_stream())\n                # Mark that egress_stream will use this tensor\n                output['out'].record_stream(egress_stream)\n                with nvtx.annotate(\"copy to CPU\", color=\"yellow\"):\n                    output_cpu, buf_id = to_cpu(output['out'])\n                with nvtx.annotate(\"queue CUDA event\", color=\"cyan\"):\n                    event_pool[buf_id].record(egress_stream)\n                    event_queue.put((i, buf_id))\n```\n\nThis results in a throughput of 1.85 steps per second — an additional 19.3% improvement over our previous experiment.\nThe final profile trace appears below:\n![](../images/body-ecaa89f42d057b19485e.webp)\nPipelined Nsight Systems Profiler Timeline (by Author)\nIn the GPU section we see a continuous block of kernel compute (in light blue) with both the host-to-device (in light green) and device-to-host (in purple) running in parallel. Our inference loop is now compute-bound, implying that we have exhausted all practical opportunities for data-transfer optimization.\n## Results\nWe summarize our results in the following table:\n![](../images/body-24e9ca0145ae5642942b.webp)\nExperiment Results (by Author)\nThrough the use of nsys profiler we were able to increase efficiency by over 4 _X_. Naturally, the impact of the optimizations we discussed will vary based on the details of the model and runtime environment.\n## Summary\nThis concludes the second part of our series of posts on the topic of optimizing data-transfer in AI/ML workloads. Part one focused on host-to-device copies and part two on device-to-host copies. When implemented naively, data-transfer in either direction can lead to significant performance bottlenecks resulting in GPU starvation and increased runtime costs. Using Nsight Systems profiler, we demonstrated how to identify and resolve these bottlenecks and increase runtime efficiency.\nAlthough the optimization of both directions involved similar steps, the implementation details were very different. While optimizing CPU-to-GPU data-transfer is well-supported by PyTorch’s data-loading APIs and required relatively small changes to the execution loop, optimizing the the GPU-to-CPU direction required a bit more software engineering. Importantly, the solutions we put forth in this post were chosen for demonstrative purposes. Your own solution may differ considerably based on your project needs and design preferences.\nHaving covered both CPU-to-GPU and GPU-to-CPU data copies, we turn our attention to GPU-to-GPU transactions: Stay tuned for a future post on the topic of optimizing data transfer between GPUs in distributed training workloads.\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](../images/body-97f5483d57a9b8741146.jpeg)\nWritten By\n## [Chaim Rand](https://towardsdatascience.com/author/chaimrand/)\n[See all from Chaim Rand](https://towardsdatascience.com/author/chaimrand/)\n[Deep Dives](https://towardsdatascience.com/tag/deep-dives/)[Artificial Intelligence](https://towardsdatascience.com/tag/artificial-intelligence/)[Machine Learning](https://towardsdatascience.com/tag/machine-learning/)[Model Optimization](https://towardsdatascience.com/tag/model-optimization/)[Pytorch](https://towardsdatascience.com/tag/pytorch/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Foptimizing-data-transfer-in-batched-ai-ml-inference-workloads%2F&title=Optimizing%20Data%20Transfer%20in%20Batched%20AI%2FML%20Inference%20Workloads)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Foptimizing-data-transfer-in-batched-ai-ml-inference-workloads%2F&title=Optimizing%20Data%20Transfer%20in%20Batched%20AI%2FML%20Inference%20Workloads)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Foptimizing-data-transfer-in-batched-ai-ml-inference-workloads%2F&text=Optimizing%20Data%20Transfer%20in%20Batched%20AI%2FML%20Inference%20Workloads)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](../images/002.jpg)](https://towardsdatascience.com/run-airbyte-syncs-on-a-custom-schedule-with-crontab-and-http-requests-8d6fbb3ea112/)\n## [Run Airbyte Syncs On A Custom Schedule With Crontab And HTTP Requests](https://towardsdatascience.com/run-airbyte-syncs-on-a-custom-schedule-with-crontab-and-http-requests-8d6fbb3ea112/)\n[Programming](https://towardsdatascience.com/category/programming/)\nLeverage Airbyte's simple REST API for complex configuration\n[Isaac Harris-Holt](https://towardsdatascience.com/author/isaacharrisholt/)\nApril 23, 20224 min read\n  * [![](../images/003.gif)](https://towardsdatascience.com/ai-is-not-a-black-box/)\n## [AI Is Not a Black Box (Relatively Speaking)](https://towardsdatascience.com/ai-is-not-a-black-box/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nCompared to the opacity around human intelligence, AI is more transparent in some very tangible ways.\n[Piotr Mardziel](https://towardsdatascience.com/author/piotrm_69949/)\nJune 13, 20256 min read\n  * [![](../images/004.jpeg)](https://towardsdatascience.com/the-best-way-to-practice-data-science-tools-7435fa5ca87d/)\n## [The Best Way to Practice Data Science Tools](https://towardsdatascience.com/the-best-way-to-practice-data-science-tools-7435fa5ca87d/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nSharpen your skills.\n[Soner Yıldırım](https://towardsdatascience.com/author/sonery/)\nAugust 27, 20203 min read\n  * [![](../images/005.jpeg)](https://towardsdatascience.com/why-you-dont-actually-need-a-reverse-etl-platform-bee9366b5ecb/)\n## [Why you don't actually need a reverse ETL platform](https://towardsdatascience.com/why-you-dont-actually-need-a-reverse-etl-platform-bee9366b5ecb/)\n[Data Engineering](https://towardsdatascience.com/category/data-science/data-engineering/)\nYou just need one, robust data pipeline system\n[Olivia Iannone](https://towardsdatascience.com/author/olivia_iannone/)\nApril 27, 20229 min read\n  * [![](../images/006.jpg)](https://towardsdatascience.com/document-intelligence-a-series-on-building-rag-brick-by-brick-from-minimal-to-corpus-scale/)\n## [Enterprise Document Intelligence: A Series on Building RAG Brick by Brick, from Minimal to Corpus scale](https://towardsdatascience.com/document-intelligence-a-series-on-building-rag-brick-by-brick-from-minimal-to-corpus-scale/)\n[Large Language Models](https://towardsdatascience.com/category/artificial-intelligence/large-language-models/)\nFor AI engineers who want to understand every step, not just call the library\n[Angela and Kezhan Shi](https://towardsdatascience.com/author/angela.shi/)\nMay 22, 202622 min read\n  * [![](../images/007.jpg)](https://towardsdatascience.com/aws-lambda-as-a-link-between-sqs-and-kinesis-a39cb6e4f762/)\n## [AWS Lambda as a link between SQS and Kinesis](https://towardsdatascience.com/aws-lambda-as-a-link-between-sqs-and-kinesis-a39cb6e4f762/)\n[Data Engineering](https://towardsdatascience.com/category/data-science/data-engineering/)\nUsing Lambda as a bridge to enable data flow from SQS queue in Account X to Kinesis Data Stream in Account Y\n[Shreyas Mondikal Subramanya](https://towardsdatascience.com/author/shreyas-ms/)\nApril 12, 20215 min read\n  * [![](../images/008.jpg)](https://towardsdatascience.com/doing-almost-as-much-with-much-less-a-case-study-in-biomedical-named-entity-recognition-efa4abe18ed/)\n## [Doing almost as much with much less: A Case Study in Biomedical Named Entity Recognition](https://towardsdatascience.com/doing-almost-as-much-with-much-less-a-case-study-in-biomedical-named-entity-recognition-efa4abe18ed/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nThoughts and Theory Can a simple string-matching method compete against a big supervised model? At...\n[Stephan Tulkens](https://towardsdatascience.com/author/stephantul/)\nMay 27, 202112 min read\n  * [![](../images/009.png)](https://towardsdatascience.com/intro-to-gaussian-process-regression-14f7c647d74d/)\n## [Intro to Gaussian Process Regression](https://towardsdatascience.com/intro-to-gaussian-process-regression-14f7c647d74d/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nA conceptual guide\n[Alex Powell](https://towardsdatascience.com/author/a-pow/)\nJanuary 6, 20214 min read\n  * [![](../images/010.png)](https://towardsdatascience.com/infiniband-vs-rocev2-choosing-the-right-network-for-large-scale-ai/)\n## [InfiniBand vs RoCEv2: Choosing the Right Network for Large-Scale AI](https://towardsdatascience.com/infiniband-vs-rocev2-choosing-the-right-network-for-large-scale-ai/)\n[Large Data Models](https://towardsdatascience.com/category/artificial-intelligence/large-data-models/)\nLearn how InfiniBand and RoCEv2 enable high-speed GPU communication\n[Shireesh Kumar Singh](https://towardsdatascience.com/author/shireeshkumar.singh/)\nAugust 6, 20257 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500) Productivity Tips, Data Career Insights, and Other Recent Must-Reads ](https://towardsdatascience.com/productivity-tips-data-career-insights-and-other-recent-must-reads-5c47eb7a2fe0/ \"Productivity Tips, Data Career Insights, and Other Recent Must-Reads\")\n\n\n",
  "metadata": {
    "title": "Optimizing Data Transfer in Batched AI/ML Inference Workloads | Towards Data Science",
    "description": "A deep dive on data transfer bottlenecks, their identification, and their resolution with the help of NVIDIA Nsight™ Systems - part 2",
    "keywords": null,
    "author": "Chaim Rand",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "Optimizing Data Transfer in Batched AI/ML Inference Workloads",
    "og:description": "A deep dive on data transfer bottlenecks, their identification, and their resolution with the help of NVIDIA Nsight™ Systems - part 2",
    "og:url": "https://towardsdatascience.com/optimizing-data-transfer-in-batched-ai-ml-inference-workloads/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2026/01/1-5.jpeg",
    "og:image:width": "1100",
    "og:image:height": "733",
    "og:image:type": "image/jpeg",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Chaim Rand",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "12 min read",
    "article:published_time": "2026-01-12T07:00:07.000Z",
    "article:modified_time": "2026-01-12T07:00:07.000Z",
    "article:author": "https://towardsdatascience.com/author/chaimrand/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 202,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/e04716433f71/code/block_000.txt",
      "chars": 2826
    },
    {
      "language": "txt",
      "file": "attachments/e04716433f71/code/block_001.txt",
      "chars": 124
    },
    {
      "language": "txt",
      "file": "attachments/e04716433f71/code/block_002.txt",
      "chars": 1640
    },
    {
      "language": "txt",
      "file": "attachments/e04716433f71/code/block_003.txt",
      "chars": 1674
    },
    {
      "language": "txt",
      "file": "attachments/e04716433f71/code/block_004.txt",
      "chars": 164
    },
    {
      "language": "txt",
      "file": "attachments/e04716433f71/code/block_005.txt",
      "chars": 169
    },
    {
      "language": "txt",
      "file": "attachments/e04716433f71/code/block_006.txt",
      "chars": 551
    },
    {
      "language": "txt",
      "file": "attachments/e04716433f71/code/block_007.txt",
      "chars": 1192
    },
    {
      "language": "txt",
      "file": "attachments/e04716433f71/code/block_008.txt",
      "chars": 1295
    }
  ],
  "images": [
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:52:53Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:52:53Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:52:53Z"
    },
    {
      "status": "http_404",
      "url": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500",
      "src": "https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500",
      "alt": "",
      "downloaded": false,
      "discovery": "saved_markdown",
      "retried_at": "2026-10-20T17:52:53Z"
    }
  ],
  "audio": [],
  "videos": [
    {
      "url": "https://www.youtube.com/c/TowardsDataScience",
      "kind": "channel_reference",
      "status": "reference_only"
    }
  ],
  "links": [
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/latest/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/editors-pick/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/the-variable/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/shipai/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/submissions/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/data-science/data-engineering/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/chaimrand/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/optimizing-data-transfer-in-ai-ml-workloads/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/deep-dives/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/artificial-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/machine-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/model-optimization/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/pytorch/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/run-airbyte-syncs-on-a-custom-schedule-with-crontab-and-http-requests-8d6fbb3ea112/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/programming/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/isaacharrisholt/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/ai-is-not-a-black-box/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/piotrm_69949/"
    },
    {
      "type": "external",
      "href": "https://write.insightmediagroup.io"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/company/towards-data-science/"
    },
    {
      "type": "external",
      "href": "https://x.com/TDataScience"
    },
    {
      "type": "external",
      "href": "https://unsplash.com/photos/landscape-photography-of-snowy-mountain-and-body-of-water-efuwb5eBDrI"
    },
    {
      "type": "external",
      "href": "https://docs.nvidia.com/nsight-systems/index.html"
    },
    {
      "type": "external",
      "href": "https://en.wikipedia.org/wiki/Vector_database"
    },
    {
      "type": "external",
      "href": "https://docs.pytorch.org/tutorials/recipes/recipes/tuning_guide.html"
    },
    {
      "type": "external",
      "href": "https://aws.amazon.com/ec2/instance-types/g6e/"
    },
    {
      "type": "external",
      "href": "https://www.nvidia.com/en-eu/data-center/l40s/"
    },
    {
      "type": "external",
      "href": "https://docs.aws.amazon.com/dlami/latest/devguide/appendix-ami-release-notes.html"
    },
    {
      "type": "external",
      "href": "https://pytorch.org/get-started/locally/"
    },
    {
      "type": "external",
      "href": "https://developer.nvidia.com/nsight-systems/get-started"
    },
    {
      "type": "external",
      "href": "https://docs.nvidia.com/tools-extension/index.html"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/data-engineer"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/in/yitzhak-levi-49a217201/"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/in/gilad-wasserman-992530268/?originalSubdomain=il"
    },
    {
      "type": "external",
      "href": "https://docs.pytorch.org/vision/main/models/deeplabv3.html"
    },
    {
      "type": "external",
      "href": "https://docs.pytorch.org/vision/main/models/generated/torchvision.models.resnet50.html"
    },
    {
      "type": "external",
      "href": "https://nvtx.readthedocs.io/en/latest/index.html"
    },
    {
      "type": "external",
      "href": "https://docs.pytorch.org/docs/stable/data.html"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:27:48Z",
  "source_url": "https://towardsdatascience.com/optimizing-data-transfer-in-batched-ai-ml-inference-workloads/",
  "delivery_status": "unverified",
  "discovery_status": "http_403",
  "missing_reason": "源页面未重新核验:http_403；已按保留正文补采图片",
  "repair_error": "",
  "actual_video_files": [],
  "expected_saved_body_images": 4,
  "image_discovery": "saved_markdown",
  "source_body_markdown": "![Revisit consent button](https://cdn-cookieyes.com/assets/images/revisit.svg)\nWe value your privacy\nWe use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking \"Accept All\", you consent to our use of cookies.\nCustomise Reject All Accept All\nCustomise Consent Preferences ![](https://cdn-cookieyes.com/assets/images/close.svg)\nWe use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.\nThe cookies that are categorised as \"Necessary\" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more\nNecessaryAlways Active\nNecessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.\n  * Cookie\nBCTempID\n  * Duration\n10 minutes\n  * Description\nNo description available.\n\n\n  * Cookie\n__cf_bm\n  * Duration\n1 hour\n  * Description\nThis cookie, set by Cloudflare, is used to support Cloudflare Bot Management. \n\n\n  * Cookie\nAWSALBCORS\n  * Duration\n7 days\n  * Description\nAmazon Web Services set this cookie for load balancing.\n\n\n  * Cookie\n_cfuvid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services\n\n\n  * Cookie\nli_gc\n  * Duration\n6 months\n  * Description\nLinkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.\n\n\n  * Cookie\n__hssrc\n  * Duration\nsession\n  * Description\nThis cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.\n\n\n  * Cookie\n__hssc\n  * Duration\n1 hour\n  * Description\nHubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.\n\n\n  * Cookie\nwpEmojiSettingsSupports\n  * Duration\nsession\n  * Description\nWordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.\n\n\n  * Cookie\nBCSessionID\n  * Duration\n1 year 1 month 4 days\n  * Description\nBlueconic sets this cookie as a unique identifier for the BlueConic profile.\n\n\n  * Cookie\n_octo\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nlogged_in\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\n__Secure-YEC\n  * Duration\npast\n  * Description\nYouTube sets this cookie to stores the user's video player preferences using embedded YouTube video\n\n\n  * Cookie\n__eoi\n  * Duration\n6 months\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTGCORS\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\nlogin-status-p\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nAWSALBTG\n  * Duration\n7 days\n  * Description\nNo description available.\n\n\n  * Cookie\ncsrf_token\n  * Duration\nsession\n  * Description\nNo description available.\n\n\n  * Cookie\ntoken_v2\n  * Duration\n1 day\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nD\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nPHPSESSID\n  * Duration\nsession\n  * Description\nThis cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.\n\n\n  * Cookie\nVISITOR_PRIVACY_METADATA\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to store the user's cookie consent state for the current domain. \n\n\n  * Cookie\ncookietest\n  * Duration\nsession\n  * Description\nThe cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.\n\n\n  * Cookie\n__Host-airtable-session\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\n__Host-airtable-session.sig\n  * Duration\n1 year\n  * Description\nThis cookie is used to enable us to integrate the services of Airtable.\n\n\n  * Cookie\nm\n  * Duration\n1 year 1 month 4 days\n  * Description\nStripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.\n\n\n  * Cookie\nBIGipServer*\n  * Duration\nsession\n  * Description\nMarketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. \n\n\n  * Cookie\n__cfruid\n  * Duration\nsession\n  * Description\nCloudflare sets this cookie to identify trusted web traffic.\n\n\n  * Cookie\n_GRECAPTCHA\n  * Duration\n6 months\n  * Description\nGoogle Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.\n\n\n  * Cookie\n__Secure-YNID\n  * Duration\n6 months\n  * Description\nGoogle cookie used to protect user security and prevent fraud, especially during the login process.\n\n\n  * Cookie\ncookieyes-consent\n  * Duration\n1 year\n  * Description\nCookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.\n\n\nFunctional\nFunctional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.\n  * Cookie\nlidc\n  * Duration\n1 day\n  * Description\nLinkedIn sets the lidc cookie to facilitate data center selection.\n\n\n  * Cookie\nbrw\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nbrwConsent\n  * Duration\n5 minutes\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nWMF-Uniq\n  * Duration\n1 year\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nloom_anon_comment\n  * Duration\n1 year\n  * Description\nNo description available.\n\n\n  * Cookie\nloom_referral_video\n  * Duration\nsession\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nVISITOR_INFO1_LIVE\n  * Duration\n6 months\n  * Description\nA cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.\n\n\n  * Cookie\nyt-remote-connected-devices\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nytidb::LAST_RESULT_ENTRY_KEY\n  * Duration\nNever Expires\n  * Description\nThe cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.\n\n\n  * Cookie\nyt-remote-device-id\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to store the user's video preferences using embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-name\n  * Duration\nsession\n  * Description\nThe yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\nyt-remote-fast-check-period\n  * Duration\nsession\n  * Description\nThe yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.\n\n\n  * Cookie\nyt-remote-session-app\n  * Duration\nsession\n  * Description\nThe yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-available\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.\n\n\n  * Cookie\nyt-remote-cast-installed\n  * Duration\nsession\n  * Description\nThe yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.\n\n\n  * Cookie\ncp_session\n  * Duration\n3 months\n  * Description\nCodepen sets this cookie for Help systems found in the website.\n\n\n  * Cookie\nloid\n  * Duration\n1 year 1 month 4 days\n  * Description\nThis cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.\n\n\nAnalytics\nAnalytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.\n  * Cookie\n__hstc\n  * Duration\n6 months\n  * Description\nHubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).\n\n\n  * Cookie\nhubspotutk\n  * Duration\n6 months\n  * Description\nHubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.\n\n\n  * Cookie\n_ga\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.\n\n\n  * Cookie\n_ga_*\n  * Duration\n1 year 1 month 4 days\n  * Description\nGoogle Analytics sets this cookie to store and count page views.\n\n\n  * Cookie\n__Host-psifi.analyticsTrace\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n__Host-psifi.analyticsTraceV2\n  * Duration\n6 hours\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\n_gh_sess\n  * Duration\nsession\n  * Description\nGitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.\n\n\n  * Cookie\nYSC\n  * Duration\nsession\n  * Description\nYSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.\n\n\n  * Cookie\najs_anonymous_id\n  * Duration\n1 year\n  * Description\nThis cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.\n\n\n  * Cookie\nvuid\n  * Duration\n1 year 1 month 4 days\n  * Description\nVimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. \n\n\nPerformance\nPerformance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.\n  * Cookie\nAWSALB\n  * Duration\n7 days\n  * Description\nAWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.\n\n\n  * Cookie\nacq\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nacq.sig\n  * Duration\npast\n  * Description\nDescription is currently not available.\n\n\n  * Cookie\nptc\n  * Duration\n2 years\n  * Description\nNo description available.\n\n\nAdvertisement\nAdvertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.\n  * Cookie\nmuc_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to collect user behaviour and interaction data to optimize the website.\n\n\n  * Cookie\nguest_id_marketing\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\nguest_id_ads\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor.\n\n\n  * Cookie\npersonalization_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.\n\n\n  * Cookie\nguest_id\n  * Duration\n1 year 1 month 4 days\n  * Description\nTwitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.\n\n\n  * Cookie\nbcookie\n  * Duration\n1 year\n  * Description\nLinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.\n\n\n  * Cookie\n__Secure-ROLLOUT_TOKEN\n  * Duration\n6 months\n  * Description\nYouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.\n\n\n  * Cookie\nyt.innertube::nextId\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nyt.innertube::requests\n  * Duration\nNever Expires\n  * Description\nYouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.\n\n\n  * Cookie\nsession_tracker\n  * Duration\nsession\n  * Description\nThis cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.\n\n\n  * Cookie\nedgebucket\n  * Duration\nsession\n  * Description\nReddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.\n\n\n  * Cookie\ndid\n  * Duration\n1 year\n  * Description\nArbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.\n\n\nUncategorised\nOther uncategorised cookies are those that are being analysed and have not been classified into a category as yet.\nNo cookies to display.\nReject All Save My Preferences Accept All\nToggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation\n[](https://towardsdatascience.com/)\nPublish AI, ML & data-science insights to a global community of data professionals.\nSign in[Submit an Article](https://write.insightmediagroup.io)\n[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)\n* * *\n[Write For TDS](https://towardsdatascience.com/submissions/)\n[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search\n[Data Engineering](https://towardsdatascience.com/category/data-science/data-engineering/)\n# Optimizing Data Transfer in Batched AI/ML Inference Workloads\nA deep dive on data transfer bottlenecks, their identification, and their resolution with the help of NVIDIA Nsight™ Systems - part 2\n[Chaim Rand](https://towardsdatascience.com/author/chaimrand/)\nJanuary 12, 202612 min read\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/01/1-5.jpeg)\n[Photo](https://unsplash.com/photos/landscape-photography-of-snowy-mountain-and-body-of-water-efuwb5eBDrI) by Joel & Jasmin Førestbird on Unsplash\nThis is a sequel post to [Optimizing Data Transfer in AI/ML Workloads](https://towardsdatascience.com/optimizing-data-transfer-in-ai-ml-workloads/) where we demonstrated the use of [NVIDIA Nsight™ Systems (nsys)](https://docs.nvidia.com/nsight-systems/index.html) in studying and solving the common data-loading bottleneck — occurrences where the GPU idles while it waits for input data from the CPU. In this post we focus our attention on data travelling in the opposite direction, from the GPU device to the CPU host. More specifically, we address AI/ML inference workloads where the size of the output being returned by the model is relatively high. Common examples include: 1) running a scene segmentation (per-pixel labeling) model on batches of high-resolution images and 2) capturing high dimensional feature embeddings of input sequences using an encoder model (e.g., to create a [vector database](https://en.wikipedia.org/wiki/Vector_database)). Both examples involve executing a model on an input batch and then copying the output tensor from the GPU to the CPU for additional processing, storage, and/or over-the-network communication.\nGPU-to-CPU memory copies of the model output typically receive much less attention in optimization tutorials than the CPU-to-GPU copies that feed the model (e.g., see [here](https://docs.pytorch.org/tutorials/recipes/recipes/tuning_guide.html)). But their potential impact on model efficiency and execution costs can be just as detrimental. Moreover, while optimizations to CPU-to-GPU data-loading are well documented and easy to implement, optimizing data copy in the opposite direction requires a bit more manual labor.\nIn this post we will apply the same strategy we used in our previous post: We will define a toy model and use nsys profiler to identify and solve performance bottlenecks. We will run our experiments on an [Amazon EC2 g6e.2xlarge](https://aws.amazon.com/ec2/instance-types/g6e/) instance (with an [NVIDIA L40S](https://www.nvidia.com/en-eu/data-center/l40s/) GPU) running an [AWS Deep Learning (Ubuntu 24.04) AMI](https://docs.aws.amazon.com/dlami/latest/devguide/appendix-ami-release-notes.html) with [PyTorch (2.8)](https://pytorch.org/get-started/locally/), [nsys-cli profiler](https://developer.nvidia.com/nsight-systems/get-started) (version 2025.6.1), and the [NVIDIA Tools Extension](https://docs.nvidia.com/tools-extension/index.html) (NVTX) library.\nLearn this step by step with the interactive [Data Engineer](https://roadmap.sh/data-engineer) roadmap.\n#### Disclaimers\nThe code we will share is intended for demonstrative purposes; please do not rely on its correctness or optimality. Please do not interpret our use of any library, tool, or platform, as an endorsement of its use. The impact of the optimizations we will cover can vary greatly based on the details of the model and the runtime environment. Please be sure to assess their effect on your own use case before integrating their use.\nMany thanks to [Yitzhak Levi](https://www.linkedin.com/in/yitzhak-levi-49a217201/) and [Gilad Wasserman](https://www.linkedin.com/in/gilad-wasserman-992530268/?originalSubdomain=il) for their contributions to this post.\n### A Toy PyTorch Model\nWe introduce a batched inference script that performs image segmentation on a synthetic dataset using a [DeepLabV3](https://docs.pytorch.org/vision/main/models/deeplabv3.html) model with a [ResNet-50](https://docs.pytorch.org/vision/main/models/generated/torchvision.models.resnet50.html#torchvision.models.resnet50) backbone. The model outputs are copied to the CPU for post processing and storage. We wrap the different portions of the inference step with color-coded [nvtx](https://nvtx.readthedocs.io/en/latest/index.html) annotations:\npython\n\n```\nimport time, torch, nvtx\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.cuda import profiler\nfrom torchvision.models.segmentation import deeplabv3_resnet50\n\nDEVICE = \"cuda\"\nWARMUP_STEPS = 10\nPROFILE_STEPS = 3\nCOOLDOWN_STEPS = 1\nTOTAL_STEPS = WARMUP_STEPS + PROFILE_STEPS + COOLDOWN_STEPS\nBATCH_SIZE = 64\nTOTAL_SAMPLES = TOTAL_STEPS * BATCH_SIZE\nIMG_SIZE = 512\nN_CLASSES = 21\nNUM_WORKERS = 8\nASYNC_DATALOAD = True\n\n\n# A synthetic Dataset with random images\nclass FakeDataset(Dataset):\n\n    def __len__(self):\n        return TOTAL_SAMPLES\n\n    def __getitem__(self, index):\n        img = torch.randn((3, IMG_SIZE, IMG_SIZE))\n        return img\n\n# utility class for prefetching data to GPU\nclass DataPrefetcher:\n    def __init__(self, loader):\n        self.loader = iter(loader)\n        self.stream = torch.cuda.Stream()\n        self.next_batch = None\n        self.preload()\n\n    def preload(self):\n        try:\n            data = next(self.loader)\n            with torch.cuda.stream(self.stream):\n                next_data = data.to(DEVICE, non_blocking=ASYNC_DATALOAD)\n            self.next_batch = next_data\n        except:\n            self.next_batch = None\n\n    def __iter__(self):\n        return self\n\n    def __next__(self):\n        torch.cuda.current_stream().wait_stream(self.stream)\n        data = self.next_batch\n        self.preload()\n        return data\n\nmodel = deeplabv3_resnet50(weights_backbone=None).to(DEVICE).eval()\n\ndata_loader = DataLoader(\n    FakeDataset(),\n    batch_size=BATCH_SIZE,\n    num_workers=NUM_WORKERS,\n    pin_memory=ASYNC_DATALOAD\n)\n\ndata_iter = DataPrefetcher(data_loader)\n\ndef synchronize_all():\n    torch.cuda.synchronize() \n\ndef to_cpu(output):\n    return output.cpu()\n\ndef process_output(batch_id, logits):\n    # do some post processing on output\n    with open('/dev/null', 'wb') as f:\n        f.write(logits.numpy().tobytes())\n\nwith torch.inference_mode():\n    for i in range(TOTAL_STEPS):\n        if i == WARMUP_STEPS:\n            synchronize_all()\n            start_time = time.perf_counter()\n            profiler.start()\n        elif i == WARMUP_STEPS + PROFILE_STEPS:\n            synchronize_all()\n            profiler.stop()\n            end_time = time.perf_counter()\n\n        with nvtx.annotate(f\"Batch {i}\", color=\"blue\"):\n            with nvtx.annotate(\"get batch\", color=\"red\"):\n                batch = next(data_iter)\n            with nvtx.annotate(\"compute\", color=\"green\"):\n                output = model(batch)\n            with nvtx.annotate(\"copy to CPU\", color=\"yellow\"):\n                output_cpu = to_cpu(output['out'])\n            with nvtx.annotate(\"process output\", color=\"cyan\"):\n                process_output(i, output_cpu)\n\ntotal_time = end_time - start_time\nthroughput = PROFILE_STEPS / total_time\nprint(f\"Throughput: {throughput:.2f} steps/sec\")\n```\n\nNote the inclusion of all of the CPU-to-GPU data-loading optimizations discussed in our previous post.\nWe run the following command to capture an nsys profile trace:\nbash\n\n```\nnsys profile \\\n  --capture-range=cudaProfilerApi \\\n  --trace=cuda,nvtx,osrt \\\n  --output=baseline \\\n  python batch_infer.py\n```\n\nThis results in a  _baseline.nsys-rep_ trace file that we copy over to our development machine for analysis.\nTo measure the inference throughput, we increase the number of steps to 100. The average throughput of our baseline experiment is 0.45 steps-per-second. In the following sections we will use the nsys profile traces to incrementally improve this result.\n#### Baseline Performance Analysis\nThe image below shows the nsys profile trace of our baseline experiment:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/01/2-1024x183.webp)\nBaseline Nsight Systems Profiler Trace (by Author)\nIn the GPU section we see the following recurring pattern:\n  1. A block of kernel compute (in light blue) that runs for ~520 milliseconds.\n  2. A small block of host-to-device memory copy (in green) that runs in parallel to the kernel compute. This concurrency was achieved using the optimizations discussed in our previous post.\n  3. A block of device-to-host memory copy (in red) that runs for ~750 milliseconds.\n  4. A long period (~940 milliseconds) of GPU idle time (white space) between every two steps.\n\n\nLooking at the NVTX bar of the CPU section, we can see that the whitespace aligns perfectly with the “process output” block (in cyan). In our initial implementation, both the model execution and the output storage function run in the same single process in a sequential manner. This leads to significant idle time on the GPU as the CPU waits for the storage function to return before feeding the GPU the next batch.\n### Optimization 1: Multi-Worker Output Processing\nThe first step we take is to run the output storage function in parallel worker processes. We took a similar step in our previous post when we moved the input batch preparation sequence to dedicated workers. However, whereas there we were able to automate [multi-process data loading](https://docs.pytorch.org/docs/stable/data.html#multi-process-data-loading) by simply setting the  _num_workers_ argument of the [DataLoader](https://docs.pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader) class to a non-zero value, applying multi-worker output-processing requires a manual implementation. Here we choose a simple solution for demonstrative purposes. This should be customized per your needs and design preferences.\n#### PyTorch Multiprocessing\nWe implement a producer-consumer strategy using PyTorch’s built-in multiprocessing package, [torch.multiprocessing](https://docs.pytorch.org/docs/stable/multiprocessing.html). We define a queue for storing output batches and multiple consumer workers that process the batches on the queue. We modify our inference loop to put the output buffers in the output queue. We also update the  _synchronize_all()_ utility to drain the queue and append a cleanup sequence at the end of the script.\nThe following block of code contains our initial implementation. As we will see in the next sections, this will require some tuning in order to reach maximum performance.\npython\n\n```\nimport torch.multiprocessing as mp\n\nPOSTPROC_WORKERS = 8 # tune for optimal throughput\n\noutput_queue = mp.JoinableQueue(maxsize=POSTPROC_WORKERS)\n\ndef output_worker(in_q):\n    while True:\n        item = in_q.get()\n        if item is None: break  # signal to shut down\n        batch_id, batch_preds = item\n        process_output(batch_id, batch_preds)\n        in_q.task_done()\n\nprocesses = []\nfor _ in range(POSTPROC_WORKERS):\n    p = mp.Process(target=output_worker, args=(output_queue,))\n    p.start()\n    processes.append(p)\n\ndef synchronize_all():\n    torch.cuda.synchronize() \n    output_queue.join() # drain queue\n\n\nwith torch.inference_mode():\n    for i in range(TOTAL_STEPS):\n        if i == WARMUP_STEPS:\n            synchronize_all()\n            start_time = time.perf_counter()\n            profiler.start()\n        elif i == WARMUP_STEPS + PROFILE_STEPS:\n            synchronize_all()\n            profiler.stop()\n            end_time = time.perf_counter()\n\n        with nvtx.annotate(f\"Batch {i}\", color=\"blue\"):\n            with nvtx.annotate(\"get batch\", color=\"red\"):\n                batch = next(data_iter)\n            with nvtx.annotate(\"compute\", color=\"green\"):\n                output = model(batch)\n            with nvtx.annotate(\"copy to CPU\", color=\"yellow\"):\n                output_cpu = to_cpu(output['out'])\n            with nvtx.annotate(\"queue output\", color=\"cyan\"):\n                output_queue.put((i, output_cpu))\n\n\ntotal_time = end_time - start_time\nthroughput = PROFILE_STEPS / total_time\nprint(f\"Throughput: {throughput:.2f} steps/sec\")\n# cleanup\nfor _ in range(POSTPROC_WORKERS):\n    output_queue.put(None)\n```\n\nThe multi-worker output processing optimization results in a throughput of 0.71 steps-per-second — a 58% increase over our baseline results.\nRerunning the nsys command results in the following profile trace:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/01/3-1024x230.webp)\nMulti-Worker Nsight Systems Profiler Timeline (by Author)\nWe can see that the size of the block of whitespace has dropped considerably (from ~940 milliseconds to ~50). Were we to zoom in on the remaining whitespace, we would find it aligned to an “munmap” operation. In our previous post, the same finding informed our asynchronous data copy optimization. But this time we take an intermediate memory-optimization step in the form of a pre-allocated pool of buffers.\n### Optimization 2: Buffer Pool Pre-allocation\nIn order to reduce the overhead of allocating and managing a new CPU tensor on every iteration, we initialize a pool of tensors pre-allocated in shared memory and define a second queue to manage their use.\nOur updated code appears below:\npython\n\n```\nshape = (BATCH_SIZE, N_CLASSES, IMG_SIZE, IMG_SIZE)\nbuffer_pool = [torch.empty(shape).share_memory_() \n               for _ in range(POSTPROC_WORKERS)]\n\nbuf_queue = mp.Queue()\nfor i in range(POSTPROC_WORKERS):\n    buf_queue.put(i)\n\ndef output_worker(buffer_pool, in_q, buf_q):\n    while True:\n        item = in_q.get()\n        if item is None: break  # signal to shut down\n        batch_id, buf_id = item\n        process_output(batch_id, buffer_pool[buf_id])\n        buf_q.put(buf_id)\n        in_q.task_done()\n\nprocesses = []\nfor _ in range(POSTPROC_WORKERS):\n    p = mp.Process(target=output_worker,\n                   args=(buffer_pool,output_queue,buf_queue))\n    p.start()\n    processes.append(p)\n\ndef to_cpu(output):\n    buf_id = buf_queue.get()\n    output_cpu = buffer_pool[buf_id]\n    output_cpu.copy_(output)\n    return output_cpu, buf_id\n\nwith torch.inference_mode():\n    for i in range(TOTAL_STEPS):\n        if i == WARMUP_STEPS:\n            synchronize_all()\n            start_time = time.perf_counter()\n            profiler.start()\n        elif i == WARMUP_STEPS + PROFILE_STEPS:\n            synchronize_all()\n            profiler.stop()\n            end_time = time.perf_counter()\n\n        with nvtx.annotate(f\"Batch {i}\", color=\"blue\"):\n            with nvtx.annotate(\"get batch\", color=\"red\"):\n                batch = next(data_iter)\n            with nvtx.annotate(\"compute\", color=\"green\"):\n                output = model(batch)\n            with nvtx.annotate(\"copy to CPU\", color=\"yellow\"):\n                output_cpu, buf_id = to_cpu(output['out'])\n            with nvtx.annotate(\"queue output\", color=\"cyan\"):\n                output_queue.put((i, buf_id))\n```\n\nFollowing these changes, the inference throughput jumps to 1.51 — a more than 2 _X_ speed-up over our previous result.\nThe new profile trace appears below:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/01/4-1024x191.webp)\nBuffer Pool Nsight Systems Profiler Timeline (by Author)\nNot only has the whitespace all but disappeared, but the CUDA DtoH memory operation (in red) has dropped from ~750 milliseconds to ~110. Presumably, the large GPU-to-CPU data copy involved quite a bit of memory-management overhead that we have removed by implementing a dedicated buffer pool.\nDespite the considerable improvement, if we zoom in we will find that there remains around ~0.5 milliseconds of whitespace that is caused by the synchronicity of the GPU-to-CPU copy command — so long as the copy has not completed the CPU does not trigger the kernel computation of the next batch.\n### Optimization 3: Asynchronous Data Copy\nOur third optimization is to change the device-to-host copy to be asynchronous. As before, we will find that implementing this change is more difficult than in the CPU-to-GPU direction.\nThe first step is to pass `non_blocking=True` to the GPU-to-CPU copy command.\npython\n\n```\ndef to_cpu(output):\n    buf_id = buf_queue.get()\n    output_cpu = buffer_pool[buf_id]\n    output_cpu.copy_(output, non_blocking=True)\n    return output_cpu, buf_id\n```\n\nHowever, as we saw in our previous post, this change will not have a meaningful impact unless we modify our tensors to use pinned memory:\npython\n\n```\nshape = (BATCH_SIZE, N_CLASSES, IMG_SIZE, IMG_SIZE)\nbuffer_pool = [torch.empty(shape, pin_memory=True).share_memory_() \n               for _ in range(POSTPROC_WORKERS)]\n```\n\nCrucially, if we apply only these two changes to our script, the throughput would increase but the output may be corrupted (e.g., see [here](https://docs.pytorch.org/tutorials/intermediate/pinmem_nonblock.html#other-copy-directions-gpu-cpu-cpu-mps)). We need an event-based mechanism for identifying each time a GPU-to-CPU copy has been completed so that we can proceed with the output data processing. (Note, that this was not required when making the CPU-to-GPU copy asynchronous. Because a single GPU stream processes commands sequentially, the kernel computation only starts when the copy has completed. Synchronization was only required when introducing a second stream.)\nTo implement the notification mechanism, we define a pool of CUDA events and an additional queue for managing their use. We further define a listener thread for monitoring the state of events on the queue and populating the output queue once the copies are complete.\npython\n\n```\nimport threading, queue\n\nevent_pool = [torch.cuda.Event() for _ in range(POSTPROC_WORKERS)]\nevent_queue = queue.Queue()\n\ndef event_monitor(event_pool, event_queue, output_queue):\n    while True:\n        item = event_queue.get()\n        if item is None: break\n        batch_id, buf_idx = item\n        event_pool[buf_idx].synchronize()\n        output_queue.put((batch_id, buf_idx))\n        event_queue.task_done()\n\nmonitor = threading.Thread(target=event_monitor,\n                           args=(event_pool, event_queue, output_queue))\nmonitor.start()\n```\n\nThe updated inference sequence consists of the following steps:\n  1. Get an input batch that was prefetched to the GPU.\n  2. Execute the model on the input batch to get an output tensor on the GPU.\n  3. Request a vacant CPU buffer from the buffer queue and use it to trigger an asynchronous data copy. Configure an event to trigger when the copy is complete and push the event to the event-queue.\n  4. The monitor thread waits for the event to trigger and then pushes the output tensor to the output queue for processing.\n  5. A worker thread pulls the output tensor from the queue and saves it to disk. It then releases the buffer back to the buffer queue.\n\n\nThe updated code appears below.\npython\n\n```\ndef synchronize_all():\n    torch.cuda.synchronize()\n    event_queue.join()\n    output_queue.join()\n\n\nwith torch.inference_mode():\n    for i in range(TOTAL_STEPS):\n        if i == WARMUP_STEPS:\n            synchronize_all()\n            start_time = time.perf_counter()\n            profiler.start()\n        elif i == WARMUP_STEPS + PROFILE_STEPS:\n            synchronize_all()\n            profiler.stop()\n            end_time = time.perf_counter()\n\n        with nvtx.annotate(f\"Batch {i}\", color=\"blue\"):\n            with nvtx.annotate(\"get batch\", color=\"red\"):\n                batch = next(data_iter)\n            with nvtx.annotate(\"compute\", color=\"green\"):\n                output = model(batch)\n            with nvtx.annotate(\"copy to CPU\", color=\"yellow\"):\n                output_cpu, buf_id = to_cpu(output['out'])\n            with nvtx.annotate(\"queue CUDA event\", color=\"cyan\"):\n                event_pool[buf_id].record()\n                event_queue.put((i, buf_id))\n\ntotal_time = end_time - start_time\nthroughput = PROFILE_STEPS / total_time\nprint(f\"Throughput: {throughput:.2f} steps/sec\")\n# cleanup\nevent_queue.put(None)\nfor _ in range(POSTPROC_WORKERS):\n    output_queue.put(None)\n```\n\nThe resultant throughput is 1.55 steps-per-second.\nThe new profile trace appears below:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/01/5-1024x248.webp)\nAsync Data Transfer Nsight Systems Profiler Timeline (by Author)\nIn the NVTX row of the CPU section we can see all of the operations in the inference loop bunched together on left side — implying that they all ran immediately and asynchronously. We also see the event synchronization calls (in light green) running on the dedicated monitor thread. In the GPU section we see that the kernel computation begins immediately after the device-to-host copy has completed.\nOur final optimization will focus on improving the parallelization of the kernel and memory operations on the GPU.\n### Optimization 4: Pipelining Using CUDA Streams\nAs in our previous post, we wish to take advantage of the independent engines for memory copying (the DMA) and kernel compute (the SMs). We do this by assigning the memory copy to a dedicated CUDA stream:\npython\n\n```\negress_stream = torch.cuda.Stream()\n\nwith torch.inference_mode():\n    for i in range(TOTAL_STEPS):\n        if i == WARMUP_STEPS:\n            synchronize_all()\n            start_time = time.perf_counter()\n            profiler.start()\n        elif i == WARMUP_STEPS + PROFILE_STEPS:\n            synchronize_all()\n            profiler.stop()\n            end_time = time.perf_counter()\n\n        with nvtx.annotate(f\"Batch {i}\", color=\"blue\"):\n            with nvtx.annotate(\"get batch\", color=\"red\"):\n                batch = next(data_iter)\n            with nvtx.annotate(\"compute\", color=\"green\"):\n                output = model(batch)\n            \n            # on separate stream\n            with torch.cuda.stream(egress_stream):\n                # wait for default stream to complete compute\n                egress_stream.wait_stream(torch.cuda.default_stream())\n                # Mark that egress_stream will use this tensor\n                output['out'].record_stream(egress_stream)\n                with nvtx.annotate(\"copy to CPU\", color=\"yellow\"):\n                    output_cpu, buf_id = to_cpu(output['out'])\n                with nvtx.annotate(\"queue CUDA event\", color=\"cyan\"):\n                    event_pool[buf_id].record(egress_stream)\n                    event_queue.put((i, buf_id))\n```\n\nThis results in a throughput of 1.85 steps per second — an additional 19.3% improvement over our previous experiment.\nThe final profile trace appears below:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/01/6-1024x241.webp)\nPipelined Nsight Systems Profiler Timeline (by Author)\nIn the GPU section we see a continuous block of kernel compute (in light blue) with both the host-to-device (in light green) and device-to-host (in purple) running in parallel. Our inference loop is now compute-bound, implying that we have exhausted all practical opportunities for data-transfer optimization.\n## Results\nWe summarize our results in the following table:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/01/7.webp)\nExperiment Results (by Author)\nThrough the use of nsys profiler we were able to increase efficiency by over 4 _X_. Naturally, the impact of the optimizations we discussed will vary based on the details of the model and runtime environment.\n## Summary\nThis concludes the second part of our series of posts on the topic of optimizing data-transfer in AI/ML workloads. Part one focused on host-to-device copies and part two on device-to-host copies. When implemented naively, data-transfer in either direction can lead to significant performance bottlenecks resulting in GPU starvation and increased runtime costs. Using Nsight Systems profiler, we demonstrated how to identify and resolve these bottlenecks and increase runtime efficiency.\nAlthough the optimization of both directions involved similar steps, the implementation details were very different. While optimizing CPU-to-GPU data-transfer is well-supported by PyTorch’s data-loading APIs and required relatively small changes to the execution loop, optimizing the the GPU-to-CPU direction required a bit more software engineering. Importantly, the solutions we put forth in this post were chosen for demonstrative purposes. Your own solution may differ considerably based on your project needs and design preferences.\nHaving covered both CPU-to-GPU and GPU-to-CPU data copies, we turn our attention to GPU-to-GPU transactions: Stay tuned for a future post on the topic of optimizing data transfer between GPUs in distributed training workloads.\n## Register Now to Continue Reading\n### Unlock Towards Data Science with a Free Account\nAll articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.\nRegister for freeSign in to your account\n* * *\n![](https://assets.insightmediagroup.io/media/1787657094227_7ymyo0.jpeg)\nWritten By\n## [Chaim Rand](https://towardsdatascience.com/author/chaimrand/)\n[See all from Chaim Rand](https://towardsdatascience.com/author/chaimrand/)\n[Deep Dives](https://towardsdatascience.com/tag/deep-dives/)[Artificial Intelligence](https://towardsdatascience.com/tag/artificial-intelligence/)[Machine Learning](https://towardsdatascience.com/tag/machine-learning/)[Model Optimization](https://towardsdatascience.com/tag/model-optimization/)[Pytorch](https://towardsdatascience.com/tag/pytorch/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Foptimizing-data-transfer-in-batched-ai-ml-inference-workloads%2F&title=Optimizing%20Data%20Transfer%20in%20Batched%20AI%2FML%20Inference%20Workloads)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Foptimizing-data-transfer-in-batched-ai-ml-inference-workloads%2F&title=Optimizing%20Data%20Transfer%20in%20Batched%20AI%2FML%20Inference%20Workloads)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Foptimizing-data-transfer-in-batched-ai-ml-inference-workloads%2F&text=Optimizing%20Data%20Transfer%20in%20Batched%20AI%2FML%20Inference%20Workloads)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/04/08M2_93JHmYYpC6qu-scaled.jpg)](https://towardsdatascience.com/run-airbyte-syncs-on-a-custom-schedule-with-crontab-and-http-requests-8d6fbb3ea112/)\n## [Run Airbyte Syncs On A Custom Schedule With Crontab And HTTP Requests](https://towardsdatascience.com/run-airbyte-syncs-on-a-custom-schedule-with-crontab-and-http-requests-8d6fbb3ea112/)\n[Programming](https://towardsdatascience.com/category/programming/)\nLeverage Airbyte's simple REST API for complex configuration\n[Isaac Harris-Holt](https://towardsdatascience.com/author/isaacharrisholt/)\nApril 23, 20224 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/06/gemma2.gif)](https://towardsdatascience.com/ai-is-not-a-black-box/)\n## [AI Is Not a Black Box (Relatively Speaking)](https://towardsdatascience.com/ai-is-not-a-black-box/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nCompared to the opacity around human intelligence, AI is more transparent in some very tangible ways.\n[Piotr Mardziel](https://towardsdatascience.com/author/piotrm_69949/)\nJune 13, 20256 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/08/1QfYDVCIebU0cH7n3CYzNXw.jpeg)](https://towardsdatascience.com/the-best-way-to-practice-data-science-tools-7435fa5ca87d/)\n## [The Best Way to Practice Data Science Tools](https://towardsdatascience.com/the-best-way-to-practice-data-science-tools-7435fa5ca87d/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nSharpen your skills.\n[Soner Yıldırım](https://towardsdatascience.com/author/sonery/)\nAugust 27, 20203 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/10/1sXmGY0qV1646EO8QxZewqQ-scaled.jpeg)](https://towardsdatascience.com/why-you-dont-actually-need-a-reverse-etl-platform-bee9366b5ecb/)\n## [Why you don't actually need a reverse ETL platform](https://towardsdatascience.com/why-you-dont-actually-need-a-reverse-etl-platform-bee9366b5ecb/)\n[Data Engineering](https://towardsdatascience.com/category/data-science/data-engineering/)\nYou just need one, robust data pipeline system\n[Olivia Iannone](https://towardsdatascience.com/author/olivia_iannone/)\nApril 27, 20229 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/05/enterprise_document_intelligence_rag_series_overview.jpg)](https://towardsdatascience.com/document-intelligence-a-series-on-building-rag-brick-by-brick-from-minimal-to-corpus-scale/)\n## [Enterprise Document Intelligence: A Series on Building RAG Brick by Brick, from Minimal to Corpus scale](https://towardsdatascience.com/document-intelligence-a-series-on-building-rag-brick-by-brick-from-minimal-to-corpus-scale/)\n[Large Language Models](https://towardsdatascience.com/category/artificial-intelligence/large-language-models/)\nFor AI engineers who want to understand every step, not just call the library\n[Angela and Kezhan Shi](https://towardsdatascience.com/author/angela.shi/)\nMay 22, 202622 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/04/0UhLA6hJQdCCuLej_-scaled.jpg)](https://towardsdatascience.com/aws-lambda-as-a-link-between-sqs-and-kinesis-a39cb6e4f762/)\n## [AWS Lambda as a link between SQS and Kinesis](https://towardsdatascience.com/aws-lambda-as-a-link-between-sqs-and-kinesis-a39cb6e4f762/)\n[Data Engineering](https://towardsdatascience.com/category/data-science/data-engineering/)\nUsing Lambda as a bridge to enable data flow from SQS queue in Account X to Kinesis Data Stream in Account Y\n[Shreyas Mondikal Subramanya](https://towardsdatascience.com/author/shreyas-ms/)\nApril 12, 20215 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/05/0udiFWxQnw4SpyBcO.jpg)](https://towardsdatascience.com/doing-almost-as-much-with-much-less-a-case-study-in-biomedical-named-entity-recognition-efa4abe18ed/)\n## [Doing almost as much with much less: A Case Study in Biomedical Named Entity Recognition](https://towardsdatascience.com/doing-almost-as-much-with-much-less-a-case-study-in-biomedical-named-entity-recognition-efa4abe18ed/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nThoughts and Theory Can a simple string-matching method compete against a big supervised model? At...\n[Stephan Tulkens](https://towardsdatascience.com/author/stephantul/)\nMay 27, 202112 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/01/1xgfSz1jMp3678YtVd6Lyyw.png)](https://towardsdatascience.com/intro-to-gaussian-process-regression-14f7c647d74d/)\n## [Intro to Gaussian Process Regression](https://towardsdatascience.com/intro-to-gaussian-process-regression-14f7c647d74d/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nA conceptual guide\n[Alex Powell](https://towardsdatascience.com/author/a-pow/)\nJanuary 6, 20214 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/08/header_infi_roce.png)](https://towardsdatascience.com/infiniband-vs-rocev2-choosing-the-right-network-for-large-scale-ai/)\n## [InfiniBand vs RoCEv2: Choosing the Right Network for Large-Scale AI](https://towardsdatascience.com/infiniband-vs-rocev2-choosing-the-right-network-for-large-scale-ai/)\n[Large Data Models](https://towardsdatascience.com/category/artificial-intelligence/large-data-models/)\nLearn how InfiniBand and RoCEv2 enable high-speed GPU communication\n[Shireesh Kumar Singh](https://towardsdatascience.com/author/shireeshkumar.singh/)\nAugust 6, 20257 min read\n\n\n  * [YouTube](https://www.youtube.com/c/TowardsDataScience)\n  * [X](https://x.com/TDataScience)\n  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)\n  * [Threads](https://www.threads.net/@towardsdatascience)\n  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)\n\n\n[](https://towardsdatascience.com/)\nYour home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.\nSubscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)\n© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)\n####  Recommended Articles \nClose\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607639/image?etag=1781250125848&width=500&height=500) Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1 ](https://towardsdatascience.com/javascript-fatigue-you-dont-need-js-to-build-chatgpt/ \"Javascript Fatigue: HTMX Is All You Need to Build ChatGPT — Part 1\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/607930/image?etag=1782124566054&width=500&height=500) The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs ](https://towardsdatascience.com/subset-sum-problem-solved-in-linear-time-for-dense-enough-inputs/ \"The Subset Sum Problem Solved in Linear Time for Dense Enough Inputs\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/3660/image?etag=1780176246070&width=500&height=500) Does Your Company Have a Data Strategy? ](https://towardsdatascience.com/does-your-company-have-a-data-strategy-e8944dbec4ae/ \"Does Your Company Have a Data Strategy?\")\n  * [ ![](https://h030.towardsdatascience.com/rest/v2/contentStores/d7d3a4ab-7caf-4383-bbd2-fbf7fb4f1787/items/4970/image?etag=1780565225463&width=500&height=500) Productivity Tips, Data Career Insights, and Other Recent Must-Reads ](https://towardsdatascience.com/productivity-tips-data-career-insights-and-other-recent-must-reads-5c47eb7a2fe0/ \"Productivity Tips, Data Career Insights, and Other Recent Must-Reads\")\n\n\n",
  "body_base_path": "attachments/e04716433f71/pages/",
  "body_markdown_path": "attachments/e04716433f71/pages/archived-body.md",
  "local_html": "attachments/e04716433f71/pages/archived-body.html",
  "body_source": "prior_capture"
}