{
  "source_file": "0930",
  "source_platform": "Medium",
  "author": "Dhruv Matani",
  "title_listed": "NT-Xent (Normalized Temperature-Scaled Cross-Entropy) Loss Explained and Implemented in PyTorch",
  "keywords": "",
  "domain": "机器学习",
  "content_type": "深度技术解析",
  "is_paid_flag": "否",
  "url": "https://towardsdatascience.com/nt-xent-normalized-temperature-scaled-cross-entropy-loss-explained-and-implemented-in-pytorch-cc081f69848/",
  "publish_date": "2023-06-13",
  "corpus_stage": "",
  "notes": "",
  "id": "859dfd0f4c0e",
  "collected_at": "2026-10-02T10:52:24",
  "title": "NT-Xent (Normalized Temperature-Scaled Cross-Entropy) Loss Explained and Implemented in PyTorch | 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# NT-Xent (Normalized Temperature-Scaled Cross-Entropy) Loss Explained and Implemented in PyTorch\nAn intuitive explanation of the NT-Xent loss with a step-by-step explanation of the operation and our implementation in PyTorch\n[Dhruv Matani](https://towardsdatascience.com/author/dhruvbird/)\nJune 13, 202314 min read\nCo-authored with [Naresh Singh](https://medium.com/u/1e659a80cffd).\n![Formula for NT-Xent loss. Source: Papers with code \\(CC-BY-SA\\)](../images/000.png)\nFormula for NT-Xent loss. Source: [Papers with code](https://paperswithcode.com/method/nt-xent) (CC-BY-SA)\n* * *\n## Introduction\nRecent advances in [self-supervised learning](https://neptune.ai/blog/self-supervised-learning) and [contrastive learning](https://towardsdatascience.com/understanding-contrastive-learning-d5b19fd96607) have excited researchers and practitioners in Machine Learning (ML) to explore this space with renewed interest.\nIn particular, the [SimCLR](https://arxiv.org/pdf/2002.05709.pdf) paper that presents a simple framework for contrastive learning of visual representations has gained a lot of attention in the self-supervised and contrastive learning space.\nThe central idea behind the paper is very simple - allow the model to learn if a pair of images were derived from the same or different initial image.\n![Figure 1: The high-level idea behind SimCLR. Source: SimCLR paper](../images/001.png)\nFigure 1: The high-level idea behind SimCLR. Source: [SimCLR paper](https://arxiv.org/pdf/2002.05709.pdf)\nThe SimCLR approach encodes each input image _**i**_ as a feature vector _**zi**_. There are 2 cases to consider:\n  1. **Positive Pairs** : The same image is augmented using a different set of augmentations, and the resulting feature vectors _**zi**_ and _**zj**_ are compared. These feature vectors are forced to be similar by the loss function.\n  2. **Negative Pairs** : Different images are augmented using a different set of augmentations, and the resulting feature vectors _**zi**_ and _**zk**_ are compared. These feature vectors are forced to be dissimilar by the loss function.\n\n\nThe rest of this article will focus on explaining and understanding this loss function, and its efficient implementation using PyTorch.\n* * *\n## The NT-Xent Loss\nAt a high level, the contrastive learning model is fed 2N images, originating from N underlying images. Each of the N underlying images is augmented using a random set of image augmentations to produce 2 augmented images. This is how we end up with 2N images in a single train batch fed to the model.\n![Figure 2: A batch of 6 images in a single training batch for contrastive learning. The number below each image is the index of that image in the input batch when fed into a contrastive learning model. Image Source: Oxford Visual Geometry Group \\(CC-SA\\).](../images/002.png)\nFigure 2: A batch of 6 images in a single training batch for contrastive learning. The number below each image is the index of that image in the input batch when fed into a contrastive learning model. Image Source: [Oxford Visual Geometry Group](https://www.robots.ox.ac.uk/~vgg/data/pets/) (CC-SA).\nIn the following sections, we will dive deep into the following aspects of the NT-Xent loss.\n  1. [The effect of temperature on SoftMax and Sigmoid](https://towardsdatascience.com/nt-xent-normalized-temperature-scaled-cross-entropy-loss-explained-and-implemented-in-pytorch-cc081f69848/#8cb8)\n  2. [A simple and intuitive interpretation of the NT-Xent loss](https://towardsdatascience.com/nt-xent-normalized-temperature-scaled-cross-entropy-loss-explained-and-implemented-in-pytorch-cc081f69848/#40d2)\n  3. [A step-by-step implementation of NT-Xent in PyTorch](https://towardsdatascience.com/nt-xent-normalized-temperature-scaled-cross-entropy-loss-explained-and-implemented-in-pytorch-cc081f69848/#29d4)\n  4. [Motivating the need for a multi-label loss function (NT-BXent)](https://towardsdatascience.com/nt-xent-normalized-temperature-scaled-cross-entropy-loss-explained-and-implemented-in-pytorch-cc081f69848/#f004)\n  5. [A step-by-step implementation of NT-BXent in PyTorch](https://towardsdatascience.com/nt-xent-normalized-temperature-scaled-cross-entropy-loss-explained-and-implemented-in-pytorch-cc081f69848/#242d)\n\n\nAll the code for steps 2–5 can be found in [[this notebook](https://github.com/dhruvbird/ml-notebooks/blob/main/nt-xent-loss/SoftMax%20and%20Sigmoid%20with%20temperature.ipynb)](https://github.com/dhruvbird/ml-notebooks/blob/main/nt-xent-loss/NT-Xent%20Loss.ipynb). The code for step-1 can be found in this notebook.\n* * *\n### The effect of temperature on SoftMax and Sigmoid\nTo understand all the moving parts of the contrastive loss function we'll be studying in this article, we need to first understand the effect of temperature on the SoftMax and Sigmoid activation functions.\nTypically, temperature scaling is applied to the input to SoftMax or Sigmoid to either smooth out or accentuate the output of those activation functions. The input logits are divided by the temperature before passing into the activation functions. You can find all the code for this section in [this notebook](https://github.com/dhruvbird/ml-notebooks/blob/main/nt-xent-loss/SoftMax%20and%20Sigmoid%20with%20temperature.ipynb).\n**SoftMax** : For SoftMax, a high temperature reduces the variance in the output distribution which results in softening of the labels. A low temperature increases the variance in the output distribution and makes the maximum value stand out over the other values. See the charts below for the effect of temperature on SoftMax when fed with the input tensor [0.1081, 0.4376, 0.7697, 0.1929, 0.3626, 2.8451].\n![Figure 3: Effect of temperature on SoftMax. Source: Author\\(s\\)](../images/003.png)\nFigure 3: Effect of temperature on SoftMax. Source: Author(s)\n**Sigmoid** : For Sigmoid, a high-temperature results in an output distribution that is pulled towards 0.0, whereas a low temperature stretches the inputs to higher values, stretching the outputs to be closer to either 0.0 or 1.0 depending on the unsigned magnitude of the input.\n![Figure 4: Effect of temperature on Sigmoid. Source: Author\\(s\\)](../images/004.png)\nFigure 4: Effect of temperature on Sigmoid. Source: Author(s)\nNow that we understand the effect of various temperature values on the SoftMax and Sigmoid functions, let's see how this applies to our understanding of the NT-Xent loss.\n* * *\n### Interpreting the NT-Xent loss\nThe NT-Xent loss is understood by understanding the individual terms in the name of this loss.\n  1. Normalized: Cosine similarity produces a normalized score in the range [-1.0 to +1.0]\n  2. Temperature-scaled: The all-pairs cosine similarity is scaled by a temperature before computing the cross-entropy loss\n  3. Cross-entropy loss: The underlying loss is a multi-class (single-label) cross-entropy loss\n\n\nAs mentioned above, we assume that for a batch of size 2N, the feature vectors at the following indices represent positive pairs (0, 1), (2, 3), (4, 5), (6, 7), ... and the rest of the combinations represent negative pairs. This is an important factor to keep in mind throughout the interpretation of the NT-Xent loss as it relates to SimCLR.\nNow that we understand what the terms mean in the context of the NT-Xent loss, let's take a look at the mechanical steps needed to compute the NT-Xent loss on a batch of feature vectors.\n  1. The all-pairs Cosine Similarity score is computed for each of the 2N vectors produced by the SimCLR model. This results in (2N)² similarity scores represented as a 2N x 2N matrix\n  2. Comparison results between the same value (i, i) are discarded (since a distribution is perfectly similar to itself and can't possibly allow the model to learn anything useful)\n  3. Each value (cosine similarity) is scaled by a temperature parameter 𝜏 (which is a hyper-parameter)\n  4. Cross-entropy loss is applied to each row of the resulting matrix above. The following paragraph explains more in detail\n  5. Typically, the mean of these losses (one loss per element in a batch) is used for backpropagation\n\n\nThe way that the cross-entropy loss is used here is semantically slightly different from how it's used in standard classification tasks. In classification tasks, a final \"classification head\" is trained to produce a one-hot-probability vector for each input, and we compute the cross-entropy loss on that one-hot-probability vector since we're effectively computing the difference between 2 distributions. [This video](https://www.youtube.com/watch?v=Pwgpl9mKars) explains the concept of cross-entropy loss beautifully. In the NT-Xent loss, there isn't a 1:1 correspondence between a trainable layer and the output distribution. Instead, a feature vector is computed for each input, and we then compute the cosine similarity between every pair of feature vectors. The trick here is that since each image is similar to exactly 1 other image in the input batch (positive pair) (if we ignore the similarity of a feature vector with itself), we can consider this to be a classification-like setting where the probability distribution of the similarity probability between images represents a classification task where one of them will be close to 1.0 and the rest will be close to 0.0.\nNow that we have a solid overall understanding of the NT-Xent loss, we should be in great shape to implement these ideas in PyTorch. Let's get going!\n* * *\n### Implementation of NT-Xent loss in PyTorch\nAll the code in this section can be found in [this notebook](https://github.com/dhruvbird/ml-notebooks/blob/main/nt-xent-loss/NT-Xent%20Loss.ipynb).\n**Code Reuse** : Many [implementations](https://github.com/KevinMusgrave/pytorch-metric-learning/blob/master/src/pytorch_metric_learning/losses/ntxent_loss.py) of the NT-Xent loss seen online implement all the operations from scratch. Furthermore, some of them implement the loss function inefficiently, preferring to use [for loops instead of GPU parallelism](https://stackoverflow.com/questions/62793043/tensorflow-implementation-of-nt-xent-contrastive-loss-function). Instead, we will use a different approach. We'll implement this loss in terms of the standard cross-entropy loss that PyTorch already provides. To do this, we need to massage the predictions and ground-truth labels in a format that cross_entropy can accept. Let's see how to do this below.\n**Predictions Tensor** : First, we need to create a PyTorch tensor that will represent the output from our contrastive learning model. Let's assume that our batch size is 8 (2N=8), and our feature vectors have 2 dimensions (2 values). We'll call our input variable _\"x\"_.\npython\n\n```\nx = torch.randn(8, 2)\n```\n\n**Cosine Similarity** : Next, we'll compute the all-pairs cosine similarity between every feature vector in this batch and store the result in the variable named _\"xcs\"_. If the line below seems confusing, please read the details on [this page](https://medium.com/@dhruvbird/all-pairs-cosine-similarity-in-pytorch-867e722c8572). This is the \"normalize\" step.\npython\n\n```\nxcs = F.cosine_similarity(x[None,:,:], x[:,None,:], dim=-1)\n```\n\nAs mentioned above, we need to ignore the self-similarity score of every feature vector since it doesn't contribute to the model's learning and will be an unnecessary nuisance later on when we want to compute the cross-entropy loss. For this purpose, we'll define a variable _\"eye\"_ which is a matrix with the elements on the principal diagonal having a value of 1.0 and the rest being 0.0. We can create such a matrix using the following command.\npython\n\n```\neye = torch.eye(8)\n```\n\nNow let's convert this into a boolean matrix so that we can index into the _\"xcs\"_ variable using this mask matrix.\npython\n\n```\neye = eye.bool()\n```\n\nLet's clone the tensor _\"xcs\"_ into a tensor named _\"y\"_ so that we can reference the \"xcs\" tensor later.\npython\n\n```\ny = xcs.clone()\n```\n\nNow, we will set the values along the principal diagonal of the all-pairs cosine similarity matrix to _-inf_ so that when we compute the softmax on each row, this value will contribute nothing.\npython\n\n```\ny[eye] = float(\"-inf\")\n```\n\nThe tensor _\"y\"_ scaled by a temperature parameter will be one of the inputs (predictions) to the[ cross-entropy loss API in PyTorch](https://pytorch.org/docs/stable/generated/torch.nn.functional.cross_entropy.html#torch.nn.functional.cross_entropy). Next, we need to compute the ground-truth labels (target) that we need to feed to the cross-entropy loss API.\n**Ground Truth labels (Target tensor)** : For the example we are using (2N=8), this is what the ground-truth tensor should look like.\n> tensor([1, 0, 3, 2, 5, 4, 7, 6])\nThat's because the following index pairs in the tensor _\"y\"_ contain positive pairs.\n> (0, 1), (1, 0)\n> (2, 3), (3, 2)\n> (4, 5), (5, 4)\n> (6, 7), (7, 6)\nTo interpret the index pairs above, we look at a single example. The pair (4, 5) means that column 5 at row 4 is supposed to be set to 1.0 (positive pair), which is what the tensor above is also saying. Great!\nTo create the tensor above, we can use the following PyTorch code, which stores the ground-truth labels in the variable _\"target\"_.\npython\n\n```\ntarget = torch.arange(8)\ntarget[0::2] += 1\ntarget[1::2] -= 1\n```\n\n**cross-entropy Loss** : We have all the ingredients we need to compute our loss! The only thing that remains to be done is to call the cross_entropy API in PyTorch.\npython\n\n```\nloss = F.cross_entropy(y / temperature, target, reduction=\"mean\")\n```\n\nThe variable \"loss\" now contains the computed NT-Xent loss. Let's wrap all the code in a single python function below.\npython\n\n```\ndef nt_xent_loss(x, temperature):\n  assert len(x.size()) == 2\n\n  # Cosine similarity\n  xcs = F.cosine_similarity(x[None,:,:], x[:,None,:], dim=-1)\n  xcs[torch.eye(x.size(0)).bool()] = float(\"-inf\")\n\n  # Ground truth labels\n  target = torch.arange(8)\n  target[0::2] += 1\n  target[1::2] -= 1\n\n  # Standard cross-entropy loss\n  return F.cross_entropy(xcs / temperature, target, reduction=\"mean\")\n```\n\nThe code above works as long as each feature vector has exactly one positive pair in the batch when training our contrastive learning model. Let's take a look at how to handle multiple positive pairs in a contrastive learning task.\n* * *\n### A multi-label loss for contrastive learning: NT-BXent\nIn the SimCLR paper, every image _**i**_ has exactly 1 similar pair at index _**j**_. This makes cross-entropy loss a perfect choice for the task since it resembles a multi-class problem. Instead, if we have M > 2 augmentations of the same image fed into the contrastive learning model's single training batch, then each batch would have image M-1 similar pairs for image _**i**_. This task would resemble a multi-label problem.\nThe obvious choice would be to replace _cross-entropy loss_ with _binary cross-entropy loss_. Hence the name NT-BXent loss, which stands for Normalized Temperature-scaled Binary cross-entropy Loss.\nThe formulation below shows the loss _**Li**_ for the element _**i**_. The σ in the formula below stands for the [Sigmoid function](https://en.wikipedia.org/wiki/Sigmoid_function).\n![Figure 5: Formulation for the NT-BXent loss. Image source: Author\\(s\\) of this article](../images/005.png)\nFigure 5: Formulation for the NT-BXent loss. Image source: Author(s) of this article\nTo avoid the class imbalance problem, we weigh the positive and negative pairs by the inverse of the number of positive and negative pairs in our mini-batch. The final loss in the mini-batch used for backpropagation will be the mean of the losses of each sample in our mini-batch.\nNext, let's focus our attention on our implementation of the NT-BXent loss in PyTorch.\n* * *\n### Implementation of NT-BXent loss in PyTorch\nAll the code in this section can be found in [this notebook](https://github.com/dhruvbird/ml-notebooks/blob/main/nt-xent-loss/NT-Xent%20Loss.ipynb).\n**Code Reuse** : Similar to our implementation of the NT-Xent loss, we shall re-use the Binary Cross-entropy (BCE) loss method provided by PyTorch. The setup of our ground-truth labels will be similar to that of a multi-label classification problem where BCE loss is used.\n**Predictions Tensor** : We'll use the same (8, 2) predictions tensor as we used for the implementation of the NT-Xent loss.\npython\n\n```\nx = torch.randn(8, 2)\n```\n\n**Cosine Similarity** : Since the input tensor _**x**_ is same, the all-pairs cosine similarity tensor _**xcs**_ will also be the same. Please see [this page](https://medium.com/@dhruvbird/all-pairs-cosine-similarity-in-pytorch-867e722c8572) for a detailed explanation of what the line below does.\npython\n\n```\nxcs = F.cosine_similarity(x[None,:,:], x[:,None,:], dim=-1)\n```\n\nTo ensure that the loss from the element at position _**(i, i)**_ is _**0**_ , we'll need to perform some gymnastics to have our _**xcs**_ tensor contain a value _**1**_ at every index _**(i, i)**_ after Sigmoid is applied to it. Since we'll be using BCE Loss, we will mark the self-similarity score of every feature vector with the value _**infinity**_ in tensor _**xcs**_. That's because applying the sigmoid function on the _**xcs**_ tensor, will convert infinity to the value _**1**_ , and we will set up our ground-truth labels so that every position _**(i, i)**_ in the ground-truth labels has the value _**1**_.\nLet's create a masking tensor that has the value _**True**_ along the principal diagonal (_**xcs**_ has self-similarity scores along the principal diagonal), and _**False**_ everywhere else.\npython\n\n```\neye = torch.eye(8).bool()\n```\n\nLet's clone the tensor _\"xcs\"_ into a tensor named _\"y\"_ so that we can reference the _\"xcs\"_ tensor later.\npython\n\n```\ny = xcs.clone()\n```\n\nNow, we will set the values along the principal diagonal of the all-pairs cosine similarity matrix to _infinity_ so that when we compute the sigmoid on each row, we get 1 in these positions.\npython\n\n```\ny[eye] = float(\"inf\")\n```\n\nThe tensor _\"y\"_ scaled by a temperature parameter will be one of the inputs (predictions) to the [BCE loss API](https://pytorch.org/docs/stable/generated/torch.nn.functional.binary_cross_entropy.html) in PyTorch. Next, we need to compute the ground-truth labels (target) that we need to feed to the BCE loss API.\n**Ground Truth labels (Target tensor)** : We will expect the user to pass to us the pair of all (x, y) index pairs which contain positive examples. This is a departure for what we did for the NT-Xent loss, since the positive pairs were implicit, whereas here, the positive pairs are explicit.\nIn addition to the locations provided by the user, we will set all the diagonal elements as positive pairs as explained above. We will use the PyTorch tensor indexing API to pluck out all the elements at those locations and set them to 1, whereas the rest are initialized to 0.\npython\n\n```\ntarget = torch.zeros(8, 8)\npos_indices = torch.tensor([\n  (0, 0), (0, 2), (0, 4),\n  (1, 4), (1, 6), (1, 1),\n  (2, 3),\n  (3, 7),\n  (4, 3),\n  (7, 6),\n])\n# Add indexes of the principal diagonal as positive indexes.\n# This will be useful since we will use the BCELoss in PyTorch,\n# which will expect a value for the elements on the principal\n# diagonal as well.\npos_indices = torch.cat([pos_indices, torch.arange(8).reshape(8, 1).expand(-1, 2)], dim=0)\n# Set the values in the target vector to 1.\ntarget[pos_indices[:,0], pos_indices[:,1]] = 1\n```\n\n**Binary cross-entropy (BCE) Loss** : Unlike the NT-Xent loss, we can't simply call the torch.nn.functional.binary_cross_entropy_function, since we want to weigh the positive and negative loss based on how many positive and negative pairs the element at index i has in the current mini-batch.\nThe first step though is to compute the element-wise BCE loss.\npython\n\n```\ntemperature = 0.1\nloss = F.binary_cross_entropy((y / temperature).sigmoid(), target, reduction=\"none\")\n```\n\nWe'll create a binary mask of positive and negative pairs and then create 2 tensors, loss_pos and loss_neg that contain only those elements from the computed loss that correspond to the positive and negative pairs.\npython\n\n```\ntarget_pos = target.bool()\ntarget_neg = ~target_pos\n# loss_pos and loss_neg below contain non-zero values only for those elements\n# that are positive pairs and negative pairs respectively.\nloss_pos = torch.zeros(x.size(0), x.size(0)).masked_scatter(target_pos, loss[target_pos])\nloss_neg = torch.zeros(x.size(0), x.size(0)).masked_scatter(target_neg, loss[target_neg])\n```\n\nNext, we'll sum up the positive and negative pair loss (separately) corresponding to each element i in our mini-batch.\npython\n\n```\n# loss_pos and loss_neg now contain the sum of positive and negative pair losses\n# as computed relative to the i'th input.\nloss_pos = loss_pos.sum(dim=1)\nloss_neg = loss_neg.sum(dim=1)\n```\n\nTo perform weighting, we need to track the number of positive and negative pairs corresponding to each element i in our mini-batch. Tensors _\"num _pos\"_ and _\"num _neg\"_ will store these values.\npython\n\n```\n# num_pos and num_neg below contain the number of positive and negative pairs\n# computed relative to the i'th input. In an actual setting, this number should\n# be the same for every input element, but we let it vary here for maximum\n# flexibility.\nnum_pos = target.sum(dim=1)\nnum_neg = target.size(0) - num_pos\n```\n\nWe have all the ingredients we need to compute our loss! The only thing that we need to do is weigh the positive and negative loss by the number of positive and negative pairs, and then average the loss across the mini-batch.\npython\n\n```\ndef nt_bxent_loss(x, pos_indices, temperature):\n    assert len(x.size()) == 2\n\n    # Add indexes of the principal diagonal elements to pos_indices\n    pos_indices = torch.cat([\n        pos_indices,\n        torch.arange(x.size(0)).reshape(x.size(0), 1).expand(-1, 2),\n    ], dim=0)\n\n    # Ground truth labels\n    target = torch.zeros(x.size(0), x.size(0))\n    target[pos_indices[:,0], pos_indices[:,1]] = 1.0\n\n    # Cosine similarity\n    xcs = F.cosine_similarity(x[None,:,:], x[:,None,:], dim=-1)\n    # Set logit of diagonal element to \"inf\" signifying complete\n    # correlation. sigmoid(inf) = 1.0 so this will work out nicely\n    # when computing the Binary cross-entropy Loss.\n    xcs[torch.eye(x.size(0)).bool()] = float(\"inf\")\n\n    # Standard binary cross-entropy loss. We use binary_cross_entropy() here and not\n    # binary_cross_entropy_with_logits() because of\n    # https://github.com/pytorch/pytorch/issues/102894\n    # The method *_with_logits() uses the log-sum-exp-trick, which causes inf and -inf values\n    # to result in a NaN result.\n    loss = F.binary_cross_entropy((xcs / temperature).sigmoid(), target, reduction=\"none\")\n\n    target_pos = target.bool()\n    target_neg = ~target_pos\n\n    loss_pos = torch.zeros(x.size(0), x.size(0)).masked_scatter(target_pos, loss[target_pos])\n    loss_neg = torch.zeros(x.size(0), x.size(0)).masked_scatter(target_neg, loss[target_neg])\n    loss_pos = loss_pos.sum(dim=1)\n    loss_neg = loss_neg.sum(dim=1)\n    num_pos = target.sum(dim=1)\n    num_neg = x.size(0) - num_pos\n\n    return ((loss_pos / num_pos) + (loss_neg / num_neg)).mean()\n\npos_indices = torch.tensor([\n    (0, 0), (0, 2), (0, 4),\n    (1, 4), (1, 6), (1, 1),\n    (2, 3),\n    (3, 7),\n    (4, 3),\n    (7, 6),\n])\nfor t in (0.01, 0.1, 1.0, 10.0, 20.0):\n    print(f\"Temperature: {t:5.2f}, Loss: {nt_bxent_loss(x, pos_indices, temperature=t)}\")\n```\n\nPrints.\n> Temperature: 0.01, Loss: 62.898780822753906\n> Temperature: 0.10, Loss: 4.851151943206787\n> Temperature: 1.00, Loss: 1.0727109909057617\n> Temperature: 10.00, Loss: 0.9827173948287964\n> Temperature: 20.00, Loss: 0.982099175453186\n* * *\n## Conclusion\nSelf-supervised learning is an upcoming field in deep learning and allows one to train models on unlabeled data. This technique lets us work around the requirement of labeled data at scale.\nIn this article, we learned about loss functions for contrastive learning. The first one, named NT-Xent loss, is used for learning on a single positive pair per input in a mini-batch. We introduced the NT-BXent loss which is used for learning on multiple (> 1) positive pairs per input in a mini-batch. We learned to interpret them intuitively, building on our knowledge of cross-entropy loss and binary cross-entropy loss. Finally, we implemented them both efficiently in PyTorch.\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-a3403563a948ce1eab7b.jpeg)\nWritten By\n## [Dhruv Matani](https://towardsdatascience.com/author/dhruvbird/)\n[See all from Dhruv Matani](https://towardsdatascience.com/author/dhruvbird/)\n[Binary Cross Entropy](https://towardsdatascience.com/tag/binary-cross-entropy/)[Cross Entropy](https://towardsdatascience.com/tag/cross-entropy/)[Loss Function](https://towardsdatascience.com/tag/loss-function/)[Pytorch](https://towardsdatascience.com/tag/pytorch/)[Self Supervised Learning](https://towardsdatascience.com/tag/self-supervised-learning/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fnt-xent-normalized-temperature-scaled-cross-entropy-loss-explained-and-implemented-in-pytorch-cc081f69848%2F&title=NT-Xent%20\\(Normalized%20Temperature-Scaled%20Cross-Entropy\\)%20Loss%20Explained%20and%20Implemented%20in%20PyTorch)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fnt-xent-normalized-temperature-scaled-cross-entropy-loss-explained-and-implemented-in-pytorch-cc081f69848%2F&title=NT-Xent%20\\(Normalized%20Temperature-Scaled%20Cross-Entropy\\)%20Loss%20Explained%20and%20Implemented%20in%20PyTorch)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fnt-xent-normalized-temperature-scaled-cross-entropy-loss-explained-and-implemented-in-pytorch-cc081f69848%2F&text=NT-Xent%20\\(Normalized%20Temperature-Scaled%20Cross-Entropy\\)%20Loss%20Explained%20and%20Implemented%20in%20PyTorch)\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/006.jpeg)](https://towardsdatascience.com/understanding-entropy-2ee52b387f8c/)\n## [An Intuitive Guide To Entropy](https://towardsdatascience.com/understanding-entropy-2ee52b387f8c/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nUnderstanding why entropy is a measure of chaos\n[Aayush Agarwal](https://towardsdatascience.com/author/ayush2991/)\nApril 29, 20225 min read\n  * [![](../images/007.jpg)](https://towardsdatascience.com/sklearn-tutorial-module-1-f31b3964a3b4/)\n## [Sklearn Tutorial: Module 1](https://towardsdatascience.com/sklearn-tutorial-module-1-f31b3964a3b4/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nI took the official sklearn MOOC tutorial. Here are my takeaways.\n[Yoann Mocquin](https://towardsdatascience.com/author/mocquin/)\nNovember 22, 202310 min read\n  * [![](../images/008.jpg)](https://towardsdatascience.com/how-to-select-loss-function-and-activation-function-for-classification-problems-b7f32c724507/)\n## [How to Select Loss Function and Activation Function for Classification Problems](https://towardsdatascience.com/how-to-select-loss-function-and-activation-function-for-classification-problems-b7f32c724507/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nUnderstanding how to choose activation function in the final layer and loss function for neural network\n[Ibrahim Kovan](https://towardsdatascience.com/author/ibrahimkovan/)\nApril 14, 20226 min read\n  * [![](../images/009.jpg)](https://towardsdatascience.com/yolov3-paper-walkthrough-even-better-but-not-that-much/)\n## [YOLOv3 Paper Walkthrough: Even Better, But Not That Much](https://towardsdatascience.com/yolov3-paper-walkthrough-even-better-but-not-that-much/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nA PyTorch implementation on the YOLOv3 architecture from scratch\n[Muhammad Ardi Putra](https://towardsdatascience.com/author/muhammad_ardi/)\nMarch 2, 202623 min read\n  * [![](../images/010.png)](https://towardsdatascience.com/image-clustering-implementation-with-pytorch-587af1d14123/)\n## [Image Clustering Implementation with PyTorch](https://towardsdatascience.com/image-clustering-implementation-with-pytorch-587af1d14123/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nLine-by-Line Tutorial Implementation of a Deep Convolutional Neural Network for the Clustering of Mushroom Photos\n[Anders Ohrn](https://towardsdatascience.com/author/ajohrn/)\nNovember 9, 202018 min read\n  * [![](../images/011.png)](https://towardsdatascience.com/from-supervised-to-unsupervised-learning-a-paradigm-shift-in-computer-vision-ae19ada1064d/)\n## [From Supervised To Unsupervised Learning: A Paradigm Shift In Computer Vision](https://towardsdatascience.com/from-supervised-to-unsupervised-learning-a-paradigm-shift-in-computer-vision-ae19ada1064d/)\n[](https://towardsdatascience.com/nt-xent-normalized-temperature-scaled-cross-entropy-loss-explained-and-implemented-in-pytorch-cc081f69848/)\nSlowly removing the injection of human knowledge from the training process\n[Leon Sick](https://towardsdatascience.com/author/leon.sick/)\nJanuary 1, 20226 min read\n  * [![](../images/012.jpg)](https://towardsdatascience.com/how-to-create-more-efficient-deep-learning-models-c27bf49e070c/)\n## [How to create more Efficient Deep Learning Models](https://towardsdatascience.com/how-to-create-more-efficient-deep-learning-models-c27bf49e070c/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nIn this article I am going to discuss several important approaches and techniques that can help improve the efficiency of neural networks.\n[Tudor Surdoiu](https://towardsdatascience.com/author/dacus-augustus/)\nJuly 1, 20216 min read\n  * [![](../images/013.jpeg)](https://towardsdatascience.com/optimizing-data-transfer-in-distributed-ai-ml-training-workloads/)\n## [Optimizing Data Transfer in Distributed AI/ML Training Workloads](https://towardsdatascience.com/optimizing-data-transfer-in-distributed-ai-ml-training-workloads/)\n[Data Engineering](https://towardsdatascience.com/category/data-science/data-engineering/)\nA deep dive on data transfer bottlenecks, their identification, and their resolution with the help of NVIDIA Nsight™ Systems – part 3\n[Chaim Rand](https://towardsdatascience.com/author/chaimrand/)\nJanuary 23, 202613 min read\n  * [![](../images/014.jpeg)](https://towardsdatascience.com/self-supervised-learning-methods-for-computer-vision-c25ec10a91bd/)\n## [Self-Supervised Learning Methods for Computer Vision](https://towardsdatascience.com/self-supervised-learning-methods-for-computer-vision-c25ec10a91bd/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nWhat is Self-supervised Learning?\n[Nilesh Vijayrania](https://towardsdatascience.com/author/nilesh0109/)\nDecember 15, 20209 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": "NT-Xent (Normalized Temperature-Scaled Cross-Entropy) Loss Explained and Implemented in PyTorch | Towards Data Science",
    "description": "An intuitive explanation of the NT-Xent loss with a step-by-step explanation of the operation and our implementation in PyTorch",
    "keywords": null,
    "author": "Dhruv Matani",
    "og:locale": "en_US",
    "og:type": "article",
    "og:title": "NT-Xent (Normalized Temperature-Scaled Cross-Entropy) Loss Explained and Implemented in PyTorch",
    "og:description": "An intuitive explanation of the NT-Xent loss with a step-by-step explanation of the operation and our implementation in PyTorch",
    "og:url": "https://towardsdatascience.com/nt-xent-normalized-temperature-scaled-cross-entropy-loss-explained-and-implemented-in-pytorch-cc081f69848/",
    "og:site_name": "Towards Data Science",
    "og:image": "https://assets.insightmediagroup.io/media/wp-content/uploads/2023/06/1bXxtQ57ZoLNduhom2Fp2ew.png",
    "og:image:width": "1189",
    "og:image:height": "1369",
    "og:image:type": "image/png",
    "twitter:card": "summary_large_image",
    "twitter:site": "@TDataScience",
    "twitter:creator": "@TDataScience",
    "twitter:label1": "Written by",
    "twitter:data1": "Dhruv Matani",
    "twitter:label2": "Est. reading time",
    "twitter:data2": "14 min read",
    "article:published_time": "2023-06-13T17:46:41.000Z",
    "article:modified_time": "2023-06-13T17:46:41.000Z",
    "article:author": "https://towardsdatascience.com/author/dhruvbird/"
  },
  "paywall": {
    "listed_paid": false,
    "detected": false,
    "marker": "",
    "public_only": false,
    "policy": "付费/会员内容只保留页面公开可见部分，不绕过付费墙"
  },
  "crawl": {
    "success": true,
    "status_code": 202,
    "error": ""
  },
  "code_blocks": [
    {
      "language": "txt",
      "file": "attachments/859dfd0f4c0e/code/block_000.txt",
      "chars": 22
    },
    {
      "language": "txt",
      "file": "attachments/859dfd0f4c0e/code/block_001.txt",
      "chars": 60
    },
    {
      "language": "txt",
      "file": "attachments/859dfd0f4c0e/code/block_002.txt",
      "chars": 19
    },
    {
      "language": "txt",
      "file": "attachments/859dfd0f4c0e/code/block_003.txt",
      "chars": 17
    },
    {
      "language": "txt",
      "file": "attachments/859dfd0f4c0e/code/block_004.txt",
      "chars": 16
    },
    {
      "language": "txt",
      "file": "attachments/859dfd0f4c0e/code/block_005.txt",
      "chars": 23
    },
    {
      "language": "txt",
      "file": "attachments/859dfd0f4c0e/code/block_006.txt",
      "chars": 61
    },
    {
      "language": "txt",
      "file": "attachments/859dfd0f4c0e/code/block_007.txt",
      "chars": 66
    },
    {
      "language": "txt",
      "file": "attachments/859dfd0f4c0e/code/block_008.txt",
      "chars": 393
    },
    {
      "language": "txt",
      "file": "attachments/859dfd0f4c0e/code/block_009.txt",
      "chars": 22
    },
    {
      "language": "txt",
      "file": "attachments/859dfd0f4c0e/code/block_010.txt",
      "chars": 60
    },
    {
      "language": "txt",
      "file": "attachments/859dfd0f4c0e/code/block_011.txt",
      "chars": 26
    },
    {
      "language": "txt",
      "file": "attachments/859dfd0f4c0e/code/block_012.txt",
      "chars": 16
    },
    {
      "language": "txt",
      "file": "attachments/859dfd0f4c0e/code/block_013.txt",
      "chars": 22
    },
    {
      "language": "txt",
      "file": "attachments/859dfd0f4c0e/code/block_014.txt",
      "chars": 540
    },
    {
      "language": "txt",
      "file": "attachments/859dfd0f4c0e/code/block_015.txt",
      "chars": 103
    },
    {
      "language": "txt",
      "file": "attachments/859dfd0f4c0e/code/block_016.txt",
      "chars": 369
    },
    {
      "language": "txt",
      "file": "attachments/859dfd0f4c0e/code/block_017.txt",
      "chars": 185
    },
    {
      "language": "txt",
      "file": "attachments/859dfd0f4c0e/code/block_018.txt",
      "chars": 311
    },
    {
      "language": "txt",
      "file": "attachments/859dfd0f4c0e/code/block_019.txt",
      "chars": 1861
    }
  ],
  "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:08:01Z"
    },
    {
      "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:08:01Z"
    },
    {
      "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:08:01Z"
    },
    {
      "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:08:01Z"
    }
  ],
  "audio": [],
  "videos": [
    {
      "url": "https://www.youtube.com/watch?v=Pwgpl9mKars",
      "status": "ok",
      "local_path": "attachments/859dfd0f4c0e/videos/repair-Pwgpl9mKars.mp4",
      "bytes": 9041770,
      "valid": true,
      "height": 1080,
      "width": 1920,
      "duration": "323.741000"
    },
    {
      "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/author/dhruvbird/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/understanding-contrastive-learning-d5b19fd96607"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/nt-xent-normalized-temperature-scaled-cross-entropy-loss-explained-and-implemented-in-pytorch-cc081f69848/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/binary-cross-entropy/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/cross-entropy/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/loss-function/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/pytorch/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/tag/self-supervised-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/understanding-entropy-2ee52b387f8c/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/category/artificial-intelligence/machine-learning/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/ayush2991/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/sklearn-tutorial-module-1-f31b3964a3b4/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/author/mocquin/"
    },
    {
      "type": "internal",
      "href": "https://towardsdatascience.com/how-to-select-loss-function-and-activation-function-for-classification-problems-b7f32c724507/"
    },
    {
      "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://medium.com/u/1e659a80cffd"
    },
    {
      "type": "external",
      "href": "https://paperswithcode.com/method/nt-xent"
    },
    {
      "type": "external",
      "href": "https://neptune.ai/blog/self-supervised-learning"
    },
    {
      "type": "external",
      "href": "https://arxiv.org/pdf/2002.05709.pdf"
    },
    {
      "type": "external",
      "href": "https://www.robots.ox.ac.uk/~vgg/data/pets/"
    },
    {
      "type": "external",
      "href": "https://github.com/dhruvbird/ml-notebooks/blob/main/nt-xent-loss/NT-Xent%20Loss.ipynb"
    },
    {
      "type": "external",
      "href": "https://github.com/dhruvbird/ml-notebooks/blob/main/nt-xent-loss/SoftMax%20and%20Sigmoid%20with%20temperature.ipynb"
    },
    {
      "type": "external",
      "href": "https://www.youtube.com/watch?v=Pwgpl9mKars"
    },
    {
      "type": "external",
      "href": "https://github.com/KevinMusgrave/pytorch-metric-learning/blob/master/src/pytorch_metric_learning/losses/ntxent_loss.py"
    },
    {
      "type": "external",
      "href": "https://stackoverflow.com/questions/62793043/tensorflow-implementation-of-nt-xent-contrastive-loss-function"
    },
    {
      "type": "external",
      "href": "https://medium.com/@dhruvbird/all-pairs-cosine-similarity-in-pytorch-867e722c8572"
    },
    {
      "type": "external",
      "href": "https://pytorch.org/docs/stable/generated/torch.nn.functional.cross_entropy.html"
    },
    {
      "type": "external",
      "href": "https://en.wikipedia.org/wiki/Sigmoid_function"
    },
    {
      "type": "external",
      "href": "https://pytorch.org/docs/stable/generated/torch.nn.functional.binary_cross_entropy.html"
    },
    {
      "type": "external",
      "href": "https://www.facebook.com/sharer/sharer.php?title=NT-Xent+%28Normalized+Temperature-Scaled+Cross-Entropy%29+Loss+Explained+and+Implemented+in+PyTorch&u=https%3A%2F%2Ftowardsdatascience.com%2Fnt-xent-normalized-temperature-scaled-cross-entropy-loss-explained-and-implemented-in-pytorch-cc081f69848%2F"
    },
    {
      "type": "external",
      "href": "https://www.linkedin.com/shareArticle?mini=true&title=NT-Xent+%28Normalized+Temperature-Scaled+Cross-Entropy%29+Loss+Explained+and+Implemented+in+PyTorch&url=https%3A%2F%2Ftowardsdatascience.com%2Fnt-xent-normalized-temperature-scaled-cross-entropy-loss-explained-and-implemented-in-pytorch-cc081f69848%2F"
    },
    {
      "type": "external",
      "href": "https://x.com/share?text=NT-Xent+%28Normalized+Temperature-Scaled+Cross-Entropy%29+Loss+Explained+and+Implemented+in+PyTorch&url=https%3A%2F%2Ftowardsdatascience.com%2Fnt-xent-normalized-temperature-scaled-cross-entropy-loss-explained-and-implemented-in-pytorch-cc081f69848%2F"
    }
  ],
  "repair_version": 2,
  "repaired_at": "2026-10-20T17:33:18Z",
  "source_url": "https://towardsdatascience.com/nt-xent-normalized-temperature-scaled-cross-entropy-loss-explained-and-implemented-in-pytorch-cc081f69848/",
  "delivery_status": "unverified",
  "discovery_status": "http_403",
  "missing_reason": "源页面未重新核验:http_403；已按保留正文补采图片",
  "repair_error": "",
  "actual_video_files": [
    {
      "local_path": "attachments/859dfd0f4c0e/videos/repair-Pwgpl9mKars.mp4",
      "bytes": 9041770,
      "valid": true,
      "height": 1080,
      "width": 1920,
      "duration": "323.741000",
      "status": "ok"
    }
  ],
  "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# NT-Xent (Normalized Temperature-Scaled Cross-Entropy) Loss Explained and Implemented in PyTorch\nAn intuitive explanation of the NT-Xent loss with a step-by-step explanation of the operation and our implementation in PyTorch\n[Dhruv Matani](https://towardsdatascience.com/author/dhruvbird/)\nJune 13, 202314 min read\nCo-authored with [Naresh Singh](https://medium.com/u/1e659a80cffd).\n![Formula for NT-Xent loss. Source: Papers with code \\(CC-BY-SA\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/06/1ocLhrfF9CpucKneGbiVfxw.png)\nFormula for NT-Xent loss. Source: [Papers with code](https://paperswithcode.com/method/nt-xent) (CC-BY-SA)\n* * *\n## Introduction\nRecent advances in [self-supervised learning](https://neptune.ai/blog/self-supervised-learning) and [contrastive learning](https://towardsdatascience.com/understanding-contrastive-learning-d5b19fd96607) have excited researchers and practitioners in Machine Learning (ML) to explore this space with renewed interest.\nIn particular, the [SimCLR](https://arxiv.org/pdf/2002.05709.pdf) paper that presents a simple framework for contrastive learning of visual representations has gained a lot of attention in the self-supervised and contrastive learning space.\nThe central idea behind the paper is very simple - allow the model to learn if a pair of images were derived from the same or different initial image.\n![Figure 1: The high-level idea behind SimCLR. Source: SimCLR paper](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/06/1JTj6w4ybgwM8UT9VvUEjgA.png)\nFigure 1: The high-level idea behind SimCLR. Source: [SimCLR paper](https://arxiv.org/pdf/2002.05709.pdf)\nThe SimCLR approach encodes each input image _**i**_ as a feature vector _**zi**_. There are 2 cases to consider:\n  1. **Positive Pairs** : The same image is augmented using a different set of augmentations, and the resulting feature vectors _**zi**_ and _**zj**_ are compared. These feature vectors are forced to be similar by the loss function.\n  2. **Negative Pairs** : Different images are augmented using a different set of augmentations, and the resulting feature vectors _**zi**_ and _**zk**_ are compared. These feature vectors are forced to be dissimilar by the loss function.\n\n\nThe rest of this article will focus on explaining and understanding this loss function, and its efficient implementation using PyTorch.\n* * *\n## The NT-Xent Loss\nAt a high level, the contrastive learning model is fed 2N images, originating from N underlying images. Each of the N underlying images is augmented using a random set of image augmentations to produce 2 augmented images. This is how we end up with 2N images in a single train batch fed to the model.\n![Figure 2: A batch of 6 images in a single training batch for contrastive learning. The number below each image is the index of that image in the input batch when fed into a contrastive learning model. Image Source: Oxford Visual Geometry Group \\(CC-SA\\).](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/06/06mw1wxsJ-HCmL7hK.png)\nFigure 2: A batch of 6 images in a single training batch for contrastive learning. The number below each image is the index of that image in the input batch when fed into a contrastive learning model. Image Source: [Oxford Visual Geometry Group](https://www.robots.ox.ac.uk/~vgg/data/pets/) (CC-SA).\nIn the following sections, we will dive deep into the following aspects of the NT-Xent loss.\n  1. [The effect of temperature on SoftMax and Sigmoid](https://towardsdatascience.com/nt-xent-normalized-temperature-scaled-cross-entropy-loss-explained-and-implemented-in-pytorch-cc081f69848/#8cb8)\n  2. [A simple and intuitive interpretation of the NT-Xent loss](https://towardsdatascience.com/nt-xent-normalized-temperature-scaled-cross-entropy-loss-explained-and-implemented-in-pytorch-cc081f69848/#40d2)\n  3. [A step-by-step implementation of NT-Xent in PyTorch](https://towardsdatascience.com/nt-xent-normalized-temperature-scaled-cross-entropy-loss-explained-and-implemented-in-pytorch-cc081f69848/#29d4)\n  4. [Motivating the need for a multi-label loss function (NT-BXent)](https://towardsdatascience.com/nt-xent-normalized-temperature-scaled-cross-entropy-loss-explained-and-implemented-in-pytorch-cc081f69848/#f004)\n  5. [A step-by-step implementation of NT-BXent in PyTorch](https://towardsdatascience.com/nt-xent-normalized-temperature-scaled-cross-entropy-loss-explained-and-implemented-in-pytorch-cc081f69848/#242d)\n\n\nAll the code for steps 2–5 can be found in [[this notebook](https://github.com/dhruvbird/ml-notebooks/blob/main/nt-xent-loss/SoftMax%20and%20Sigmoid%20with%20temperature.ipynb)](https://github.com/dhruvbird/ml-notebooks/blob/main/nt-xent-loss/NT-Xent%20Loss.ipynb). The code for step-1 can be found in this notebook.\n* * *\n### The effect of temperature on SoftMax and Sigmoid\nTo understand all the moving parts of the contrastive loss function we'll be studying in this article, we need to first understand the effect of temperature on the SoftMax and Sigmoid activation functions.\nTypically, temperature scaling is applied to the input to SoftMax or Sigmoid to either smooth out or accentuate the output of those activation functions. The input logits are divided by the temperature before passing into the activation functions. You can find all the code for this section in [this notebook](https://github.com/dhruvbird/ml-notebooks/blob/main/nt-xent-loss/SoftMax%20and%20Sigmoid%20with%20temperature.ipynb).\n**SoftMax** : For SoftMax, a high temperature reduces the variance in the output distribution which results in softening of the labels. A low temperature increases the variance in the output distribution and makes the maximum value stand out over the other values. See the charts below for the effect of temperature on SoftMax when fed with the input tensor [0.1081, 0.4376, 0.7697, 0.1929, 0.3626, 2.8451].\n![Figure 3: Effect of temperature on SoftMax. Source: Author\\(s\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/06/1bXxtQ57ZoLNduhom2Fp2ew.png)\nFigure 3: Effect of temperature on SoftMax. Source: Author(s)\n**Sigmoid** : For Sigmoid, a high-temperature results in an output distribution that is pulled towards 0.0, whereas a low temperature stretches the inputs to higher values, stretching the outputs to be closer to either 0.0 or 1.0 depending on the unsigned magnitude of the input.\n![Figure 4: Effect of temperature on Sigmoid. Source: Author\\(s\\)](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/06/19qshoOkmDvRw-yqzvGwkSw.png)\nFigure 4: Effect of temperature on Sigmoid. Source: Author(s)\nNow that we understand the effect of various temperature values on the SoftMax and Sigmoid functions, let's see how this applies to our understanding of the NT-Xent loss.\n* * *\n### Interpreting the NT-Xent loss\nThe NT-Xent loss is understood by understanding the individual terms in the name of this loss.\n  1. Normalized: Cosine similarity produces a normalized score in the range [-1.0 to +1.0]\n  2. Temperature-scaled: The all-pairs cosine similarity is scaled by a temperature before computing the cross-entropy loss\n  3. Cross-entropy loss: The underlying loss is a multi-class (single-label) cross-entropy loss\n\n\nAs mentioned above, we assume that for a batch of size 2N, the feature vectors at the following indices represent positive pairs (0, 1), (2, 3), (4, 5), (6, 7), ... and the rest of the combinations represent negative pairs. This is an important factor to keep in mind throughout the interpretation of the NT-Xent loss as it relates to SimCLR.\nNow that we understand what the terms mean in the context of the NT-Xent loss, let's take a look at the mechanical steps needed to compute the NT-Xent loss on a batch of feature vectors.\n  1. The all-pairs Cosine Similarity score is computed for each of the 2N vectors produced by the SimCLR model. This results in (2N)² similarity scores represented as a 2N x 2N matrix\n  2. Comparison results between the same value (i, i) are discarded (since a distribution is perfectly similar to itself and can't possibly allow the model to learn anything useful)\n  3. Each value (cosine similarity) is scaled by a temperature parameter 𝜏 (which is a hyper-parameter)\n  4. Cross-entropy loss is applied to each row of the resulting matrix above. The following paragraph explains more in detail\n  5. Typically, the mean of these losses (one loss per element in a batch) is used for backpropagation\n\n\nThe way that the cross-entropy loss is used here is semantically slightly different from how it's used in standard classification tasks. In classification tasks, a final \"classification head\" is trained to produce a one-hot-probability vector for each input, and we compute the cross-entropy loss on that one-hot-probability vector since we're effectively computing the difference between 2 distributions. [This video](https://www.youtube.com/watch?v=Pwgpl9mKars) explains the concept of cross-entropy loss beautifully. In the NT-Xent loss, there isn't a 1:1 correspondence between a trainable layer and the output distribution. Instead, a feature vector is computed for each input, and we then compute the cosine similarity between every pair of feature vectors. The trick here is that since each image is similar to exactly 1 other image in the input batch (positive pair) (if we ignore the similarity of a feature vector with itself), we can consider this to be a classification-like setting where the probability distribution of the similarity probability between images represents a classification task where one of them will be close to 1.0 and the rest will be close to 0.0.\nNow that we have a solid overall understanding of the NT-Xent loss, we should be in great shape to implement these ideas in PyTorch. Let's get going!\n* * *\n### Implementation of NT-Xent loss in PyTorch\nAll the code in this section can be found in [this notebook](https://github.com/dhruvbird/ml-notebooks/blob/main/nt-xent-loss/NT-Xent%20Loss.ipynb).\n**Code Reuse** : Many [implementations](https://github.com/KevinMusgrave/pytorch-metric-learning/blob/master/src/pytorch_metric_learning/losses/ntxent_loss.py) of the NT-Xent loss seen online implement all the operations from scratch. Furthermore, some of them implement the loss function inefficiently, preferring to use [for loops instead of GPU parallelism](https://stackoverflow.com/questions/62793043/tensorflow-implementation-of-nt-xent-contrastive-loss-function). Instead, we will use a different approach. We'll implement this loss in terms of the standard cross-entropy loss that PyTorch already provides. To do this, we need to massage the predictions and ground-truth labels in a format that cross_entropy can accept. Let's see how to do this below.\n**Predictions Tensor** : First, we need to create a PyTorch tensor that will represent the output from our contrastive learning model. Let's assume that our batch size is 8 (2N=8), and our feature vectors have 2 dimensions (2 values). We'll call our input variable _\"x\"_.\npython\n\n```\nx = torch.randn(8, 2)\n```\n\n**Cosine Similarity** : Next, we'll compute the all-pairs cosine similarity between every feature vector in this batch and store the result in the variable named _\"xcs\"_. If the line below seems confusing, please read the details on [this page](https://medium.com/@dhruvbird/all-pairs-cosine-similarity-in-pytorch-867e722c8572). This is the \"normalize\" step.\npython\n\n```\nxcs = F.cosine_similarity(x[None,:,:], x[:,None,:], dim=-1)\n```\n\nAs mentioned above, we need to ignore the self-similarity score of every feature vector since it doesn't contribute to the model's learning and will be an unnecessary nuisance later on when we want to compute the cross-entropy loss. For this purpose, we'll define a variable _\"eye\"_ which is a matrix with the elements on the principal diagonal having a value of 1.0 and the rest being 0.0. We can create such a matrix using the following command.\npython\n\n```\neye = torch.eye(8)\n```\n\nNow let's convert this into a boolean matrix so that we can index into the _\"xcs\"_ variable using this mask matrix.\npython\n\n```\neye = eye.bool()\n```\n\nLet's clone the tensor _\"xcs\"_ into a tensor named _\"y\"_ so that we can reference the \"xcs\" tensor later.\npython\n\n```\ny = xcs.clone()\n```\n\nNow, we will set the values along the principal diagonal of the all-pairs cosine similarity matrix to _-inf_ so that when we compute the softmax on each row, this value will contribute nothing.\npython\n\n```\ny[eye] = float(\"-inf\")\n```\n\nThe tensor _\"y\"_ scaled by a temperature parameter will be one of the inputs (predictions) to the[ cross-entropy loss API in PyTorch](https://pytorch.org/docs/stable/generated/torch.nn.functional.cross_entropy.html#torch.nn.functional.cross_entropy). Next, we need to compute the ground-truth labels (target) that we need to feed to the cross-entropy loss API.\n**Ground Truth labels (Target tensor)** : For the example we are using (2N=8), this is what the ground-truth tensor should look like.\n> tensor([1, 0, 3, 2, 5, 4, 7, 6])\nThat's because the following index pairs in the tensor _\"y\"_ contain positive pairs.\n> (0, 1), (1, 0)\n> (2, 3), (3, 2)\n> (4, 5), (5, 4)\n> (6, 7), (7, 6)\nTo interpret the index pairs above, we look at a single example. The pair (4, 5) means that column 5 at row 4 is supposed to be set to 1.0 (positive pair), which is what the tensor above is also saying. Great!\nTo create the tensor above, we can use the following PyTorch code, which stores the ground-truth labels in the variable _\"target\"_.\npython\n\n```\ntarget = torch.arange(8)\ntarget[0::2] += 1\ntarget[1::2] -= 1\n```\n\n**cross-entropy Loss** : We have all the ingredients we need to compute our loss! The only thing that remains to be done is to call the cross_entropy API in PyTorch.\npython\n\n```\nloss = F.cross_entropy(y / temperature, target, reduction=\"mean\")\n```\n\nThe variable \"loss\" now contains the computed NT-Xent loss. Let's wrap all the code in a single python function below.\npython\n\n```\ndef nt_xent_loss(x, temperature):\n  assert len(x.size()) == 2\n\n  # Cosine similarity\n  xcs = F.cosine_similarity(x[None,:,:], x[:,None,:], dim=-1)\n  xcs[torch.eye(x.size(0)).bool()] = float(\"-inf\")\n\n  # Ground truth labels\n  target = torch.arange(8)\n  target[0::2] += 1\n  target[1::2] -= 1\n\n  # Standard cross-entropy loss\n  return F.cross_entropy(xcs / temperature, target, reduction=\"mean\")\n```\n\nThe code above works as long as each feature vector has exactly one positive pair in the batch when training our contrastive learning model. Let's take a look at how to handle multiple positive pairs in a contrastive learning task.\n* * *\n### A multi-label loss for contrastive learning: NT-BXent\nIn the SimCLR paper, every image _**i**_ has exactly 1 similar pair at index _**j**_. This makes cross-entropy loss a perfect choice for the task since it resembles a multi-class problem. Instead, if we have M > 2 augmentations of the same image fed into the contrastive learning model's single training batch, then each batch would have image M-1 similar pairs for image _**i**_. This task would resemble a multi-label problem.\nThe obvious choice would be to replace _cross-entropy loss_ with _binary cross-entropy loss_. Hence the name NT-BXent loss, which stands for Normalized Temperature-scaled Binary cross-entropy Loss.\nThe formulation below shows the loss _**Li**_ for the element _**i**_. The σ in the formula below stands for the [Sigmoid function](https://en.wikipedia.org/wiki/Sigmoid_function).\n![Figure 5: Formulation for the NT-BXent loss. Image source: Author\\(s\\) of this article](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/06/0eh_WA6AvteTizYns.png)\nFigure 5: Formulation for the NT-BXent loss. Image source: Author(s) of this article\nTo avoid the class imbalance problem, we weigh the positive and negative pairs by the inverse of the number of positive and negative pairs in our mini-batch. The final loss in the mini-batch used for backpropagation will be the mean of the losses of each sample in our mini-batch.\nNext, let's focus our attention on our implementation of the NT-BXent loss in PyTorch.\n* * *\n### Implementation of NT-BXent loss in PyTorch\nAll the code in this section can be found in [this notebook](https://github.com/dhruvbird/ml-notebooks/blob/main/nt-xent-loss/NT-Xent%20Loss.ipynb).\n**Code Reuse** : Similar to our implementation of the NT-Xent loss, we shall re-use the Binary Cross-entropy (BCE) loss method provided by PyTorch. The setup of our ground-truth labels will be similar to that of a multi-label classification problem where BCE loss is used.\n**Predictions Tensor** : We'll use the same (8, 2) predictions tensor as we used for the implementation of the NT-Xent loss.\npython\n\n```\nx = torch.randn(8, 2)\n```\n\n**Cosine Similarity** : Since the input tensor _**x**_ is same, the all-pairs cosine similarity tensor _**xcs**_ will also be the same. Please see [this page](https://medium.com/@dhruvbird/all-pairs-cosine-similarity-in-pytorch-867e722c8572) for a detailed explanation of what the line below does.\npython\n\n```\nxcs = F.cosine_similarity(x[None,:,:], x[:,None,:], dim=-1)\n```\n\nTo ensure that the loss from the element at position _**(i, i)**_ is _**0**_ , we'll need to perform some gymnastics to have our _**xcs**_ tensor contain a value _**1**_ at every index _**(i, i)**_ after Sigmoid is applied to it. Since we'll be using BCE Loss, we will mark the self-similarity score of every feature vector with the value _**infinity**_ in tensor _**xcs**_. That's because applying the sigmoid function on the _**xcs**_ tensor, will convert infinity to the value _**1**_ , and we will set up our ground-truth labels so that every position _**(i, i)**_ in the ground-truth labels has the value _**1**_.\nLet's create a masking tensor that has the value _**True**_ along the principal diagonal (_**xcs**_ has self-similarity scores along the principal diagonal), and _**False**_ everywhere else.\npython\n\n```\neye = torch.eye(8).bool()\n```\n\nLet's clone the tensor _\"xcs\"_ into a tensor named _\"y\"_ so that we can reference the _\"xcs\"_ tensor later.\npython\n\n```\ny = xcs.clone()\n```\n\nNow, we will set the values along the principal diagonal of the all-pairs cosine similarity matrix to _infinity_ so that when we compute the sigmoid on each row, we get 1 in these positions.\npython\n\n```\ny[eye] = float(\"inf\")\n```\n\nThe tensor _\"y\"_ scaled by a temperature parameter will be one of the inputs (predictions) to the [BCE loss API](https://pytorch.org/docs/stable/generated/torch.nn.functional.binary_cross_entropy.html) in PyTorch. Next, we need to compute the ground-truth labels (target) that we need to feed to the BCE loss API.\n**Ground Truth labels (Target tensor)** : We will expect the user to pass to us the pair of all (x, y) index pairs which contain positive examples. This is a departure for what we did for the NT-Xent loss, since the positive pairs were implicit, whereas here, the positive pairs are explicit.\nIn addition to the locations provided by the user, we will set all the diagonal elements as positive pairs as explained above. We will use the PyTorch tensor indexing API to pluck out all the elements at those locations and set them to 1, whereas the rest are initialized to 0.\npython\n\n```\ntarget = torch.zeros(8, 8)\npos_indices = torch.tensor([\n  (0, 0), (0, 2), (0, 4),\n  (1, 4), (1, 6), (1, 1),\n  (2, 3),\n  (3, 7),\n  (4, 3),\n  (7, 6),\n])\n# Add indexes of the principal diagonal as positive indexes.\n# This will be useful since we will use the BCELoss in PyTorch,\n# which will expect a value for the elements on the principal\n# diagonal as well.\npos_indices = torch.cat([pos_indices, torch.arange(8).reshape(8, 1).expand(-1, 2)], dim=0)\n# Set the values in the target vector to 1.\ntarget[pos_indices[:,0], pos_indices[:,1]] = 1\n```\n\n**Binary cross-entropy (BCE) Loss** : Unlike the NT-Xent loss, we can't simply call the torch.nn.functional.binary_cross_entropy_function, since we want to weigh the positive and negative loss based on how many positive and negative pairs the element at index i has in the current mini-batch.\nThe first step though is to compute the element-wise BCE loss.\npython\n\n```\ntemperature = 0.1\nloss = F.binary_cross_entropy((y / temperature).sigmoid(), target, reduction=\"none\")\n```\n\nWe'll create a binary mask of positive and negative pairs and then create 2 tensors, loss_pos and loss_neg that contain only those elements from the computed loss that correspond to the positive and negative pairs.\npython\n\n```\ntarget_pos = target.bool()\ntarget_neg = ~target_pos\n# loss_pos and loss_neg below contain non-zero values only for those elements\n# that are positive pairs and negative pairs respectively.\nloss_pos = torch.zeros(x.size(0), x.size(0)).masked_scatter(target_pos, loss[target_pos])\nloss_neg = torch.zeros(x.size(0), x.size(0)).masked_scatter(target_neg, loss[target_neg])\n```\n\nNext, we'll sum up the positive and negative pair loss (separately) corresponding to each element i in our mini-batch.\npython\n\n```\n# loss_pos and loss_neg now contain the sum of positive and negative pair losses\n# as computed relative to the i'th input.\nloss_pos = loss_pos.sum(dim=1)\nloss_neg = loss_neg.sum(dim=1)\n```\n\nTo perform weighting, we need to track the number of positive and negative pairs corresponding to each element i in our mini-batch. Tensors _\"num _pos\"_ and _\"num _neg\"_ will store these values.\npython\n\n```\n# num_pos and num_neg below contain the number of positive and negative pairs\n# computed relative to the i'th input. In an actual setting, this number should\n# be the same for every input element, but we let it vary here for maximum\n# flexibility.\nnum_pos = target.sum(dim=1)\nnum_neg = target.size(0) - num_pos\n```\n\nWe have all the ingredients we need to compute our loss! The only thing that we need to do is weigh the positive and negative loss by the number of positive and negative pairs, and then average the loss across the mini-batch.\npython\n\n```\ndef nt_bxent_loss(x, pos_indices, temperature):\n    assert len(x.size()) == 2\n\n    # Add indexes of the principal diagonal elements to pos_indices\n    pos_indices = torch.cat([\n        pos_indices,\n        torch.arange(x.size(0)).reshape(x.size(0), 1).expand(-1, 2),\n    ], dim=0)\n\n    # Ground truth labels\n    target = torch.zeros(x.size(0), x.size(0))\n    target[pos_indices[:,0], pos_indices[:,1]] = 1.0\n\n    # Cosine similarity\n    xcs = F.cosine_similarity(x[None,:,:], x[:,None,:], dim=-1)\n    # Set logit of diagonal element to \"inf\" signifying complete\n    # correlation. sigmoid(inf) = 1.0 so this will work out nicely\n    # when computing the Binary cross-entropy Loss.\n    xcs[torch.eye(x.size(0)).bool()] = float(\"inf\")\n\n    # Standard binary cross-entropy loss. We use binary_cross_entropy() here and not\n    # binary_cross_entropy_with_logits() because of\n    # https://github.com/pytorch/pytorch/issues/102894\n    # The method *_with_logits() uses the log-sum-exp-trick, which causes inf and -inf values\n    # to result in a NaN result.\n    loss = F.binary_cross_entropy((xcs / temperature).sigmoid(), target, reduction=\"none\")\n\n    target_pos = target.bool()\n    target_neg = ~target_pos\n\n    loss_pos = torch.zeros(x.size(0), x.size(0)).masked_scatter(target_pos, loss[target_pos])\n    loss_neg = torch.zeros(x.size(0), x.size(0)).masked_scatter(target_neg, loss[target_neg])\n    loss_pos = loss_pos.sum(dim=1)\n    loss_neg = loss_neg.sum(dim=1)\n    num_pos = target.sum(dim=1)\n    num_neg = x.size(0) - num_pos\n\n    return ((loss_pos / num_pos) + (loss_neg / num_neg)).mean()\n\npos_indices = torch.tensor([\n    (0, 0), (0, 2), (0, 4),\n    (1, 4), (1, 6), (1, 1),\n    (2, 3),\n    (3, 7),\n    (4, 3),\n    (7, 6),\n])\nfor t in (0.01, 0.1, 1.0, 10.0, 20.0):\n    print(f\"Temperature: {t:5.2f}, Loss: {nt_bxent_loss(x, pos_indices, temperature=t)}\")\n```\n\nPrints.\n> Temperature: 0.01, Loss: 62.898780822753906\n> Temperature: 0.10, Loss: 4.851151943206787\n> Temperature: 1.00, Loss: 1.0727109909057617\n> Temperature: 10.00, Loss: 0.9827173948287964\n> Temperature: 20.00, Loss: 0.982099175453186\n* * *\n## Conclusion\nSelf-supervised learning is an upcoming field in deep learning and allows one to train models on unlabeled data. This technique lets us work around the requirement of labeled data at scale.\nIn this article, we learned about loss functions for contrastive learning. The first one, named NT-Xent loss, is used for learning on a single positive pair per input in a mini-batch. We introduced the NT-BXent loss which is used for learning on multiple (> 1) positive pairs per input in a mini-batch. We learned to interpret them intuitively, building on our knowledge of cross-entropy loss and binary cross-entropy loss. Finally, we implemented them both efficiently in PyTorch.\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/1787657076238_edr3rv.jpeg)\nWritten By\n## [Dhruv Matani](https://towardsdatascience.com/author/dhruvbird/)\n[See all from Dhruv Matani](https://towardsdatascience.com/author/dhruvbird/)\n[Binary Cross Entropy](https://towardsdatascience.com/tag/binary-cross-entropy/)[Cross Entropy](https://towardsdatascience.com/tag/cross-entropy/)[Loss Function](https://towardsdatascience.com/tag/loss-function/)[Pytorch](https://towardsdatascience.com/tag/pytorch/)[Self Supervised Learning](https://towardsdatascience.com/tag/self-supervised-learning/)\nShare This Article\n  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fnt-xent-normalized-temperature-scaled-cross-entropy-loss-explained-and-implemented-in-pytorch-cc081f69848%2F&title=NT-Xent%20\\(Normalized%20Temperature-Scaled%20Cross-Entropy\\)%20Loss%20Explained%20and%20Implemented%20in%20PyTorch)\n  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fnt-xent-normalized-temperature-scaled-cross-entropy-loss-explained-and-implemented-in-pytorch-cc081f69848%2F&title=NT-Xent%20\\(Normalized%20Temperature-Scaled%20Cross-Entropy\\)%20Loss%20Explained%20and%20Implemented%20in%20PyTorch)\n  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fnt-xent-normalized-temperature-scaled-cross-entropy-loss-explained-and-implemented-in-pytorch-cc081f69848%2F&text=NT-Xent%20\\(Normalized%20Temperature-Scaled%20Cross-Entropy\\)%20Loss%20Explained%20and%20Implemented%20in%20PyTorch)\n\n\nTowards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.\n[Write for TDS](https://towardsdatascience.com/submissions/)\n## Related Articles\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/04/1K8v5y5UvNwvS-vSy7J0zww-scaled.jpeg)](https://towardsdatascience.com/understanding-entropy-2ee52b387f8c/)\n## [An Intuitive Guide To Entropy](https://towardsdatascience.com/understanding-entropy-2ee52b387f8c/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nUnderstanding why entropy is a measure of chaos\n[Aayush Agarwal](https://towardsdatascience.com/author/ayush2991/)\nApril 29, 20225 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2023/11/0n2-NehXZWdVRGBlb-scaled.jpg)](https://towardsdatascience.com/sklearn-tutorial-module-1-f31b3964a3b4/)\n## [Sklearn Tutorial: Module 1](https://towardsdatascience.com/sklearn-tutorial-module-1-f31b3964a3b4/)\n[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)\nI took the official sklearn MOOC tutorial. Here are my takeaways.\n[Yoann Mocquin](https://towardsdatascience.com/author/mocquin/)\nNovember 22, 202310 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/04/0cZC-iSUaaPWFJSDO-scaled.jpg)](https://towardsdatascience.com/how-to-select-loss-function-and-activation-function-for-classification-problems-b7f32c724507/)\n## [How to Select Loss Function and Activation Function for Classification Problems](https://towardsdatascience.com/how-to-select-loss-function-and-activation-function-for-classification-problems-b7f32c724507/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nUnderstanding how to choose activation function in the final layer and loss function for neural network\n[Ibrahim Kovan](https://towardsdatascience.com/author/ibrahimkovan/)\nApril 14, 20226 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/03/volodymyr-hryshchenko-L0oJ4Dlfyuo-unsplash-scaled-1.jpg)](https://towardsdatascience.com/yolov3-paper-walkthrough-even-better-but-not-that-much/)\n## [YOLOv3 Paper Walkthrough: Even Better, But Not That Much](https://towardsdatascience.com/yolov3-paper-walkthrough-even-better-but-not-that-much/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nA PyTorch implementation on the YOLOv3 architecture from scratch\n[Muhammad Ardi Putra](https://towardsdatascience.com/author/muhammad_ardi/)\nMarch 2, 202623 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/11/1YhYxuW4UYhwojOMe66rBdw.png)](https://towardsdatascience.com/image-clustering-implementation-with-pytorch-587af1d14123/)\n## [Image Clustering Implementation with PyTorch](https://towardsdatascience.com/image-clustering-implementation-with-pytorch-587af1d14123/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nLine-by-Line Tutorial Implementation of a Deep Convolutional Neural Network for the Clustering of Mushroom Photos\n[Anders Ohrn](https://towardsdatascience.com/author/ajohrn/)\nNovember 9, 202018 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2022/01/1OpMOF2vd3dWikyhUNnzeEw.png)](https://towardsdatascience.com/from-supervised-to-unsupervised-learning-a-paradigm-shift-in-computer-vision-ae19ada1064d/)\n## [From Supervised To Unsupervised Learning: A Paradigm Shift In Computer Vision](https://towardsdatascience.com/from-supervised-to-unsupervised-learning-a-paradigm-shift-in-computer-vision-ae19ada1064d/)\n[](https://towardsdatascience.com/nt-xent-normalized-temperature-scaled-cross-entropy-loss-explained-and-implemented-in-pytorch-cc081f69848/)\nSlowly removing the injection of human knowledge from the training process\n[Leon Sick](https://towardsdatascience.com/author/leon.sick/)\nJanuary 1, 20226 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2021/07/0EgRJezSYgE295j4X-scaled.jpg)](https://towardsdatascience.com/how-to-create-more-efficient-deep-learning-models-c27bf49e070c/)\n## [How to create more Efficient Deep Learning Models](https://towardsdatascience.com/how-to-create-more-efficient-deep-learning-models-c27bf49e070c/)\n[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)\nIn this article I am going to discuss several important approaches and techniques that can help improve the efficiency of neural networks.\n[Tudor Surdoiu](https://towardsdatascience.com/author/dacus-augustus/)\nJuly 1, 20216 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2026/01/1-2-1.jpeg)](https://towardsdatascience.com/optimizing-data-transfer-in-distributed-ai-ml-training-workloads/)\n## [Optimizing Data Transfer in Distributed AI/ML Training Workloads](https://towardsdatascience.com/optimizing-data-transfer-in-distributed-ai-ml-training-workloads/)\n[Data Engineering](https://towardsdatascience.com/category/data-science/data-engineering/)\nA deep dive on data transfer bottlenecks, their identification, and their resolution with the help of NVIDIA Nsight™ Systems – part 3\n[Chaim Rand](https://towardsdatascience.com/author/chaimrand/)\nJanuary 23, 202613 min read\n  * [![](https://assets.insightmediagroup.io/media/wp-content/uploads/2020/12/1lavhAToKGO9Bo4j3U7n4TA.jpeg)](https://towardsdatascience.com/self-supervised-learning-methods-for-computer-vision-c25ec10a91bd/)\n## [Self-Supervised Learning Methods for Computer Vision](https://towardsdatascience.com/self-supervised-learning-methods-for-computer-vision-c25ec10a91bd/)\n[Deep Learning](https://towardsdatascience.com/category/artificial-intelligence/deep-learning/)\nWhat is Self-supervised Learning?\n[Nilesh Vijayrania](https://towardsdatascience.com/author/nilesh0109/)\nDecember 15, 20209 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/859dfd0f4c0e/pages/",
  "body_markdown_path": "attachments/859dfd0f4c0e/pages/archived-body.md",
  "local_html": "attachments/859dfd0f4c0e/pages/archived-body.html",
  "body_source": "prior_capture"
}