Skip to content

Precision by Vector Dimension #163

Closed

Description

@olirice

We've been digging into performance to improve documentation around required instance sizes, expected queries/sec, precision, etc

I had an unexpected result when measuring precision for different vector sizes and wanted to share to see if you have any insights

Holding the following parameters constant:

parameter value
# records 10_000
# index lists 30
top k 10
metric inner product
dataset random unit vectors

I varied the dataset's dimension and ivfflat.probes to measure the precision@k=10

That resulted in:
Screenshot 2023-06-15 at 1 40 43 PM

*note: the legend was abbreviated, tested dimensions were [3, 5, 10, 20, 30, 40, 50, ... 1400, 1600]

Interpreting that chart:
As the number of probes approaches number of index lists, precision approaches 100% (as expected)

Another trend is that as the vector dimension grows, the relative benefit of the index decreases. That is visible as the curves "flatten out"

Another way to think about that is the amount of the dataset that has to be scanned to achieve a given precision.

For example:

Screenshot 2023-06-15 at 1 17 09 PM

so, to achieve a minimum of 99.0% precision on vector dimensions > 150, we have to compute distances for more than 80% of the records in the dataset.


Questions:

  • Is that roughly what you expected?

  • Is the characterization of the relationships among lists, probes, and vector dimensions (shown above) roughly correct, or am I missing some info?

  • Do you think recommendations in the form of
    "for approximately M% precision on N dimensional vectors, set ivfflat.probes = Y% of lists "
    would be the right way to summarize for users?

Activity

  1. jkatz commented on Jun 17, 2023

    @jkatz
    Contributor

    @olirice This seems to be a pretty small data set, i.e. 10,000 rows, along with it being divided up over 30 lists. This is probably skewing the clusters a bit, so it's less likely you're going to find commonality without visiting multiple lists. At the size of this data set, even with higher dimensionality, I would suspect doing a sequential scan (not using the index) is likely the way to go if you're most interested in precision.

    I'd be more curious on the results across larger data sets, even at 100,000 rows. At that point you're going to need to rely on the index more for performance, and I think it'll give a better sense of what it will take to get precise results.

  2. olirice commented on Jun 20, 2023

    @olirice
    Author

    10,000 rows, along with it being divided up over 30 lists. This is probably skewing the clusters a bit

    @jkatz I didn't understand what you mean wrt cluster skew

    k-means should result in an equal number of entries in each list and each vector/point will always be assigned to its nearest centroid immediately following training. Once we're at a statistically significant number of records I'd expect the precision results to be invariant to both parameters (if probes is taken as a % of lists).

    Could you pls explain how the skew occurs & if increasing the dataset size fully resolves it (I increased it in the chart below to be safe)?

  3. olirice commented on Jun 20, 2023

    @olirice
    Author

    (from a separate thread)

    1. It'd be good to run the benchmarking framework with the IVFFlat index type from Faiss to confirm

    I re-ran the analysis using faiss and increased dataset size and precision samples to 100k and 10k respectively.

    Screenshot 2023-06-20 at 10 07 33 AM

    which shows the same result, so looks like that's correct

    It's interesting that the number of required probes for a given level of precision starts to decrease after an inflection point between 256 and 512 dimensions in both implementations. Not sure what that's about

  4. olirice commented on Jun 20, 2023

    @olirice
    Author

    Here's the code to reproduce that output if anyone's interested

    import numpy as np
    import faiss
    import seaborn as sns
    import pandas as pd
    
    # seed RNG for reproducible result
    np.random.seed(1234)
    
    nlist = 30
    
    # number of results to return from each query
    k = 10
    
    # dataset size
    nb = 100000
    
    # number of queries used to calculate mean precision
    nq = 10000
    
    precision = []
    
    # Number of dimensions
    dimensions = [5, 10, 32, 64, 128, 256, 512, 1024, 1536]
    
    for d in dimensions:
        
        # Vector Dataset
        xb = np.random.normal(size = (nb, d)).astype('float32') 
        xb = xb / np.linalg.norm(xb, axis=1)[:, np.newaxis]
        
        # Query Dataset
        xq = np.random.normal(size = (nq, d)).astype('float32')
        xq = xq / np.linalg.norm(xq, axis=1)[:, np.newaxis]
        
        # Define the index
        quantizer = faiss.IndexFlatL2(d)  # the other index
        index = faiss.IndexIVFFlat(quantizer, d, nlist, faiss.METRIC_L2)
    
        # Train the index
        assert not index.is_trained
        index.train(xb)
        assert index.is_trained
    
        # Load dataset into the index
        index.add(xb)
            
        # Collect the accurate results by setting nprobes == nlists
        index.nprobe = nlist
    
        # The accurate results for each query vector
        _, correct_results = index.search(xq, k=k)
        
        # For each number of probesm calculate precision@k
        for nprobes in range(1,nlist+1):
            index.nprobe = nprobes
    
            # Results for the given number of nprobes
            _, q_results = index.search(xq, k=k)
    
            # Compare each row of the correct results with the query results 
            agg = []
            for correct_row, q_row in zip(correct_results, q_results):
                correct_row = set(correct_row)
                q_row = set(q_row)
            
                row_precision = float(len(q_row.intersection(correct_row))) / k
                agg.append(row_precision)
    
            # Add result to the output (dimensions, nprobes, precision)
            rec = (d, nprobes, sum(agg) / len(agg))
            print(rec)
            precision.append(rec)
    
    # Load dataset into a dataframe for plotting
    df = pd.DataFrame(precision, columns=['vector_dim', 'probes', 'precision'])
    
    # Plot the results
    sns.lineplot(
        data=df,
        x='probes',
        y='precision',
        hue='vector_dim'
    ).set(title='precision@k=10 by probes')
  5. olirice commented on Jun 21, 2023

    @olirice
    Author

    closing as questions were resolved

  6. olirice commented on Jun 22, 2023

    @olirice
    Author

    It's interesting that the number of required probes for a given level of precision starts to decrease after an inflection point between 256 and 512 dimensions in both implementations. Not sure what that's about

    This effect was due normalizing vectors produced by np.random.random rather than np.random.normal. It has been corrected in the code snippet above and now as the vector dimension increases the value of the index consistently reduces

    other conclusions remain unchanged

    Screenshot 2023-06-22 at 12 07 22 PM

    thanks @akorotkov for pointing out this error

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions