- 
                Notifications
    You must be signed in to change notification settings 
- Fork 5.7k
SERVER-39057 Add distance expressions for image feature comparison #1291
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Open
      
      
            marcvivet-we
  wants to merge
  3
  commits into
  mongodb:master
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
WideEyesTech:master
  
      
      
   
  
    
  
  
  
 
  
      
    base: master
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
  
     Open
                    Changes from all commits
      Commits
    
    
  File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| #!/bin/bash | ||
|  | ||
| python2 buildscripts/scons.py mongod mongo mongos --disable-warnings-as-errors -j8 --release --distance-expression-use-avx2 | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| # Distance expression test. | ||
|  | ||
| from __future__ import print_function | ||
| from builtins import range | ||
| from pymongo import MongoClient | ||
| import numpy as np | ||
| import random | ||
| import time | ||
| import string | ||
| from bson import binary | ||
|  | ||
|  | ||
| client = MongoClient() | ||
| db = client["test_speed"] | ||
|  | ||
| vec_size = 4096 | ||
| num_documents = 150000 | ||
| fill_data_base = True | ||
| iterations = 10 | ||
| functions = ['no_op', 'cossim', 'chi2', 'euclidean', 'squared_euclidean', 'manhattan', 'no_op'] | ||
|  | ||
| vec = [] | ||
|  | ||
| for _ in range(iterations): | ||
| vec.append(binary.Binary(np.random.rand(vec_size).astype(np.float32).tobytes())) | ||
|  | ||
|  | ||
| if fill_data_base: | ||
| print("load database") | ||
| db.test_speed.drop() | ||
| for i in range(num_documents): | ||
| if i % 1000 == 0: print(i) | ||
| db.test_speed.insert({ | ||
| "id": random.randint(0, 1000000), | ||
| "other_id": ''.join(np.random.choice(list(string.ascii_uppercase)) for _ in range(6)), | ||
| "vector": binary.Binary(np.random.rand(vec_size).astype(np.float32).tobytes()) | ||
| }) | ||
|  | ||
| print("database loaded", db.test_speed.count()) | ||
|  | ||
| times_aggregate_base = np.zeros([iterations, 1], dtype=np.float32) | ||
| for function in functions: | ||
| for index in range(iterations): | ||
| start = time.time() | ||
| result = db.test_speed.aggregate([ | ||
| { | ||
| '$project': | ||
| { | ||
| 'id': '$id', | ||
| "other_id": '$other_id', | ||
| 'distance': {'${}'.format(function): [vec[index], '$vector']}, | ||
| }, | ||
| }, | ||
| {"$sort": {"distance": -1}}, | ||
| {"$limit": 20} | ||
| ]) | ||
| selection = list(result) | ||
| times_aggregate_base[index] = time.time() - start | ||
|  | ||
| print("Aggregate distance {}:".format(function)) | ||
| print(" - average: {:.5f}ms".format(np.mean(times_aggregate_base) * 1000)) | ||
| print(" - std: {:.5f}ms".format(np.std(times_aggregate_base) * 1000)) | ||
| print(" - max: {:.5f}ms".format(np.max(times_aggregate_base) * 1000)) | ||
| print(" - min: {:.5f}ms".format(np.min(times_aggregate_base) * 1000)) | ||
| print(" - median: {:.5f}ms".format(np.median(times_aggregate_base) * 1000)) | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| #if !defined(DISTANCE_EXPRESSION_NOT_BSON) && !defined(USE_AVX2) && !defined(USE_AVX512) | ||
|  | ||
| #include "mongo/db/pipeline/expression_distance.h" | ||
|  | ||
| namespace mongo { | ||
|  | ||
| REGISTER_EXPRESSION(euclidean, ExpressionEuclidean::parse) | ||
| REGISTER_EXPRESSION(cossim, ExpressionCosineSimilarity::parse) | ||
| REGISTER_EXPRESSION(chi2, ExpressionChi2::parse) | ||
| REGISTER_EXPRESSION(squared_euclidean, ExpressionSquaredEuclidean::parse) | ||
| REGISTER_EXPRESSION(manhattan, ExpressionManhattan::parse) | ||
| REGISTER_EXPRESSION(no_op, ExpressionNoOp::parse) | ||
|  | ||
| /* ------------------------- ExpressionEuclideanBin ----------------------------- */ | ||
|  | ||
| Value ExpressionEuclidean::evaluateImpl(const float* p_pData1, const float* p_pData2, const size_t p_uiSize) const { | ||
| float r = 0.0; | ||
| for (size_t i = 0; i < p_uiSize; ++i, ++p_pData1, ++p_pData2) { | ||
| float diff = *p_pData1 - *p_pData2; | ||
| r += diff * diff; | ||
| } | ||
|  | ||
| return Value(double(std::sqrt(r))); | ||
| } | ||
|  | ||
| /* ------------------------- ExpressionCosineSimilarityBin ----------------------------- */ | ||
|  | ||
| Value ExpressionCosineSimilarity::evaluateImpl(const float* p_pData1, const float* p_pData2, const size_t p_uiSize) const { | ||
| float dot = 0.0; | ||
| float norm_a = 0.0; | ||
| float norm_b = 0.0; | ||
|  | ||
| for (size_t i = 0; i < p_uiSize; ++i, ++p_pData1, ++p_pData2) { | ||
| float a = *p_pData1; | ||
| float b = *p_pData2; | ||
|  | ||
| dot += a * b; | ||
| norm_a += a * a; | ||
| norm_b += b * b; | ||
| } | ||
|  | ||
| float result = 1 - ( dot / ( (std::sqrt(norm_a*norm_b) + FLT_MIN) )); | ||
| return Value(double(result)); | ||
| } | ||
|  | ||
| /* ------------------------- ExpressionChi2Bin ----------------------------- */ | ||
|  | ||
| Value ExpressionChi2::evaluateImpl(const float* p_pData1, const float* p_pData2, const size_t p_uiSize) const { | ||
| float r = 0.0f; | ||
| for (size_t i = 0; i < p_uiSize; ++i, ++p_pData1, ++p_pData2) { | ||
| float a = *p_pData1; | ||
| float b = *p_pData2; | ||
| float t = a + b; | ||
| float diff = a - b; | ||
|  | ||
| r += (diff * diff) / ( t + FLT_MIN); | ||
| } | ||
|  | ||
| return Value(double(r)); | ||
| } | ||
|  | ||
| /* ------------------------- ExpressionSquaredEuclideanBin ----------------------------- */ | ||
|  | ||
| Value ExpressionSquaredEuclidean::evaluateImpl(const float* p_pData1, const float* p_pData2, const size_t p_uiSize) const { | ||
| float r = 0.f; | ||
| for (size_t i = 0; i < p_uiSize; ++i, ++p_pData1, ++p_pData2) { | ||
| float diff = *p_pData1 - *p_pData2; | ||
| r += diff * diff; | ||
| } | ||
|  | ||
| return Value(double(r)); | ||
| } | ||
|  | ||
| /* ------------------------- ExpressionManhattanBin ----------------------------- */ | ||
|  | ||
| Value ExpressionManhattan::evaluateImpl(const float* p_pData1, const float* p_pData2, const size_t p_uiSize) const { | ||
| float r = 0.0; | ||
|  | ||
| for (size_t i = 0; i < p_uiSize; ++i, ++p_pData1, ++p_pData2) { | ||
| r += std::fabs( *p_pData1 - *p_pData2 ); | ||
| } | ||
|  | ||
| return Value( double(r) ); | ||
| } | ||
|  | ||
| /* ------------------------- ExpressionNoOp ----------------------------- */ | ||
|  | ||
| inline Value ExpressionNoOp::evaluateImpl( | ||
| const float* p_pData1, const float* p_pData2, const size_t p_uiSize) const { | ||
| return Value( 0.0 ); | ||
| } | ||
|  | ||
| } | ||
|  | ||
| #endif | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,124 @@ | ||
|  | ||
| #pragma once | ||
|  | ||
| #include "mongo/db/pipeline/expression.h" | ||
|  | ||
| namespace mongo { | ||
|  | ||
| // When not using BSON we will use vectors | ||
| #ifdef DISTANCE_EXPRESSION_NOT_BSON | ||
| #define DISTANCE_EVALUATE_IMPL_PROTO(type) \ | ||
| Value evaluateImpl( \ | ||
| const std::vector<Value>& vector1, \ | ||
| const std::vector<Value>& vector2) const override final; | ||
| #else | ||
| // When using BSON we will get a pointer | ||
| #define DISTANCE_EVALUATE_IMPL_PROTO(type) \ | ||
| Value evaluateImpl( \ | ||
| const type* vector1, \ | ||
| const type* vector2, const size_t size) const override final; | ||
| #endif | ||
|  | ||
| #define DECLARE_DISTANCE_EXPRESSION(key, class_name, type, error) \ | ||
| class class_name final \ | ||
| : public ExpressionDistance<class_name, type, error> { \ | ||
| public: \ | ||
| explicit class_name(const boost::intrusive_ptr<ExpressionContext>& expCtx) \ | ||
| : ExpressionDistance<class_name, type, error>(expCtx) {} \ | ||
| const char* getOpName() const final { \ | ||
| return "$" #key; \ | ||
| } \ | ||
| protected: \ | ||
| const std::vector<boost::intrusive_ptr<Expression>>& getOperandList() const final { \ | ||
| return vpOperand; \ | ||
| } \ | ||
| DISTANCE_EVALUATE_IMPL_PROTO(type) \ | ||
| }; | ||
|  | ||
| // Template class for defining a distance expression | ||
| template <class SubClass, typename T, long ERROR> | ||
| class ExpressionDistance : public ExpressionNaryBase<SubClass> { | ||
| public: | ||
| explicit ExpressionDistance(const boost::intrusive_ptr<ExpressionContext>& expCtx) | ||
| : ExpressionNaryBase<SubClass>(expCtx) {} | ||
|  | ||
| Value evaluate(const Document& root) const final { | ||
| std::string sExpression = getOpName(); | ||
| const auto& vpOperand = getOperandList(); | ||
| const size_t n = vpOperand.size(); | ||
|  | ||
| if (n != 2) { | ||
| uasserted(ERROR, | ||
| str::stream() << sExpression << " only suppports 2 expressions, not " << n); | ||
| } | ||
|  | ||
| const Value& value1 = vpOperand[0]->evaluate(root); | ||
| const Value& value2 = vpOperand[1]->evaluate(root); | ||
|  | ||
| #ifndef DISTANCE_EXPRESSION_NOT_BSON | ||
| const BSONBinData& vector1 = value1.getBinData(); | ||
| const BSONBinData& vector2 = value2.getBinData(); | ||
|  | ||
| if (vector1.length != vector2.length) { | ||
| uasserted(ERROR + 1000L, | ||
| str::stream() << sExpression << " both operands must have the same length."); | ||
| } | ||
|  | ||
| const T* pData1 = (const T*)vector1.data; | ||
| const T* pData2 = (const T*)vector2.data; | ||
|  | ||
| return evaluateImpl(pData1, pData2, vector1.length / sizeof(T)); | ||
| #else | ||
| if (!value1.isArray()) { | ||
| uasserted(ErrorCodes::FailedToParse, | ||
| str::stream() << sExpression << " only supports array on 1st expression , not " | ||
| << typeName(value1.getType())); | ||
| } | ||
|  | ||
| if (!value2.isArray()) { | ||
| uasserted(ErrorCodes::FailedToParse, | ||
| str::stream() << sExpression << " only supports array on 2nd expression, not " | ||
| << typeName(value2.getType())); | ||
| } | ||
|  | ||
| const std::vector<Value>& vector1 = value1.getArray(); | ||
| const std::vector<Value>& vector2 = value2.getArray(); | ||
|  | ||
| if(vector1.size() != vector2.size()){ | ||
| uasserted(ErrorCodes::FailedToParse, | ||
| str::stream() << sExpression << " vectors of different sizes found " | ||
| << vector1.size() << " " << vector2.size()); | ||
| } | ||
|  | ||
| return evaluateImpl(vector1, vector2); | ||
| #endif | ||
| } | ||
|  | ||
| bool isAssociative() const final { | ||
| return true; | ||
| } | ||
|  | ||
| bool isCommutative() const final { | ||
| return false; | ||
| } | ||
|  | ||
| virtual const char* getOpName() const = 0; | ||
|  | ||
| protected: | ||
| virtual const std::vector<boost::intrusive_ptr<Expression>>& getOperandList() const = 0; | ||
| #ifndef DISTANCE_EXPRESSION_NOT_BSON | ||
| virtual Value evaluateImpl(const T* p_pData1, const T* p_pData2, const size_t p_uiSize) const = 0; | ||
| #else | ||
| virtual Value evaluateImpl(const std::vector<Value>& vector1, const std::vector<Value>& vector2) const = 0; | ||
| #endif | ||
| }; | ||
|  | ||
| DECLARE_DISTANCE_EXPRESSION(euclidean, ExpressionEuclidean, float, 9020) | ||
| DECLARE_DISTANCE_EXPRESSION(cossim, ExpressionCosineSimilarity, float, 90021) | ||
| DECLARE_DISTANCE_EXPRESSION(chi2, ExpressionChi2, float, 90022) | ||
| DECLARE_DISTANCE_EXPRESSION(squared_euclidean, ExpressionSquaredEuclidean, float, 90023) | ||
| DECLARE_DISTANCE_EXPRESSION(manhattan, ExpressionManhattan, float, 90024) | ||
| // Only for benchmarking | ||
| DECLARE_DISTANCE_EXPRESSION(no_op, ExpressionNoOp, float, 90025) | ||
|  | ||
| } | 
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Những
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can you explain what is your intention @anhems with this line?
Seems completely unrelated to this PR,
Best,
Miguel