More reliable nearest-neighbor search with deep metric learning

Novel loss term that can be added to any loss function regularizes interclass and intraclass distances.

Many machine learning (ML) applications involve embedding data in a representation space, where the geometric relationships between embeddings carry semantic content. Performing a useful task often involves retrieving an embedding’s proximate neighbors in the space: for instance, the answer embeddings near a query embedding, the image embeddings near the embedding of a text description, the text embeddings in one language near a text embedding in another, and so on.

A popular way to ensure that retrieved examples accurately represent the intended semantics is deep metric learning, which is commonly used to train contrastive-learning models like the vision-language model CLIP. In deep metric learning, the ML model learns to structure the representation space according to a specified metric, so as to maximize the distinction between dissimilar training samples while promoting proximity among similar ones.

One drawback of deep metric learning (DML), however, is that both the distances between embeddings of the same class and the distances between different classes of embeddings can vary. This is a problem in many real-world applications, where you want a single distance threshold that meets specific false-positive and false-negative rate requirements. If both the interclass and intraclass distances vary, no single threshold is optimal in all cases. This can cause substantial deployment complexities in large-scale applications, as individual users may require distinct threshold settings.

Related content
New approach speeds graph-based search by 20% to 60%, regardless of graph construction method.

At this year’s International Conference on Learning Representations (ICLR), my colleagues and I presented a way to make the distances between DML embeddings more consistent, so that a single threshold will yield equitable fractions of relevant results across classes.

First, we propose a new evaluation metric for measuring DML models’ threshold consistency, called the operating-point-inconsistency score (OPIS), which we use to show that optimizing model accuracy does not optimize threshold consistency. Then we propose a new loss term, which can be added to any loss function and backbone architecture for training a DML model, that regularizes distances between both hard-positive intraclass and hard-negative interclass embeddings, to make distance thresholds more consistent. This helps to ensure consistent accuracy across customers, even amid significant variations in their query data.

To test our approach, we used four benchmark image retrieval datasets, and with each one we trained eight networks: four of the networks were residual networks, trained with two different loss functions, each with and without our added term; the other four were vision transformer networks, also trained with two different state-of-the-art DML loss functions, with and without our added term.

In the resulting 16 comparisons, the incorporation of our loss term notably enhanced threshold consistency across all experiments, reducing the OPIS inconsistency score by as much as 77.3%. The integration of our proposed loss also led to improved accuracy in 14 out of the 16 comparisons, with the greatest margin of improvement being 3.6% and the highest margin of diminishment being 0.2%.

Measuring consistency

DML models are typically trained using contrastive learning, in which the model receives pairs of inputs, which are either of the same class or of different classes. During training, the model learns an embedding scheme that pushes data of different classes apart from each other and pulls data of the same class together.

As the separation between classes increases, and the separation within classes decreases, you might expect that the embeddings for each class become highly compact, leading to a high degree of distance consistency across classes. But we show that this is not the case, even for models with very high accuracies.

Our evaluation metric, OPIS, relies on a utility score that measures a model’s accuracy at different threshold values. We use the standard F1 score, which factors in both the false-acceptance and false-rejection rate, where a weighting term can be added to emphasize one rate over the other.

Thousands of overlaid approximately-bell-shaped curves, with wide disparity in width, illustrating the difficulty of choosing a single threshold value optimizes utility for all of them.
Utility (U(d)) vs. threshold distance (d) for the iNaturalist dataset, in which the labeled data classes are animal species.

Then we define a range of threshold values, which we call the calibration range, which is typically based on the target performance metric in some way. For instance, it might be chosen so as to impose bounds on the false-acceptance or false-rejection rate. We then compute the average difference between the utility score for a given threshold choice and the average utility score over the complete range of threshold values. As can be seen in the graph of utility vs. threshold distance, the utility-threshold curve can vary significantly for different classes of data in the same dataset.

