{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Chaim Rand",
  "title_listed": "Optimizing PyTorch Model Inference on AWS Graviton",
  "keywords": "",
  "domain": "机器学习",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/optimizing-pytorch-model-inference-on-aws-graviton/",
  "publish_date": "2025-12-10",
  "corpus_stage": "",
  "notes": "",
  "id": "4f30fba24dc0",
  "collected_at": "2026-10-02T11:05:57",
  "title": "Optimizing PyTorch Model Inference on AWS Graviton | 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[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\n# Optimizing PyTorch Model Inference on AWS Graviton\nTips for accelerating AI/ML on CPU — Part 2\n[Chaim Rand](https://towardsdatascience.com/author/chaimrand/)\nDecember 10, 20259 min read\n![](../images/000.jpg)\n[Photo](https://unsplash.com/photos/view-of-earth-and-satellite-yZygONrUBe8) by NASA on Unsplash\nDeveloping and deploying AI/ML models can be an extremely expensive endeavor. Many of [our posts](https://towardsdatascience.com/author/chaimrand/) have been focused on a wide variety of tips, tricks, and techniques for analyzing and optimizing the runtime performance of AI/ML workloads. Our argument has been twofold:\n  1. Performance analysis and optimizations must be an integral process of every AI/ML development project, and,\n  2. Reaching meaningful performance boosts and cost reduction does not require a high degree of specialization. Any AI/ML developer can do it. Every AI/ML developer should do it.\n\n\n[In a recent post](https://towardsdatascience.com/optimizing-pytorch-model-inference-on-cpu), we addressed the challenge of optimizing an ML inference workload on an Intel® Xeon® processor. We began by reviewing a number of scenarios in which a CPU might be the best choice for AI/ML inference even in an era of multiple dedicated AI inference chips. We then introduced a toy image-classification PyTorch model and proceeded to demonstrate a wide number of techniques for boosting its runtime performance on an [Amazon EC2 c7i.xlarge](https://aws.amazon.com/ec2/instance-types/c7i/) instance, powered by 4th Generation Intel Xeon Scalable processors. In this post, we extend our discussion to AWS’s homegrown Arm-based Graviton CPUs. We will revisit many of the optimizations we discussed in our previous posts — some of which will require adaptation to the Arm processor — and assess their impact on the same toy model. Given the profound differences between the Arm and Intel processors, the paths to the best performing configuration may take different paths.\nLearn this step by step with the interactive [Machine Learning](https://roadmap.sh/machine-learning) roadmap.\n## AWS Graviton\n[AWS Graviton](https://aws.amazon.com/ec2/graviton/) is a family of processors based on [Arm Neoverse](https://www.arm.com/products/silicon-ip-cpu/neoverse/neoverse-n1) CPUs, that are custom designed and built by AWS for optimal price-performance and energy efficiency. Their dedicated engines for vector processing ([NEON](https://developer.arm.com/Architectures/Neon) and [SVE/SVE2](https://developer.arm.com/Architectures/Scalable%20Vector%20Extensions)) and matrix multiplication ([MMLA](https://developer.arm.com/documentation/ddi0596/2020-12/SVE-Instructions/BFMMLA--BFloat16-floating-point-matrix-multiply-accumulate-)), and their support for [Bfloat16](https://en.wikipedia.org/wiki/Bfloat16_floating-point_format) operations (as of Graviton3), make them a compelling candidate for running compute intensive workloads such as [AI/ML inference](https://community.arm.com/arm-community-blogs/b/servers-and-cloud-computing-blog/posts/machine-learning-inference-on-aws-graviton3). To facilitate high-performance AI/ML on Graviton, the entire software stack has been optimized for its use:\n  * **Low-Level Compute Kernels** from the [**Arm Compute Library (ACL)**](https://github.com/ARM-software/ComputeLibrary) are highly optimized to leverage the Graviton hardware accelerators (e.g., SVE and MMLA).\n  * **ML Middleware Libraries** such as [oneDNN](https://github.com/uxlfoundation/oneDNN) and [OpenBLAS](https://github.com/OpenMathLib/OpenBLAS) route deep learning and linear algebra operations to the specialized ACL kernels.\n  * **AI/ML Frameworks** like [PyTorch](https://github.com/aws/aws-graviton-getting-started/blob/main/machinelearning/pytorch.md) and [TensorFlow](https://github.com/aws/aws-graviton-getting-started/blob/main/machinelearning/tensorflow.md) are compiled and configured to use these optimized backends.\n\n\nIn this post we will use an [Amazon EC2 c8g.xlarge](https://aws.amazon.com/ec2/instance-types/c8g/) instance powered by four [AWS Graviton4](https://aws.amazon.com/ec2/graviton/) processors and an [AWS ARM64 PyTorch Deep Learning AMI](https://docs.aws.amazon.com/dlami/latest/devguide/aws-deep-learning-arm64-gpu-pytorch-2.8-ubuntu-24-04.html) (DLAMI).\nThe intention of this post is to demonstrate tips for boosting performance on an AWS Graviton instance. Importantly, our intention is **not** to draw a comparison between AWS Graviton and alternative chips, nor is it to advocate for the use of one chip over the other. The best choice of processor depends on a whole bunch of considerations beyond the scope of this post. One of the important considerations will be the maximum runtime performance of your model on each chip. In other words: how much “bang” can we get for our buck? Thus, making an informed decision about the best processor is one of the motivations for optimizing runtime performance on each one.\nAnother motivation for optimizing our model’s performance for multiple inference devices, is to increase its portability. The playing field of AI/ML is extremely dynamic and resilience to changing circumstances is crucial for success. It is not uncommon for compute instances of certain types to suddenly become unavailable or scarce. Conversely, an increase in capacity of AWS Graviton instances, could imply their availability at steep discounts, e.g., in the [Amazon EC2 Spot Instance](https://aws.amazon.com/ec2/spot/pricing/) market, presenting cost-savings opportunities that you would not want to miss out on.\n## Disclaimers\nThe blocks code of code we will share, the optimization steps we will discuss, and the results we will reach, are intended as an example of the benefits you may see from ML performance optimization on an AWS Graviton instance. These may differ considerably from the results you might see with your own model and runtime environment. Please do not rely on the accuracy or optimality of the contents of this post. Please do not interpret the mention of any library, framework, or platform as an endorsement of its use.\n## Inference Optimization on AWS Graviton\nAs in our [previous post](https://towardsdatascience.com/optimizing-pytorch-model-inference-on-cpu), we will demonstrate the optimization steps on a toy image classification model:\npython\n\n```\nimport torch, torchvision\nimport time\n\n\ndef get_model(channels_last=False, compile=False):\n    model = torchvision.models.resnet50()\n\n    if channels_last:\n        model= model.to(memory_format=torch.channels_last)\n\n    model = model.eval()\n\n    if compile:\n        model = torch.compile(model)\n\n    return model\n\ndef get_input(batch_size, channels_last=False):\n    batch = torch.randn(batch_size, 3, 224, 224)\n    if channels_last:\n        batch = batch.to(memory_format=torch.channels_last)\n    return batch\n\ndef get_inference_fn(model, enable_amp=False):\n    def infer_fn(batch):\n        with torch.inference_mode(), torch.amp.autocast(\n                'cpu',\n                dtype=torch.bfloat16,\n                enabled=enable_amp\n        ):\n            output = model(batch)\n        return output\n    return infer_fn\n\ndef benchmark(infer_fn, batch):\n    # warm-up\n    for _ in range(20):\n        _ = infer_fn(batch)\n\n    iters = 100\n\n    start = time.time()\n    for _ in range(iters):\n        _ = infer_fn(batch)\n    end = time.time()\n\n    return (end - start) / iters\n\n\nbatch_size = 1\nmodel = get_model()\nbatch = get_input(batch_size)\ninfer_fn = get_inference_fn(model)\navg_time = benchmark(infer_fn, batch)\nprint(f\"\\nAverage samples per second: {(batch_size/avg_time):.2f}\")\n```\n\nThe initial throughput is 12 samples per second (SPS).\n### Upgrade to the Most Recent PyTorch Release\nWhereas the version of PyTorch in our DLAMI is 2.8, the latest version of PyTorch, at the time of this writing, is 2.9. Given the rapid pace of development in the field of AI/ML, it is highly recommended to use the most up-to-date library packages. As our first step, we upgrade to [PyTorch 2.9](https://pytorch.org/blog/pytorch-2-9/) which [includes key updates to its Arm backend](https://community.arm.com/arm-community-blogs/b/ai-blog/posts/advancing-pytorch-performance-on-arm-key-enhancements-in-the-2-9-release).\nbash\n\n```\npip3 install -U torch torchvision --index-url https://download.pytorch.org/whl/cpu\n```\n\nIn the case of our model in its initial configuration, upgrading the PyTorch version does not have any effect. However, this step is crucial for getting the most out of the optimization techniques that we will assess.\n### Batched Inference\nTo reduce the overhead of launching overheads and increase the utilization of the HW accelerators, we group together samples and apply batched inference. The table below demonstrates how the model throughput varies as a function of batch size:\n![](../images/001.webp)\nInference Throughput for Varying Batch Sizes (by Author)\n### Memory Optimizations\nWe apply a number of techniques from our previous post for optimizing memory allocation and usage. These include the [channels-last memory format](https://docs.pytorch.org/tutorials/intermediate/memory_format_tutorial.html), [automatic mixed precision](https://pytorch.org/docs/stable/amp.html) with the bfloat16 data type (supported from Graviton3), the [TCMalloc](https://google.github.io/tcmalloc/overview.html) allocation library, and huge page allocation. Please see the [previous post](https://towardsdatascience.com/optimizing-pytorch-model-inference-on-cpu) for details. We also enable the  _fast math_ mode of the ACL GEMM kernels, and caching of the kernel primitives — two optimizations that appear in the official [guidelines for running PyTorch inference on Graviton](https://github.com/aws/aws-graviton-getting-started/blob/main/machinelearning/pytorch.md#runtime-configurations-for-optimal-performance).\nThe command line instructions required to enable these optimizations are shown below:\nbash\n\n```\n# install TCMalloc\nsudo apt-get install google-perftools\n\n# Program the use of TCMalloc\nexport LD_PRELOAD=/usr/lib/aarch64-linux-gnu/libtcmalloc.so.4\n\n# Enable huge page memory allocation\nexport THP_MEM_ALLOC_ENABLE=1\n\n# Enable the fast math mode of the GEMM kernels\nexport DNNL_DEFAULT_FPMATH_MODE=BF16\n\n# Set LRU Cache capacity to cache the kernel primitives\nexport LRU_CACHE_CAPACITY=1024\n```\n\nThe following table captures the impact of the memory optimizations, applied successively:\n![](../images/body-dadc397f87aabaffefd2.webp)\nResNet-50 Memory Optimization Results (by Author)\nIn the case of our toy model, the  _channels-last_ and  _bfloat16-mixed precision_ optimizations had the greatest impact. After applying all of the memory optimizations, the average throughput is 53.03 SPS.\n### Model Compilation\nThe support of PyTorch compilation for AWS Graviton is an [area of focused effort of the AWS Graviton team](https://aws.amazon.com/blogs/machine-learning/accelerated-pytorch-inference-with-torch-compile-on-aws-graviton-processors/). However, in the case of our toy model, it results in a slight reduction in throughput, from 53.03 SPS to 52.23.\n### Multi-Worker Inference\nWhile typically applied in settings with many more than four vCPUs, we demonstrate the implementation of multi-worker inference by modifying our script to support core pinning:\npython\n\n```\nif __name__ == '__main__':\n    # pin CPUs according to worker rank\n    import os, psutil\n    rank = int(os.environ.get('RANK','0'))\n    world_size = int(os.environ.get('WORLD_SIZE','1'))\n    cores = list(range(psutil.cpu_count(logical=True)))\n    num_cores = len(cores)\n    cores_per_process = num_cores // world_size\n    start_index = rank * cores_per_process\n    end_index = (rank + 1) * cores_per_process\n    pid = os.getpid()\n    p = psutil.Process(pid)\n    p.cpu_affinity(cores[start_index:end_index])\n\n    batch_size = 8\n    model = get_model(channels_last=True)\n    batch = get_input(batch_size, channels_last=True)\n    infer_fn = get_inference_fn(model, enable_amp=True)\n    avg_time = benchmark(infer_fn, batch)\n    print(f\"\\nAverage samples per second: {(batch_size/avg_time):.2f}\")\n```\n\nWe note that contrary to other AWS EC2 CPU instance types, each Graviton vCPU maps directly to a single physical CPU core. We use the [torchrun](https://docs.pytorch.org/docs/stable/elastic/run.html) utility to start up four workers, with each running on a single CPU core:\nbash\n\n```\nexport OMP_NUM_THREADS=1 #set one OpenMP thread per worker\ntorchrun --nproc_per_node=4 main.py\n```\n\nThis results in a throughput of 55.15 SPS, a 4% improvement over our previous best result.\n### INT8 Quantization for Arm\nAnother area of active development and continuous improvement on Arm is INT8 quantization. INT8 quantization tools are typically heavily tied to the target instance type. In our [previous post](https://towardsdatascience.com/optimizing-pytorch-model-inference-on-cpu) we demonstrated [PyTorch 2 Export Quantization with X86 Backend through Inductor](https://docs.pytorch.org/ao/stable/tutorials_source/pt2e_quant_x86_inductor.html) using the [TorchAO](https://github.com/pytorch/ao) (0.12.1) library. Fortunately, recent versions of [TorchAO](https://github.com/pytorch/ao) include a dedicated [quantizer for Arm](https://github.com/pytorch/ao/blob/main/torchao/quantization/pt2e/quantizer/arm_inductor_quantizer.py). The updated quantization sequence is shown below. As in our [previous post](https://towardsdatascience.com/optimizing-pytorch-model-inference-on-cpu) we are interested just in the potential performance impact. In practice, INT8 quantization can have a significant impact on the quality of the model and may necessitate a more sophisticated quantization strategy.\npython\n\n```\nfrom torchao.quantization.pt2e.quantize_pt2e import prepare_pt2e, convert_pt2e\nimport torchao.quantization.pt2e.quantizer.arm_inductor_quantizer as aiq\n\ndef quantize_model(model):\n    x = torch.randn(4, 3, 224, 224).contiguous(\n                            memory_format=torch.channels_last)\n    example_inputs = (x,)\n    batch_dim = torch.export.Dim(\"batch\")\n    with torch.no_grad():\n        exported_model = torch.export.export(\n            model,\n            example_inputs,\n            dynamic_shapes=((batch_dim,\n                             torch.export.Dim.STATIC,\n                             torch.export.Dim.STATIC,\n                             torch.export.Dim.STATIC),\n                            )\n        ).module()\n    quantizer = aiq.ArmInductorQuantizer()\n    quantizer.set_global(aiq.get_default_arm_inductor_quantization_config())\n    prepared_model = prepare_pt2e(exported_model, quantizer)\n    prepared_model(*example_inputs)\n    converted_model = convert_pt2e(prepared_model)\n    optimized_model = torch.compile(converted_model)\n    return optimized_model\n\n\nbatch_size = 8\nmodel = get_model(channels_last=True)\nmodel = quantize_model(model)\nbatch = get_input(batch_size, channels_last=True)\ninfer_fn = get_inference_fn(model, enable_amp=True)\navg_time = benchmark(infer_fn, batch)\nprint(f\"\\nAverage samples per second: {(batch_size/avg_time):.2f}\")\n```\n\nThe resultant throughput is 56.77 SPS for a 7.1% improvement over the bfloat16 solution.\n### AOT Compilation Using ONNX and OpenVINO\nIn [our previous post](https://towardsdatascience.com/optimizing-pytorch-model-inference-on-cpu), we explored ahead-of-time (AOT) model compilation techniques using [Open Neural Network Exchange](https://onnx.ai/) (ONNX) and [OpenVINO](https://docs.openvino.ai/2025/index.html). Both libraries include dedicated support for running on AWS Graviton (e.g., see [here](https://github.com/aws/aws-graviton-getting-started/blob/main/machinelearning/onnx.md) and [here](https://blog.openvino.ai/blog-posts/openvino-toolkit-for-arm-platforms-overview)). The experiments in this section require the following library installations:\nbash\n\n```\npip install onnxruntime onnxscript openvino nncf\n```\n\nThe following code block demonstrates the model compilation and execution on Arm using ONNX:\npython\n\n```\ndef export_to_onnx(model, onnx_path=\"resnet50.onnx\"):\n    dummy_input = torch.randn(4, 3, 224, 224)\n    batch = torch.export.Dim(\"batch\")\n    torch.onnx.export(\n        model,\n        dummy_input,\n        onnx_path,\n        input_names=[\"input\"],\n        output_names=[\"output\"],\n        dynamic_shapes=((batch,\n                         torch.export.Dim.STATIC,\n                         torch.export.Dim.STATIC,\n                         torch.export.Dim.STATIC),\n                        ),\n        dynamo=True\n    )\n    return onnx_path\n\ndef onnx_infer_fn(onnx_path):\n    import onnxruntime as ort\n\n    sess = ort.InferenceSession(\n        onnx_path,\n        providers=[\"CPUExecutionProvider\"]\n   )\n    sess_options = ort.SessionOptions()\n    sess_options.add_session_config_entry(\n               \"mlas.enable_gemm_fastmath_arm64_bfloat16\", \"1\")\n    input_name = sess.get_inputs()[0].name\n\n    def infer_fn(batch):\n        result = sess.run(None, {input_name: batch})\n        return result\n    return infer_fn\n\nbatch_size = 8\nmodel = get_model()\nonnx_path = export_to_onnx(model)\nbatch = get_input(batch_size).numpy()\ninfer_fn = onnx_infer_fn(onnx_path)\navg_time = benchmark(infer_fn, batch)\nprint(f\"\\nAverage samples per second: {(batch_size/avg_time):.2f}\")\n```\n\nIt should be noted that the ONNX runtime supports a dedicated [ACL-ExecutionProvider](https://onnxruntime.ai/docs/execution-providers/community-maintained/ACL-ExecutionProvider.html) for running on Arm, but this requires a custom ONNX build (as of the time of this writing), which is out of the scope of this post.\nAlternatively, we can compile the model using [OpenVINO](https://docs.openvino.ai/2025/index.html). The code block below demonstrates its use, including an option for INT8 quantization using [NNCF](https://docs.openvino.ai/2025/openvino-workflow/model-optimization-guide/quantizing-models-post-training/basic-quantization-flow.html):\npython\n\n```\nimport openvino as ov\nimport nncf\n\ndef openvino_infer_fn(compiled_model):\n    def infer_fn(batch):\n        result = compiled_model([batch])[0]\n        return result\n    return infer_fn\n\nclass RandomDataset(torch.utils.data.Dataset):\n    def __len__(self):\n        return 10000\n\n    def __getitem__(self, idx):\n        return torch.randn(3, 224, 224)\n\nquantize_model = False\nbatch_size = 8\nmodel = get_model()\ncalibration_loader = torch.utils.data.DataLoader(RandomDataset())\ncalibration_dataset = nncf.Dataset(calibration_loader)\n\nif quantize_model:\n    # quantize PyTorch model\n    model = nncf.quantize(model, calibration_dataset)\n\novm = ov.convert_model(model, example_input=torch.randn(1, 3, 224, 224))\novm = ov.compile_model(ovm)\nbatch = get_input(batch_size).numpy()\ninfer_fn = openvino_infer_fn(ovm)\navg_time = benchmark(infer_fn, batch)\nprint(f\"\\nAverage samples per second: {(batch_size/avg_time):.2f}\")\n```\n\nIn the case of our toy model, OpenVINO compilation results in an additional boost of the throughput to 63.48 SPS, but the NNCF quantization disappoints, resulting in just 55.18 SPS.\n## Results\nThe results of our experiments are summarized in the table below:\n![](../images/body-32fa8128c096a626b4e4.webp)\nResNet50 Inference Optimization Results (by Author)  \n\nAs in our [previous post](https://towardsdatascience.com/optimizing-pytorch-model-inference-on-cpu), we reran our experiments on a second model — a Vision Transformer (ViT) from the [timm](https://pypi.org/project/timm/) library — to demonstrate how the impact of the runtime optimizations we discussed can vary based on the details of the model. The results are captured below:\n![](../images/body-a89777d4cb7e9e5a8a34.webp)\nViT Inference Optimization Results (by Author)\n## Summary\nIn this post, we reviewed a number of relatively simple optimization techniques and applied them to two toy PyTorch models. As the results demonstrated, the impact of each optimization step can vary greatly based on the details of the model, and the journey toward peak performance can take many different paths. The steps we presented in this post were just an appetizer; there are undoubtedly many more optimizations that can unlock even greater performance.\nAlong the way, we noted the many AI/ML libraries that have introduced deep support for the Graviton architecture, and the seemingly continuous community effort of ongoing optimization. The performance gains we achieved, combined with this apparent dedication, prove that AWS Graviton is firmly in the “big leagues” when it comes to running compute-intensive AI/ML 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[Artificial Intelligence](https://towardsdatascience.com/tag/artificial-intelligence/)[Deep Learning](https://towardsdatascience.com/tag/deep-learning/)[Inference](https://towardsdatascience.com/tag/inference/)[Machine Learning](https://towardsdatascience.com/tag/machine-learning/)[Pytorch](https://towardsdatascience.com/tag/pytorch/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Foptimizing-pytorch-model-inference-on-aws-graviton%2F&title=Optimizing%20PyTorch%20Model%20Inference%20on%20AWS%20Graviton)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Foptimizing-pytorch-model-inference-on-aws-graviton%2F&title=Optimizing%20PyTorch%20Model%20Inference%20on%20AWS%20Graviton)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Foptimizing-pytorch-model-inference-on-aws-graviton%2F&text=Optimizing%20PyTorch%20Model%20Inference%20on%20AWS%20Graviton)\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.jpeg)](https://towardsdatascience.com/back-propagation-the-easy-way-part-2-bea37046c897/)\n## [Back Propagation, the Easy Way (Part 2)](https://towardsdatascience.com/back-propagation-the-easy-way-part-2-bea37046c897/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nPractical implementation\n[Ziad SALLOUM](https://towardsdatascience.com/author/zsalloum/)\nJanuary 19, 20196 min read\n  * [![](../images/body-63beb50f664a055ed739.jpg)](https://towardsdatascience.com/text-classification-with-bert-in-pytorch-887965e5820f/)\n## [Text Classification with BERT in PyTorch](https://towardsdatascience.com/text-classification-with-bert-in-pytorch-887965e5820f/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nHow to leverage a pre-trained BERT model from Hugging Face to classify text of news articles\n[Ruben Winastwan](https://towardsdatascience.com/author/marcellusruben/)\nNovember 10, 20214 min read\n  * [![](../images/004.jpeg)](https://towardsdatascience.com/how-to-price-an-ai-project-in-2023-7ffa627dd32f/)\n## [How to Price an AI Project in 2023](https://towardsdatascience.com/how-to-price-an-ai-project-in-2023-7ffa627dd32f/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nWhat's new and what stayed the same 6 years after my 2017 article in TDS\n[Daniel Shapiro, PhD](https://towardsdatascience.com/author/lemaysolutions/)\nJanuary 12, 202311 min read\n  * [![](../images/005.jpg)](https://towardsdatascience.com/audio-deep-learning-made-simple-part-1-state-of-the-art-techniques-da1d3dff2504/)\n## [Audio Deep Learning Made Simple (Part 1): State-of-the-Art Techniques](https://towardsdatascience.com/audio-deep-learning-made-simple-part-1-state-of-the-art-techniques-da1d3dff2504/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nA Gentle Guide to the world of disruptive deep learning audio applications and architectures. And why we all need to know about...\n[Ketan Doshi](https://towardsdatascience.com/author/ketanhdoshi/)\nFebruary 11, 202112 min read\n  * [![](../images/006.png)](https://towardsdatascience.com/introduction-to-support-vector-machines-motivation-and-basics-920e4c1e22e0/)\n## [Introduction to Support Vector Machines - Motivation and Basics](https://towardsdatascience.com/introduction-to-support-vector-machines-motivation-and-basics-920e4c1e22e0/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nLearn basic concepts that make Support Vector Machine a powerful linear classifier\n[Rishabh Misra](https://towardsdatascience.com/author/rishabh_misra_/)\nAugust 10, 20247 min read\n  * [![](../images/007.png)](https://towardsdatascience.com/a-loss-function-suitable-for-class-imbalanced-data-focal-loss-af1702d75d75/)\n## [A Loss Function Suitable for Class Imbalanced Data: \"Focal Loss\"](https://towardsdatascience.com/a-loss-function-suitable-for-class-imbalanced-data-focal-loss-af1702d75d75/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nDeep Learning with Class Imbalanced Data\n[Saptashwa Bhattacharyya](https://towardsdatascience.com/author/saptashwa/)\nFebruary 15, 20219 min read\n  * [![](../images/008.png)](https://towardsdatascience.com/decision-tree-classifier-explained-a-visual-guide-with-code-examples-for-beginners-7c863f06a71e/)\n## [Decision Tree Classifier, Explained: A Visual Guide with Code Examples for Beginners](https://towardsdatascience.com/decision-tree-classifier-explained-a-visual-guide-with-code-examples-for-beginners-7c863f06a71e/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nA fresh look on our favorite upside-down tree\n[Samy Baladram](https://towardsdatascience.com/author/samybaladram/)\nAugust 30, 202410 min read\n  * [![](../images/009.jpg)](https://towardsdatascience.com/i-stole-a-wall-street-trick-to-solve-a-google-trends-data-problem-2/)\n## [I Stole a Wall Street Trick to Solve a Google Trends Data Problem](https://towardsdatascience.com/i-stole-a-wall-street-trick-to-solve-a-google-trends-data-problem-2/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nA methodology for comparing Google Trends data across countries.\n[Leigh Collier](https://towardsdatascience.com/author/leigh.collier/)\nMarch 9, 202612 min read\n  * [![](../images/010.jpg)](https://towardsdatascience.com/data-mining-market-basket-analysis-with-apriori-algorithm-970ff256a92c/)\n## [Data Mining: Market Basket Analysis with Apriori Algorithm](https://towardsdatascience.com/data-mining-market-basket-analysis-with-apriori-algorithm-970ff256a92c/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nUncovering the secret behind why breads are always conveniently placed beside butter in groceries\n[Yenwee Lim](https://towardsdatascience.com/author/limyenwee_19946/)\nApril 8, 20228 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 PyTorch Model Inference on AWS Graviton | Towards Data Science",
    "description": "Tips for accelerating AI/ML on CPU — Part 2",
    "keywords": null,
    "author": "Chaim Rand",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "Optimizing PyTorch Model Inference on AWS Graviton",
    "og:description": "Tips for accelerating AI/ML on CPU — Part 2",
    "og:url": "https://towardsdatascience.com/optimizing-pytorch-model-inference-on-aws-graviton/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2025/12/1-4-scaled-copy.jpg",
    "og:image:width": "2560",
    "og:image:height": "1704",
    "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": "9 min read",
    "article:published_time": "2025-12-10T07:00:07.000Z",
    "article:modified_time": "2025-12-10T07: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/4f30fba24dc0/code/block_000.txt",
      "chars": 1283
    },
    {
      "language": "txt",
      "file": "attachments/4f30fba24dc0/code/block_001.txt",
      "chars": 83
    },
    {
      "language": "txt",
      "file": "attachments/4f30fba24dc0/code/block_002.txt",
      "chars": 392
    },
    {
      "language": "txt",
      "file": "attachments/4f30fba24dc0/code/block_003.txt",
      "chars": 793
    },
    {
      "language": "txt",
      "file": "attachments/4f30fba24dc0/code/block_004.txt",
      "chars": 95
    },
    {
      "language": "txt",
      "file": "attachments/4f30fba24dc0/code/block_005.txt",
      "chars": 1371
    },
    {
      "language": "txt",
      "file": "attachments/4f30fba24dc0/code/block_006.txt",
      "chars": 49
    },
    {
      "language": "txt",
      "file": "attachments/4f30fba24dc0/code/block_007.txt",
      "chars": 1260
    },
    {
      "language": "txt",
      "file": "attachments/4f30fba24dc0/code/block_008.txt",
      "chars": 913
    }
  ],
  "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-20T18:06:17Z"
    },
    {
      "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-20T18:06:17Z"
    },
    {
      "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-20T18:06:17Z"
    },
    {
      "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-20T18:06:17Z"
    }
  ],
  "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/artificial-intelligence/deep-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/chaimrand/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/optimizing-pytorch-model-inference-on-cpu"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/artificial-intelligence/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/deep-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/inference/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/machine-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/pytorch/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/back-propagation-the-easy-way-part-2-bea37046c897/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/zsalloum/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/text-classification-with-bert-in-pytorch-887965e5820f/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/marcellusruben/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/how-to-price-an-ai-project-in-2023-7ffa627dd32f/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/"
    },
    {
      "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/view-of-earth-and-satellite-yZygONrUBe8"
    },
    {
      "type": "external",
      "href": "https://aws.amazon.com/ec2/instance-types/c7i/"
    },
    {
      "type": "external",
      "href": "https://roadmap.sh/machine-learning"
    },
    {
      "type": "external",
      "href": "https://aws.amazon.com/ec2/graviton/"
    },
    {
      "type": "external",
      "href": "https://www.arm.com/products/silicon-ip-cpu/neoverse/neoverse-n1"
    },
    {
      "type": "external",
      "href": "https://developer.arm.com/Architectures/Neon"
    },
    {
      "type": "external",
      "href": "https://developer.arm.com/Architectures/Scalable%20Vector%20Extensions"
    },
    {
      "type": "external",
      "href": "https://developer.arm.com/documentation/ddi0596/2020-12/SVE-Instructions/BFMMLA--BFloat16-floating-point-matrix-multiply-accumulate-"
    },
    {
      "type": "external",
      "href": "https://en.wikipedia.org/wiki/Bfloat16_floating-point_format"
    },
    {
      "type": "external",
      "href": "https://community.arm.com/arm-community-blogs/b/servers-and-cloud-computing-blog/posts/machine-learning-inference-on-aws-graviton3"
    },
    {
      "type": "external",
      "href": "https://github.com/ARM-software/ComputeLibrary"
    },
    {
      "type": "external",
      "href": "https://github.com/uxlfoundation/oneDNN"
    },
    {
      "type": "external",
      "href": "https://github.com/OpenMathLib/OpenBLAS"
    },
    {
      "type": "external",
      "href": "https://github.com/aws/aws-graviton-getting-started/blob/main/machinelearning/pytorch.md"
    },
    {
      "type": "external",
      "href": "https://github.com/aws/aws-graviton-getting-started/blob/main/machinelearning/tensorflow.md"
    },
    {
      "type": "external",
      "href": "https://aws.amazon.com/ec2/instance-types/c8g/"
    },
    {
      "type": "external",
      "href": "https://docs.aws.amazon.com/dlami/latest/devguide/aws-deep-learning-arm64-gpu-pytorch-2.8-ubuntu-24-04.html"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:32:35Z",
  "source_url": "https://towardsdatascience.com/optimizing-pytorch-model-inference-on-aws-graviton/",
  "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[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\n# Optimizing PyTorch Model Inference on AWS Graviton\nTips for accelerating AI/ML on CPU — Part 2\n[Chaim Rand](https://towardsdatascience.com/author/chaimrand/)\nDecember 10, 20259 min read\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/12/1-4-scaled-copy.jpg)\n[Photo](https://unsplash.com/photos/view-of-earth-and-satellite-yZygONrUBe8) by NASA on Unsplash\nDeveloping and deploying AI/ML models can be an extremely expensive endeavor. Many of [our posts](https://towardsdatascience.com/author/chaimrand/) have been focused on a wide variety of tips, tricks, and techniques for analyzing and optimizing the runtime performance of AI/ML workloads. Our argument has been twofold:\n  1. Performance analysis and optimizations must be an integral process of every AI/ML development project, and,\n  2. Reaching meaningful performance boosts and cost reduction does not require a high degree of specialization. Any AI/ML developer can do it. Every AI/ML developer should do it.\n\n\n[In a recent post](https://towardsdatascience.com/optimizing-pytorch-model-inference-on-cpu), we addressed the challenge of optimizing an ML inference workload on an Intel® Xeon® processor. We began by reviewing a number of scenarios in which a CPU might be the best choice for AI/ML inference even in an era of multiple dedicated AI inference chips. We then introduced a toy image-classification PyTorch model and proceeded to demonstrate a wide number of techniques for boosting its runtime performance on an [Amazon EC2 c7i.xlarge](https://aws.amazon.com/ec2/instance-types/c7i/) instance, powered by 4th Generation Intel Xeon Scalable processors. In this post, we extend our discussion to AWS’s homegrown Arm-based Graviton CPUs. We will revisit many of the optimizations we discussed in our previous posts — some of which will require adaptation to the Arm processor — and assess their impact on the same toy model. Given the profound differences between the Arm and Intel processors, the paths to the best performing configuration may take different paths.\nLearn this step by step with the interactive [Machine Learning](https://roadmap.sh/machine-learning) roadmap.\n## AWS Graviton\n[AWS Graviton](https://aws.amazon.com/ec2/graviton/) is a family of processors based on [Arm Neoverse](https://www.arm.com/products/silicon-ip-cpu/neoverse/neoverse-n1) CPUs, that are custom designed and built by AWS for optimal price-performance and energy efficiency. Their dedicated engines for vector processing ([NEON](https://developer.arm.com/Architectures/Neon) and [SVE/SVE2](https://developer.arm.com/Architectures/Scalable%20Vector%20Extensions)) and matrix multiplication ([MMLA](https://developer.arm.com/documentation/ddi0596/2020-12/SVE-Instructions/BFMMLA--BFloat16-floating-point-matrix-multiply-accumulate-)), and their support for [Bfloat16](https://en.wikipedia.org/wiki/Bfloat16_floating-point_format) operations (as of Graviton3), make them a compelling candidate for running compute intensive workloads such as [AI/ML inference](https://community.arm.com/arm-community-blogs/b/servers-and-cloud-computing-blog/posts/machine-learning-inference-on-aws-graviton3). To facilitate high-performance AI/ML on Graviton, the entire software stack has been optimized for its use:\n  * **Low-Level Compute Kernels** from the [**Arm Compute Library (ACL)**](https://github.com/ARM-software/ComputeLibrary) are highly optimized to leverage the Graviton hardware accelerators (e.g., SVE and MMLA).\n  * **ML Middleware Libraries** such as [oneDNN](https://github.com/uxlfoundation/oneDNN) and [OpenBLAS](https://github.com/OpenMathLib/OpenBLAS) route deep learning and linear algebra operations to the specialized ACL kernels.\n  * **AI/ML Frameworks** like [PyTorch](https://github.com/aws/aws-graviton-getting-started/blob/main/machinelearning/pytorch.md) and [TensorFlow](https://github.com/aws/aws-graviton-getting-started/blob/main/machinelearning/tensorflow.md) are compiled and configured to use these optimized backends.\n\n\nIn this post we will use an [Amazon EC2 c8g.xlarge](https://aws.amazon.com/ec2/instance-types/c8g/) instance powered by four [AWS Graviton4](https://aws.amazon.com/ec2/graviton/) processors and an [AWS ARM64 PyTorch Deep Learning AMI](https://docs.aws.amazon.com/dlami/latest/devguide/aws-deep-learning-arm64-gpu-pytorch-2.8-ubuntu-24-04.html) (DLAMI).\nThe intention of this post is to demonstrate tips for boosting performance on an AWS Graviton instance. Importantly, our intention is **not** to draw a comparison between AWS Graviton and alternative chips, nor is it to advocate for the use of one chip over the other. The best choice of processor depends on a whole bunch of considerations beyond the scope of this post. One of the important considerations will be the maximum runtime performance of your model on each chip. In other words: how much “bang” can we get for our buck? Thus, making an informed decision about the best processor is one of the motivations for optimizing runtime performance on each one.\nAnother motivation for optimizing our model’s performance for multiple inference devices, is to increase its portability. The playing field of AI/ML is extremely dynamic and resilience to changing circumstances is crucial for success. It is not uncommon for compute instances of certain types to suddenly become unavailable or scarce. Conversely, an increase in capacity of AWS Graviton instances, could imply their availability at steep discounts, e.g., in the [Amazon EC2 Spot Instance](https://aws.amazon.com/ec2/spot/pricing/) market, presenting cost-savings opportunities that you would not want to miss out on.\n## Disclaimers\nThe blocks code of code we will share, the optimization steps we will discuss, and the results we will reach, are intended as an example of the benefits you may see from ML performance optimization on an AWS Graviton instance. These may differ considerably from the results you might see with your own model and runtime environment. Please do not rely on the accuracy or optimality of the contents of this post. Please do not interpret the mention of any library, framework, or platform as an endorsement of its use.\n## Inference Optimization on AWS Graviton\nAs in our [previous post](https://towardsdatascience.com/optimizing-pytorch-model-inference-on-cpu), we will demonstrate the optimization steps on a toy image classification model:\npython\n\n```\nimport torch, torchvision\nimport time\n\n\ndef get_model(channels_last=False, compile=False):\n    model = torchvision.models.resnet50()\n\n    if channels_last:\n        model= model.to(memory_format=torch.channels_last)\n\n    model = model.eval()\n\n    if compile:\n        model = torch.compile(model)\n\n    return model\n\ndef get_input(batch_size, channels_last=False):\n    batch = torch.randn(batch_size, 3, 224, 224)\n    if channels_last:\n        batch = batch.to(memory_format=torch.channels_last)\n    return batch\n\ndef get_inference_fn(model, enable_amp=False):\n    def infer_fn(batch):\n        with torch.inference_mode(), torch.amp.autocast(\n                'cpu',\n                dtype=torch.bfloat16,\n                enabled=enable_amp\n        ):\n            output = model(batch)\n        return output\n    return infer_fn\n\ndef benchmark(infer_fn, batch):\n    # warm-up\n    for _ in range(20):\n        _ = infer_fn(batch)\n\n    iters = 100\n\n    start = time.time()\n    for _ in range(iters):\n        _ = infer_fn(batch)\n    end = time.time()\n\n    return (end - start) / iters\n\n\nbatch_size = 1\nmodel = get_model()\nbatch = get_input(batch_size)\ninfer_fn = get_inference_fn(model)\navg_time = benchmark(infer_fn, batch)\nprint(f\"\\nAverage samples per second: {(batch_size/avg_time):.2f}\")\n```\n\nThe initial throughput is 12 samples per second (SPS).\n### Upgrade to the Most Recent PyTorch Release\nWhereas the version of PyTorch in our DLAMI is 2.8, the latest version of PyTorch, at the time of this writing, is 2.9. Given the rapid pace of development in the field of AI/ML, it is highly recommended to use the most up-to-date library packages. As our first step, we upgrade to [PyTorch 2.9](https://pytorch.org/blog/pytorch-2-9/) which [includes key updates to its Arm backend](https://community.arm.com/arm-community-blogs/b/ai-blog/posts/advancing-pytorch-performance-on-arm-key-enhancements-in-the-2-9-release).\nbash\n\n```\npip3 install -U torch torchvision --index-url https://download.pytorch.org/whl/cpu\n```\n\nIn the case of our model in its initial configuration, upgrading the PyTorch version does not have any effect. However, this step is crucial for getting the most out of the optimization techniques that we will assess.\n### Batched Inference\nTo reduce the overhead of launching overheads and increase the utilization of the HW accelerators, we group together samples and apply batched inference. The table below demonstrates how the model throughput varies as a function of batch size:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/11/2-3.webp)\nInference Throughput for Varying Batch Sizes (by Author)\n### Memory Optimizations\nWe apply a number of techniques from our previous post for optimizing memory allocation and usage. These include the [channels-last memory format](https://docs.pytorch.org/tutorials/intermediate/memory_format_tutorial.html), [automatic mixed precision](https://pytorch.org/docs/stable/amp.html) with the bfloat16 data type (supported from Graviton3), the [TCMalloc](https://google.github.io/tcmalloc/overview.html) allocation library, and huge page allocation. Please see the [previous post](https://towardsdatascience.com/optimizing-pytorch-model-inference-on-cpu) for details. We also enable the  _fast math_ mode of the ACL GEMM kernels, and caching of the kernel primitives — two optimizations that appear in the official [guidelines for running PyTorch inference on Graviton](https://github.com/aws/aws-graviton-getting-started/blob/main/machinelearning/pytorch.md#runtime-configurations-for-optimal-performance).\nThe command line instructions required to enable these optimizations are shown below:\nbash\n\n```\n# install TCMalloc\nsudo apt-get install google-perftools\n\n# Program the use of TCMalloc\nexport LD_PRELOAD=/usr/lib/aarch64-linux-gnu/libtcmalloc.so.4\n\n# Enable huge page memory allocation\nexport THP_MEM_ALLOC_ENABLE=1\n\n# Enable the fast math mode of the GEMM kernels\nexport DNNL_DEFAULT_FPMATH_MODE=BF16\n\n# Set LRU Cache capacity to cache the kernel primitives\nexport LRU_CACHE_CAPACITY=1024\n```\n\nThe following table captures the impact of the memory optimizations, applied successively:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/11/3-3.webp)\nResNet-50 Memory Optimization Results (by Author)\nIn the case of our toy model, the  _channels-last_ and  _bfloat16-mixed precision_ optimizations had the greatest impact. After applying all of the memory optimizations, the average throughput is 53.03 SPS.\n### Model Compilation\nThe support of PyTorch compilation for AWS Graviton is an [area of focused effort of the AWS Graviton team](https://aws.amazon.com/blogs/machine-learning/accelerated-pytorch-inference-with-torch-compile-on-aws-graviton-processors/). However, in the case of our toy model, it results in a slight reduction in throughput, from 53.03 SPS to 52.23.\n### Multi-Worker Inference\nWhile typically applied in settings with many more than four vCPUs, we demonstrate the implementation of multi-worker inference by modifying our script to support core pinning:\npython\n\n```\nif __name__ == '__main__':\n    # pin CPUs according to worker rank\n    import os, psutil\n    rank = int(os.environ.get('RANK','0'))\n    world_size = int(os.environ.get('WORLD_SIZE','1'))\n    cores = list(range(psutil.cpu_count(logical=True)))\n    num_cores = len(cores)\n    cores_per_process = num_cores // world_size\n    start_index = rank * cores_per_process\n    end_index = (rank + 1) * cores_per_process\n    pid = os.getpid()\n    p = psutil.Process(pid)\n    p.cpu_affinity(cores[start_index:end_index])\n\n    batch_size = 8\n    model = get_model(channels_last=True)\n    batch = get_input(batch_size, channels_last=True)\n    infer_fn = get_inference_fn(model, enable_amp=True)\n    avg_time = benchmark(infer_fn, batch)\n    print(f\"\\nAverage samples per second: {(batch_size/avg_time):.2f}\")\n```\n\nWe note that contrary to other AWS EC2 CPU instance types, each Graviton vCPU maps directly to a single physical CPU core. We use the [torchrun](https://docs.pytorch.org/docs/stable/elastic/run.html) utility to start up four workers, with each running on a single CPU core:\nbash\n\n```\nexport OMP_NUM_THREADS=1 #set one OpenMP thread per worker\ntorchrun --nproc_per_node=4 main.py\n```\n\nThis results in a throughput of 55.15 SPS, a 4% improvement over our previous best result.\n### INT8 Quantization for Arm\nAnother area of active development and continuous improvement on Arm is INT8 quantization. INT8 quantization tools are typically heavily tied to the target instance type. In our [previous post](https://towardsdatascience.com/optimizing-pytorch-model-inference-on-cpu) we demonstrated [PyTorch 2 Export Quantization with X86 Backend through Inductor](https://docs.pytorch.org/ao/stable/tutorials_source/pt2e_quant_x86_inductor.html) using the [TorchAO](https://github.com/pytorch/ao) (0.12.1) library. Fortunately, recent versions of [TorchAO](https://github.com/pytorch/ao) include a dedicated [quantizer for Arm](https://github.com/pytorch/ao/blob/main/torchao/quantization/pt2e/quantizer/arm_inductor_quantizer.py). The updated quantization sequence is shown below. As in our [previous post](https://towardsdatascience.com/optimizing-pytorch-model-inference-on-cpu) we are interested just in the potential performance impact. In practice, INT8 quantization can have a significant impact on the quality of the model and may necessitate a more sophisticated quantization strategy.\npython\n\n```\nfrom torchao.quantization.pt2e.quantize_pt2e import prepare_pt2e, convert_pt2e\nimport torchao.quantization.pt2e.quantizer.arm_inductor_quantizer as aiq\n\ndef quantize_model(model):\n    x = torch.randn(4, 3, 224, 224).contiguous(\n                            memory_format=torch.channels_last)\n    example_inputs = (x,)\n    batch_dim = torch.export.Dim(\"batch\")\n    with torch.no_grad():\n        exported_model = torch.export.export(\n            model,\n            example_inputs,\n            dynamic_shapes=((batch_dim,\n                             torch.export.Dim.STATIC,\n                             torch.export.Dim.STATIC,\n                             torch.export.Dim.STATIC),\n                            )\n        ).module()\n    quantizer = aiq.ArmInductorQuantizer()\n    quantizer.set_global(aiq.get_default_arm_inductor_quantization_config())\n    prepared_model = prepare_pt2e(exported_model, quantizer)\n    prepared_model(*example_inputs)\n    converted_model = convert_pt2e(prepared_model)\n    optimized_model = torch.compile(converted_model)\n    return optimized_model\n\n\nbatch_size = 8\nmodel = get_model(channels_last=True)\nmodel = quantize_model(model)\nbatch = get_input(batch_size, channels_last=True)\ninfer_fn = get_inference_fn(model, enable_amp=True)\navg_time = benchmark(infer_fn, batch)\nprint(f\"\\nAverage samples per second: {(batch_size/avg_time):.2f}\")\n```\n\nThe resultant throughput is 56.77 SPS for a 7.1% improvement over the bfloat16 solution.\n### AOT Compilation Using ONNX and OpenVINO\nIn [our previous post](https://towardsdatascience.com/optimizing-pytorch-model-inference-on-cpu), we explored ahead-of-time (AOT) model compilation techniques using [Open Neural Network Exchange](https://onnx.ai/) (ONNX) and [OpenVINO](https://docs.openvino.ai/2025/index.html). Both libraries include dedicated support for running on AWS Graviton (e.g., see [here](https://github.com/aws/aws-graviton-getting-started/blob/main/machinelearning/onnx.md) and [here](https://blog.openvino.ai/blog-posts/openvino-toolkit-for-arm-platforms-overview)). The experiments in this section require the following library installations:\nbash\n\n```\npip install onnxruntime onnxscript openvino nncf\n```\n\nThe following code block demonstrates the model compilation and execution on Arm using ONNX:\npython\n\n```\ndef export_to_onnx(model, onnx_path=\"resnet50.onnx\"):\n    dummy_input = torch.randn(4, 3, 224, 224)\n    batch = torch.export.Dim(\"batch\")\n    torch.onnx.export(\n        model,\n        dummy_input,\n        onnx_path,\n        input_names=[\"input\"],\n        output_names=[\"output\"],\n        dynamic_shapes=((batch,\n                         torch.export.Dim.STATIC,\n                         torch.export.Dim.STATIC,\n                         torch.export.Dim.STATIC),\n                        ),\n        dynamo=True\n    )\n    return onnx_path\n\ndef onnx_infer_fn(onnx_path):\n    import onnxruntime as ort\n\n    sess = ort.InferenceSession(\n        onnx_path,\n        providers=[\"CPUExecutionProvider\"]\n   )\n    sess_options = ort.SessionOptions()\n    sess_options.add_session_config_entry(\n               \"mlas.enable_gemm_fastmath_arm64_bfloat16\", \"1\")\n    input_name = sess.get_inputs()[0].name\n\n    def infer_fn(batch):\n        result = sess.run(None, {input_name: batch})\n        return result\n    return infer_fn\n\nbatch_size = 8\nmodel = get_model()\nonnx_path = export_to_onnx(model)\nbatch = get_input(batch_size).numpy()\ninfer_fn = onnx_infer_fn(onnx_path)\navg_time = benchmark(infer_fn, batch)\nprint(f\"\\nAverage samples per second: {(batch_size/avg_time):.2f}\")\n```\n\nIt should be noted that the ONNX runtime supports a dedicated [ACL-ExecutionProvider](https://onnxruntime.ai/docs/execution-providers/community-maintained/ACL-ExecutionProvider.html) for running on Arm, but this requires a custom ONNX build (as of the time of this writing), which is out of the scope of this post.\nAlternatively, we can compile the model using [OpenVINO](https://docs.openvino.ai/2025/index.html). The code block below demonstrates its use, including an option for INT8 quantization using [NNCF](https://docs.openvino.ai/2025/openvino-workflow/model-optimization-guide/quantizing-models-post-training/basic-quantization-flow.html):\npython\n\n```\nimport openvino as ov\nimport nncf\n\ndef openvino_infer_fn(compiled_model):\n    def infer_fn(batch):\n        result = compiled_model([batch])[0]\n        return result\n    return infer_fn\n\nclass RandomDataset(torch.utils.data.Dataset):\n    def __len__(self):\n        return 10000\n\n    def __getitem__(self, idx):\n        return torch.randn(3, 224, 224)\n\nquantize_model = False\nbatch_size = 8\nmodel = get_model()\ncalibration_loader = torch.utils.data.DataLoader(RandomDataset())\ncalibration_dataset = nncf.Dataset(calibration_loader)\n\nif quantize_model:\n    # quantize PyTorch model\n    model = nncf.quantize(model, calibration_dataset)\n\novm = ov.convert_model(model, example_input=torch.randn(1, 3, 224, 224))\novm = ov.compile_model(ovm)\nbatch = get_input(batch_size).numpy()\ninfer_fn = openvino_infer_fn(ovm)\navg_time = benchmark(infer_fn, batch)\nprint(f\"\\nAverage samples per second: {(batch_size/avg_time):.2f}\")\n```\n\nIn the case of our toy model, OpenVINO compilation results in an additional boost of the throughput to 63.48 SPS, but the NNCF quantization disappoints, resulting in just 55.18 SPS.\n## Results\nThe results of our experiments are summarized in the table below:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/11/4-2.webp)\nResNet50 Inference Optimization Results (by Author)  \n\nAs in our [previous post](https://towardsdatascience.com/optimizing-pytorch-model-inference-on-cpu), we reran our experiments on a second model — a Vision Transformer (ViT) from the [timm](https://pypi.org/project/timm/) library — to demonstrate how the impact of the runtime optimizations we discussed can vary based on the details of the model. The results are captured below:\n![](https://assets.insightmediagroup.io/media/wp-content/uploads/2025/11/5-1.webp)\nViT Inference Optimization Results (by Author)\n## Summary\nIn this post, we reviewed a number of relatively simple optimization techniques and applied them to two toy PyTorch models. As the results demonstrated, the impact of each optimization step can vary greatly based on the details of the model, and the journey toward peak performance can take many different paths. The steps we presented in this post were just an appetizer; there are undoubtedly many more optimizations that can unlock even greater performance.\nAlong the way, we noted the many AI/ML libraries that have introduced deep support for the Graviton architecture, and the seemingly continuous community effort of ongoing optimization. The performance gains we achieved, combined with this apparent dedication, prove that AWS Graviton is firmly in the “big leagues” when it comes to running compute-intensive AI/ML 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[Artificial Intelligence](https://towardsdatascience.com/tag/artificial-intelligence/)[Deep Learning](https://towardsdatascience.com/tag/deep-learning/)[Inference](https://towardsdatascience.com/tag/inference/)[Machine Learning](https://towardsdatascience.com/tag/machine-learning/)[Pytorch](https://towardsdatascience.com/tag/pytorch/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Foptimizing-pytorch-model-inference-on-aws-graviton%2F&title=Optimizing%20PyTorch%20Model%20Inference%20on%20AWS%20Graviton)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Foptimizing-pytorch-model-inference-on-aws-graviton%2F&title=Optimizing%20PyTorch%20Model%20Inference%20on%20AWS%20Graviton)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Foptimizing-pytorch-model-inference-on-aws-graviton%2F&text=Optimizing%20PyTorch%20Model%20Inference%20on%20AWS%20Graviton)\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/2019/01/1aQ8yYq4PiC49TTbMS_wD7Q-scaled.jpeg)](https://towardsdatascience.com/back-propagation-the-easy-way-part-2-bea37046c897/)\n## [Back Propagation, the Easy Way (Part 2)](https://towardsdatascience.com/back-propagation-the-easy-way-part-2-bea37046c897/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nPractical implementation\n[Ziad SALLOUM](https://towardsdatascience.com/author/zsalloum/)\nJanuary 19, 20196 min read\n  * [![](https://towardsdatascience.com/images/fallback-image.jpg)](https://towardsdatascience.com/text-classification-with-bert-in-pytorch-887965e5820f/)\n## [Text Classification with BERT in PyTorch](https://towardsdatascience.com/text-classification-with-bert-in-pytorch-887965e5820f/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nHow to leverage a pre-trained BERT model from Hugging Face to classify text of news articles\n[Ruben Winastwan](https://towardsdatascience.com/author/marcellusruben/)\nNovember 10, 20214 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/01/1IHajfVeoOwry7K34EoGZXw.jpeg)](https://towardsdatascience.com/how-to-price-an-ai-project-in-2023-7ffa627dd32f/)\n## [How to Price an AI Project in 2023](https://towardsdatascience.com/how-to-price-an-ai-project-in-2023-7ffa627dd32f/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nWhat's new and what stayed the same 6 years after my 2017 article in TDS\n[Daniel Shapiro, PhD](https://towardsdatascience.com/author/lemaysolutions/)\nJanuary 12, 202311 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/02/0oCxt5IgoVGSWsnKQ-scaled.jpg)](https://towardsdatascience.com/audio-deep-learning-made-simple-part-1-state-of-the-art-techniques-da1d3dff2504/)\n## [Audio Deep Learning Made Simple (Part 1): State-of-the-Art Techniques](https://towardsdatascience.com/audio-deep-learning-made-simple-part-1-state-of-the-art-techniques-da1d3dff2504/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nA Gentle Guide to the world of disruptive deep learning audio applications and architectures. And why we all need to know about...\n[Ketan Doshi](https://towardsdatascience.com/author/ketanhdoshi/)\nFebruary 11, 202112 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/08/0zdY3L-nQhTu7kpVf.png)](https://towardsdatascience.com/introduction-to-support-vector-machines-motivation-and-basics-920e4c1e22e0/)\n## [Introduction to Support Vector Machines - Motivation and Basics](https://towardsdatascience.com/introduction-to-support-vector-machines-motivation-and-basics-920e4c1e22e0/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nLearn basic concepts that make Support Vector Machine a powerful linear classifier\n[Rishabh Misra](https://towardsdatascience.com/author/rishabh_misra_/)\nAugust 10, 20247 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/02/1CbQ2VWJ1HV8ypZDiTvY-A.png)](https://towardsdatascience.com/a-loss-function-suitable-for-class-imbalanced-data-focal-loss-af1702d75d75/)\n## [A Loss Function Suitable for Class Imbalanced Data: \"Focal Loss\"](https://towardsdatascience.com/a-loss-function-suitable-for-class-imbalanced-data-focal-loss-af1702d75d75/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nDeep Learning with Class Imbalanced Data\n[Saptashwa Bhattacharyya](https://towardsdatascience.com/author/saptashwa/)\nFebruary 15, 20219 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2024/08/1L__wKaz3S7hlKlff8wjQ-A.png)](https://towardsdatascience.com/decision-tree-classifier-explained-a-visual-guide-with-code-examples-for-beginners-7c863f06a71e/)\n## [Decision Tree Classifier, Explained: A Visual Guide with Code Examples for Beginners](https://towardsdatascience.com/decision-tree-classifier-explained-a-visual-guide-with-code-examples-for-beginners-7c863f06a71e/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nA fresh look on our favorite upside-down tree\n[Samy Baladram](https://towardsdatascience.com/author/samybaladram/)\nAugust 30, 202410 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/03/Copy-of-GUILTY.jpg)](https://towardsdatascience.com/i-stole-a-wall-street-trick-to-solve-a-google-trends-data-problem-2/)\n## [I Stole a Wall Street Trick to Solve a Google Trends Data Problem](https://towardsdatascience.com/i-stole-a-wall-street-trick-to-solve-a-google-trends-data-problem-2/)\n[Data Science](https://towardsdatascience.com/category/data-science/)\nA methodology for comparing Google Trends data across countries.\n[Leigh Collier](https://towardsdatascience.com/author/leigh.collier/)\nMarch 9, 202612 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/04/0qQ_AcNirSyLE_WD9-scaled.jpg)](https://towardsdatascience.com/data-mining-market-basket-analysis-with-apriori-algorithm-970ff256a92c/)\n## [Data Mining: Market Basket Analysis with Apriori Algorithm](https://towardsdatascience.com/data-mining-market-basket-analysis-with-apriori-algorithm-970ff256a92c/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nUncovering the secret behind why breads are always conveniently placed beside butter in groceries\n[Yenwee Lim](https://towardsdatascience.com/author/limyenwee_19946/)\nApril 8, 20228 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/4f30fba24dc0/pages/",
  "body_markdown_path": "attachments/4f30fba24dc0/pages/archived-body.md",
  "local_html": "attachments/4f30fba24dc0/pages/archived-body.html",
  "body_source": "prior_capture"
}