github.com/weaviate/weaviate@v1.24.6/adapters/repos/db/vector/hnsw/distancer/dot_product.go (about) 1 // _ _ 2 // __ _____ __ ___ ___ __ _| |_ ___ 3 // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \ 4 // \ V V / __/ (_| |\ V /| | (_| | || __/ 5 // \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___| 6 // 7 // Copyright © 2016 - 2024 Weaviate B.V. All rights reserved. 8 // 9 // CONTACT: hello@weaviate.io 10 // 11 12 package distancer 13 14 import ( 15 "github.com/pkg/errors" 16 ) 17 18 // can be set depending on architecture, e.g. pure go, AVX-enabled assembly, etc. 19 // Warning: This is not the dot product distance, but the pure product. 20 // 21 // This default will always work, regardless of architecture. An init function 22 // will overwrite it on amd64 if AVX is present. 23 var dotProductImplementation func(a, b []float32) float32 = func(a, b []float32) float32 { 24 var sum float32 25 for i := range a { 26 sum += a[i] * b[i] 27 } 28 29 return sum 30 } 31 32 type DotProduct struct { 33 a []float32 34 } 35 36 func (d *DotProduct) Distance(b []float32) (float32, bool, error) { 37 if len(d.a) != len(b) { 38 return 0, false, errors.Errorf("vector lengths don't match: %d vs %d", 39 len(d.a), len(b)) 40 } 41 42 dist := -dotProductImplementation(d.a, b) 43 return dist, true, nil 44 } 45 46 type DotProductProvider struct{} 47 48 func NewDotProductProvider() DotProductProvider { 49 return DotProductProvider{} 50 } 51 52 func DotProductGo(a, b []float32) float32 { 53 var sum float32 54 for i := range a { 55 sum += a[i] * b[i] 56 } 57 58 return -sum 59 } 60 61 func (d DotProductProvider) SingleDist(a, b []float32) (float32, bool, error) { 62 if len(a) != len(b) { 63 return 0, false, errors.Errorf("vector lengths don't match: %d vs %d", 64 len(a), len(b)) 65 } 66 67 prod := -dotProductImplementation(a, b) 68 69 return prod, true, nil 70 } 71 72 func (d DotProductProvider) Type() string { 73 return "dot" 74 } 75 76 func (d DotProductProvider) New(a []float32) Distancer { 77 return &DotProduct{a: a} 78 } 79 80 func (d DotProductProvider) Step(x, y []float32) float32 { 81 var sum float32 82 for i := range x { 83 sum += x[i] * y[i] 84 } 85 86 return sum 87 } 88 89 func (d DotProductProvider) Wrap(x float32) float32 { 90 return -x 91 }