To gauge the relationship between performance and threshold consistency, we trained a series of models on the same dataset using a range of different loss functions and batch sizes. We found that, among the lower-accuracy models, there was indeed a correlation between accuracy and threshold consistency. But beyond an inflection point, improved performance came at the cost of less consistent thresholds.

Seven blue circles of different sizes, plotted on a plane whose axes are labeled "Threshold inconsistency (OPIS)" and "Recognition error". The three rightmost (highest-error) circles lie almost on a straight line, from upper right to lower left, which is approximated with a downward-pointing red arrow. The circles to the left of the red arrow, however, show a slight upward trend from right to left — that is, toward greater inconsistency, as the error rate goes down. Connected to four of the circles by dotted lines are four red triangles, representing versions of the same models trained using the TCM loss. In all four cases, the triangles are closer to both the x-axis and the y-axis than the associated circles, indicating lower error and greater consistency in threshold distance.
Threshold consistency vs. recognition error for two different models trained using five different loss functions and varied batch sizes. Circles represent models trained using the basic form of the loss function; triangles represent models trained with our additional loss term. Arrows indicate the correlations between increasing accuracy and threshold consistency.

Better threshold consistency

To improve threshold consistency, we introduce a new regularization loss for DML training, called the threshold-consistent margin (TCM) loss. TCM has two parameters. The first is a positive margin for mining hard positive data pairs, where “hard” denotes data items of the same class with small cosine similarity (i.e., they’re so dissimilar that it is hard to assign them to the same class). The second is a negative margin for mining hard negative data pairs, where “hard” indicates data points of different classes with high cosine similarity (i.e., they’re so similar that it is hard to assign them to different classes).

Related content
New loss functions enable better approximation of the optimal loss and more-useful representations of multimodal data.

After mining these hard pairs, the loss term imposes a penalty that’s proportional to the difference between the measured distance and the parameter for the hard pairs exclusively. Like the calibration range, these values can be designed to enforce bounds on the false-acceptance of false-rejection rates — although, because of distribution drift between training and test sets, we do recommend that they be tuned to the data.

In other words, our TCM loss term serves as a “local inspector" by selectively adjusting hard samples to prevent overseparateness and excessive compactness in the vicinity of the boundaries between classes. As can be seen in the figure below, which compares the utility-threshold curves for a model trained using our loss function to one trained without it, our regularization term improves the consistency of threshold distances across data classes.

The superimposed curves from above, now paired with a second set of curves, whose disparity in width is less pronounced. The first set is labeled as having been produced using the Smooth-AP loss function, the second set as having been produced using Smooth-AP and TCM.
Utility (U(d)) vs. threshold distance (d) for the iNaturalist dataset, before and after the use of our additional loss term (TCM).

Below are the results of our experiments on four benchmark datasets, using two models for each and two versions of two loss functions for each model:

TCM results.png
The results of our experiments. Performance is measured according to recall for the top-scoring results (R@1); we also report change in OPIS and change in 10%-OPIS, meaning the difference in OPIS between the worst-performing 10% of data and the remaining 90%. We report results only for models trained with our loss term; the absolute change in performance relative to models trained without our loss term is recorded in red or green, with arrows indicating direction of change.

We also conducted a toy experiment using the MNIST dataset of hand-drawn digits to visualize the effect of our proposed TCM regularization, where the task was to learn to group examples of the same digit together. The addition of our loss term led to more compact class clusters and clearer separation between clusters, as can be seen in the visualization below:

Two figures consisting of 10 symmetrically spaced arrows of equal length radiating out from a point on a blue field. Each arrow is labeled with one of the digits 0 through 9, and the tip of each arrow is surrounded by a reddish oval. In the image at left, the ovals for the number pairs 4 and 9, 8 and 0, and 2 and 5 blur into each other at their edges. In the image at right, the ovals are more compact, and there are clear boundaries of blue between any two of them.
The results of adding our extra term to the ArcFace loss function during training on the MNIST dataset of hand-drawn digits. The color intensity conveys the probability density distribution of embeddings within each class, with higher density depicted in red.

The addition of our TCM loss term may not lead to dramatic improvements in every instance. But because it can be used, at no added computational cost, with any choice of model and any choice of loss function, the occasions are rare when it wouldn’t be worth trying.

Related content

US, WA, Seattle
Do you want to re-invent how millions of people consume video content on their TVs, Tablets and Alexa? We are building a free to watch streaming service called Fire TV Channels (https://techcrunch.com/2023/08/21/amazon-launches-fire-tv-channels-app-400-fast-channels/). Our goal is to provide customers with a delightful and personalized experience for consuming content across News, Sports, Cooking, Gaming, Entertainment, Lifestyle and more. You will work closely with engineering and product stakeholders to realize our ambitious product vision. You will get to work with Generative AI and other state of the art technologies to help build personalization and recommendation solutions from the ground up. You will be in the driver's seat to present customers with content they will love. Using Amazon’s large-scale computing resources, you will ask research questions about customer behavior, build state-of-the-art models to generate recommendations and run these models to enhance the customer experience. You will participate in the Amazon ML community and mentor Applied Scientists and Software Engineers with a strong interest in and knowledge of ML. Your work will directly benefit customers and you will measure the impact using scientific tools.
US, MA, Boston
The Artificial General Intelligence (AGI) team is looking for a passionate, talented, and inventive Applied Scientist with a strong deep learning background, to build industry-leading technology with Large Language Models (LLMs) and multi-modal systems. You will support projects that work on technologies including multi-modal model alignment, moderation systems and evaluation. Key job responsibilities As an Applied Scientist with the AGI team, you will support the development of novel algorithms and modeling techniques, to advance the state of the art with LLMs. Your work will directly impact our customers in the form of products and services that make use of speech and language technology. You will leverage Amazon’s heterogeneous data sources and large-scale computing resources to accelerate advances in generative artificial intelligence (GenAI). You are also expected to publish in top tier conferences. About the team The AGI team has a mission to push the envelope in LLMs and multimodal systems. Specifically, we focus on model alignment with an aim to maintain safety while not denting utility, in order to provide the best-possible experience for our customers.
IN, HR, Gurugram
Our customers have immense faith in our ability to deliver packages timely and as expected. A well planned network seamlessly scales to handle millions of package movements a day. It has monitoring mechanisms that detect failures before they even happen (such as predicting network congestion, operations breakdown), and perform proactive corrective actions. When failures do happen, it has inbuilt redundancies to mitigate impact (such as determine other routes or service providers that can handle the extra load), and avoids relying on single points of failure (service provider, node, or arc). Finally, it is cost optimal, so that customers can be passed the benefit from an efficiently set up network. Amazon Shipping is hiring Applied Scientists to help improve our ability to plan and execute package movements. As an Applied Scientist in Amazon Shipping, you will work on multiple challenging machine learning problems spread across a wide spectrum of business problems. You will build ML models to help our transportation cost auditing platforms effectively audit off-manifest (discrepancies between planned and actual shipping cost). You will build models to improve the quality of financial and planning data by accurately predicting ship cost at a package level. Your models will help forecast the packages required to be pick from shipper warehouses to reduce First Mile shipping cost. Using signals from within the transportation network (such as network load, and velocity of movements derived from package scan events) and outside (such as weather signals), you will build models that predict delivery delay for every package. These models will help improve buyer experience by triggering early corrective actions, and generating proactive customer notifications. Your role will require you to demonstrate Think Big and Invent and Simplify, by refining and translating Transportation domain-related business problems into one or more Machine Learning problems. You will use techniques from a wide array of machine learning paradigms, such as supervised, unsupervised, semi-supervised and reinforcement learning. Your model choices will include, but not be limited to, linear/logistic models, tree based models, deep learning models, ensemble models, and Q-learning models. You will use techniques such as LIME and SHAP to make your models interpretable for your customers. You will employ a family of reusable modelling solutions to ensure that your ML solution scales across multiple regions (such as North America, Europe, Asia) and package movement types (such as small parcel movements and truck movements). You will partner with Applied Scientists and Research Scientists from other teams in US and India working on related business domains. Your models are expected to be of production quality, and will be directly used in production services. You will work as part of a diverse data science and engineering team comprising of other Applied Scientists, Software Development Engineers and Business Intelligence Engineers. You will participate in the Amazon ML community by authoring scientific papers and submitting them to Machine Learning conferences. You will mentor Applied Scientists and Software Development Engineers having a strong interest in ML. You will also be called upon to provide ML consultation outside your team for other problem statements. If you are excited by this charter, come join us!
IN, HR, Gurugram
We're on a journey to build something new a green field project! Come join our team and build new discovery and shopping products that connect customers with their vehicle of choice. We're looking for a talented Senior Applied Scientist to join our team of product managers, designers, and engineers to design, and build innovative automotive-shopping experiences for our customers. This is a great opportunity for an experienced engineer to design and implement the technology for a new Amazon business. We are looking for a Applied Scientist to design, implement and deliver end-to-end solutions. We are seeking passionate, hands-on, experienced and seasoned Senior Applied Scientist who will be deep in code and algorithms; who are technically strong in building scalable computer vision machine learning systems across item understanding, pose estimation, class imbalanced classifiers, identification and segmentation.. You will drive ideas to products using paradigms such as deep learning, semi supervised learning and dynamic learning. As a Senior Applied Scientist, you will also help lead and mentor our team of applied scientists and engineers. You will take on complex customer problems, distill customer requirements, and then deliver solutions that either leverage existing academic and industrial research or utilize your own out-of-the-box but pragmatic thinking. In addition to coming up with novel solutions and prototypes, you will directly contribute to implementation while you lead. A successful candidate has excellent technical depth, scientific vision, project management skills, great communication skills, and a drive to achieve results in a unified team environment. You should enjoy the process of solving real-world problems that, quite frankly, haven’t been solved at scale anywhere before. Along the way, we guarantee you’ll get opportunities to be a bold disruptor, prolific innovator, and a reputed problem solver—someone who truly enables AI and robotics to significantly impact the lives of millions of consumers. Key job responsibilities Architect, design, and implement Machine Learning models for vision systems on robotic platforms Optimize, deploy, and support at scale ML models on the edge. Influence the team's strategy and contribute to long-term vision and roadmap. Work with stakeholders across , science, and operations teams to iterate on design and implementation. Maintain high standards by participating in reviews, designing for fault tolerance and operational excellence, and creating mechanisms for continuous improvement. Prototype and test concepts or features, both through simulation and emulators and with live robotic equipment Work directly with customers and partners to test prototypes and incorporate feedback Mentor other engineer team members. A day in the life - 6+ years of building machine learning models for retail application experience - PhD, or Master's degree and 6+ years of applied research experience - Experience programming in Java, C++, Python or related language - Experience with neural deep learning methods and machine learning - Demonstrated expertise in computer vision and machine learning techniques.
US, MA, Boston
The Artificial General Intelligence (AGI) team is looking for a passionate, talented, and inventive Senior Applied Scientist with a strong deep learning background, to build industry-leading technology with Large Language Models (LLMs) and multimodal systems. Key job responsibilities As a Senior Applied Scientist with the AGI team, you will work with talented peers to lead the development of novel algorithms and modeling techniques, to advance the state of the art with LLMs. Your work will directly impact our customers in the form of products and services that make use of speech and language technology. You will leverage Amazon’s heterogeneous data sources and large-scale computing resources to accelerate advances in generative artificial intelligence (GenAI). About the team The AGI team has a mission to push the envelope in LLMs and multimodal systems, in order to provide the best-possible experience for our customers.
IN, KA, Bengaluru
The Amazon Alexa AI team in India is seeking a talented, self-driven Applied Scientist to work on prototyping, optimizing, and deploying ML algorithms within the realm of Generative AI. Key responsibilities include: - Research, experiment and build Proof Of Concepts advancing the state of the art in AI & ML for GenAI. - Collaborate with cross-functional teams to architect and execute technically rigorous AI projects. - Thrive in dynamic environments, adapting quickly to evolving technical requirements and deadlines. - Engage in effective technical communication (written & spoken) with coordination across teams. - Conduct thorough documentation of algorithms, methodologies, and findings for transparency and reproducibility. - Publish research papers in internal and external venues of repute - Support on-call activities for critical issues Basic Qualifications: - Master’s or PhD in computer science, statistics or a related field or relevant science experience (publications/scientific prototypes) in lieu of Masters - Experience in deep learning, machine learning, and data science. - Proficiency in coding and software development, with a strong focus on machine learning frameworks. - Experience in Python, or another language; command line usage; familiarity with Linux and AWS ecosystems. - Understanding of relevant statistical measures such as confidence intervals, significance of error measurements, development and evaluation data sets, etc. - Excellent communication skills (written & spoken) and ability to collaborate effectively in a distributed, cross-functional team setting. Preferred Qualifications: - Track record of diving into data to discover hidden patterns and conducting error/deviation analysis - Ability to develop experimental and analytic plans for data modeling processes, use of strong baselines, ability to accurately determine cause and effect relations - The motivation to achieve results in a fast-paced environment. - Exceptional level of organization and strong attention to detail - Comfortable working in a fast paced, highly collaborative, dynamic work environment - Papers published in AI/ML venues of repute
IN, KA, Bengaluru
The Amazon Alexa AI team in India is seeking a talented, self-driven Applied Scientist to work on prototyping, optimizing, and deploying ML algorithms within the realm of Generative AI. Key responsibilities include: - Research, experiment and build Proof Of Concepts advancing the state of the art in AI & ML for GenAI. - Collaborate with cross-functional teams to architect and execute technically rigorous AI projects. - Thrive in dynamic environments, adapting quickly to evolving technical requirements and deadlines. - Engage in effective technical communication (written & spoken) with coordination across teams. - Conduct thorough documentation of algorithms, methodologies, and findings for transparency and reproducibility. - Publish research papers in internal and external venues of repute - Support on-call activities for critical issues Basic Qualifications: - Master’s or PhD in computer science, statistics or a related field - 2-7 years experience in deep learning, machine learning, and data science. - Proficiency in coding and software development, with a strong focus on machine learning frameworks. - Experience in Python, or another language; command line usage; familiarity with Linux and AWS ecosystems. - Understanding of relevant statistical measures such as confidence intervals, significance of error measurements, development and evaluation data sets, etc. - Excellent communication skills (written & spoken) and ability to collaborate effectively in a distributed, cross-functional team setting. - Papers published in AI/ML venues of repute Preferred Qualifications: - Track record of diving into data to discover hidden patterns and conducting error/deviation analysis - Ability to develop experimental and analytic plans for data modeling processes, use of strong baselines, ability to accurately determine cause and effect relations - The motivation to achieve results in a fast-paced environment. - Exceptional level of organization and strong attention to detail - Comfortable working in a fast paced, highly collaborative, dynamic work environment
IN, KA, Bengaluru
Amazon is investing heavily in building a world class advertising business and we are responsible for defining and delivering a collection of self-service performance advertising products that drive discovery and sales. Our products are strategically important to our Retail and Marketplace businesses driving long term growth. We deliver billions of ad impressions and millions of clicks daily and are breaking fresh ground to create world-class products. We are highly motivated, collaborative and fun-loving with an entrepreneurial spirit and bias for action. With a broad mandate to experiment and innovate, we are growing at an unprecedented rate with a seemingly endless range of new opportunities. The ATT team, based in Bangalore, is responsible for ensuring that ads are relevant and is of good quality, leading to higher conversion for the sellers and providing a great experience for the customers. We deal with one of the world’s largest product catalog, handle billions of requests a day with plans to grow it by order of magnitude and use automated systems to validate tens of millions of offers submitted by thousands of merchants in multiple countries and languages. In this role, you will build and develop ML models to address content understanding problems in Ads. These models will rely on a variety of visual and textual features requiring expertise in both domains. These models need to scale to multiple languages and countries. You will collaborate with engineers and other scientists to build, train and deploy these models. As part of these activities, you will develop production level code that enables moderation of millions of ads submitted each day.
US, WA, Seattle
The Search Supply & Experiences team, within Sponsored Products, is seeking an Applied Scientist to solve challenging problems in natural language understanding, personalization, and other areas using the latest techniques in machine learning. In our team, you will have the opportunity to create new ads experiences that elevate the shopping experience for our hundreds of millions customers worldwide. As an Applied Scientist, you will partner with other talented scientists and engineers to design, train, test, and deploy machine learning models. You will be responsible for translating business and engineering requirements into deliverables, and performing detailed experiment analysis to determine how shoppers and advertisers are responding to your changes. We are looking for candidates who thrive in an exciting, fast-paced environment and who have a strong personal interest in learning, researching, and creating new technologies with high customer impact. Key job responsibilities As an Applied Scientist on the Search Supply & Experiences team you will: - Perform hands-on analysis and modeling of enormous datasets to develop insights that increase traffic monetization and merchandise sales, without compromising the shopper experience. - Drive end-to-end machine learning projects that have a high degree of ambiguity, scale, and complexity. - Build machine learning models, perform proof-of-concept, experiment, optimize, and deploy your models into production; work closely with software engineers to assist in productionizing your ML models. - Design and run experiments, gather data, and perform statistical analysis. - Establish scalable, efficient, automated processes for large-scale data analysis, machine-learning model development, model validation and serving. - Stay up to date on the latest advances in machine learning. About the team We are a customer-obsessed team of engineers, technologists, product leaders, and scientists. We are focused on continuous exploration of contexts and creatives where advertising delivers value to shoppers and advertisers. We specifically work on new ads experiences globally with the goal of helping shoppers make the most informed purchase decision. We obsess about our customers and we are continuously innovating on their behalf to enrich their shopping experience on Amazon
US, WA, Seattle
Amazon.com strives to be Earth's most customer-centric company where customers can shop in our stores to find and discover anything they want to buy. We hire the world's brightest minds, offering them a fast paced, technologically sophisticated and friendly work environment. Economists at Amazon partner closely with senior management, business stakeholders, scientist and engineers, and economist leadership to solve key business problems ranging from Amazon Web Services, Kindle, Prime, inventory planning, international retail, third party merchants, search, pricing, labor and employment planning, effective benefits (health, retirement, etc.) and beyond. Amazon Economists build econometric models using our world class data systems and apply approaches from a variety of skillsets – applied macro/time series, applied micro, econometric theory, empirical IO, empirical health, labor, public economics and related fields are all highly valued skillsets at Amazon. You will work in a fast moving environment to solve business problems as a member of either a cross-functional team embedded within a business unit or a central science and economics organization. You will be expected to develop techniques that apply econometrics to large data sets, address quantitative problems, and contribute to the design of automated systems around the company. About the team The International Seller Services (ISS) Economics team is a dynamic group at the forefront of shaping Amazon's global seller ecosystem. As part of ISS, we drive innovation and growth through sophisticated economic analysis and data-driven insights. Our mission is critical: we're transforming how Amazon empowers millions of international sellers to succeed in the digital marketplace. Our team stands at the intersection of innovative technology and practical business solutions. We're leading Amazon's transformation in seller services through work with Large Language Models (LLMs) and generative AI, while tackling fundamental questions about seller growth, marketplace dynamics, and operational efficiency. What sets us apart is our unique blend of rigorous economic methodology and practical business impact. We're not just analyzing data – we're building the frameworks and measurement systems that will define the future of Amazon's seller services. Whether we're optimizing the seller journey, evaluating new technologies, or designing innovative service models, our team transforms complex economic challenges into actionable insights that drive real-world results. Join us in shaping how millions of businesses worldwide succeed on Amazon's marketplace, while working on problems that combine economic theory, advanced analytics, and innovative technology.