feat(matching): rank with semantic embeddings and explain matches by evidence
This commit is contained in:
1 parent
facc1789b1
commit
24b64d698a
215 files changed
+16951
-327
No files matched your search
@@ -0,0 +1,102 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
// ErrInvalidSemanticVector reports a vector that cannot be stored or used.
|
||||
var ErrInvalidSemanticVector = errors.New("invalid semantic vector")
|
||||
|
||||
const (
|
||||
// MaxSemanticDimension matches the ML contract bound of one vector.
|
||||
MaxSemanticDimension = 4096
|
||||
// semanticNormTolerance is how far a stored vector may be from unit
|
||||
// length; float32 encoding stays far below it.
|
||||
semanticNormTolerance = 1e-3
|
||||
maxSemanticModelText = 200
|
||||
)
|
||||
|
||||
var semanticModelTextPattern = regexp.MustCompile(`^[A-Za-z0-9._/-]{1,200}$`)
|
||||
|
||||
// SemanticModel identifies the encoder of a vector: the model, the pinned
|
||||
// revision of its weights, and the prompt and pooling recipe. Vectors of two
|
||||
// different models are never compared.
|
||||
type SemanticModel struct {
|
||||
ID string
|
||||
Revision string
|
||||
PromptVersion string
|
||||
}
|
||||
|
||||
// Validate rejects an empty or malformed model identity.
|
||||
func (model SemanticModel) Validate() error {
|
||||
for _, part := range []string{model.ID, model.Revision, model.PromptVersion} {
|
||||
if len(part) > maxSemanticModelText || !semanticModelTextPattern.MatchString(part) {
|
||||
return fmt.Errorf("domain.SemanticModel.Validate - model identity is malformed: %w", ErrInvalidSemanticVector)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SemanticVector is one L2-normalized float32 vector.
|
||||
type SemanticVector []float32
|
||||
|
||||
// NewSemanticVector checks the dimension, finiteness, and unit length.
|
||||
func NewSemanticVector(values []float32) (SemanticVector, error) {
|
||||
const location = "domain.NewSemanticVector"
|
||||
if len(values) == 0 || len(values) > MaxSemanticDimension {
|
||||
return nil, fmt.Errorf("%s - dimension is out of range: %w", location, ErrInvalidSemanticVector)
|
||||
}
|
||||
var norm float64
|
||||
for _, value := range values {
|
||||
if math.IsNaN(float64(value)) || math.IsInf(float64(value), 0) {
|
||||
return nil, fmt.Errorf("%s - value is not finite: %w", location, ErrInvalidSemanticVector)
|
||||
}
|
||||
norm += float64(value) * float64(value)
|
||||
}
|
||||
if math.Abs(math.Sqrt(norm)-1) > semanticNormTolerance {
|
||||
return nil, fmt.Errorf("%s - vector is not normalized: %w", location, ErrInvalidSemanticVector)
|
||||
}
|
||||
return append(SemanticVector(nil), values...), nil
|
||||
}
|
||||
|
||||
// Encode stores the vector as little-endian float32: exact, compact (four
|
||||
// bytes a dimension), and independent of the platform.
|
||||
func (vector SemanticVector) Encode() []byte {
|
||||
encoded := make([]byte, 4*len(vector))
|
||||
for index, value := range vector {
|
||||
binary.LittleEndian.PutUint32(encoded[4*index:], math.Float32bits(value))
|
||||
}
|
||||
return encoded
|
||||
}
|
||||
|
||||
// DecodeSemanticVector reads a stored vector of the given dimension.
|
||||
func DecodeSemanticVector(encoded []byte, dimension int) (SemanticVector, error) {
|
||||
if dimension <= 0 || dimension > MaxSemanticDimension || len(encoded) != 4*dimension {
|
||||
return nil, fmt.Errorf("domain.DecodeSemanticVector - length does not match the dimension: %w", ErrInvalidSemanticVector)
|
||||
}
|
||||
vector := make(SemanticVector, dimension)
|
||||
for index := range vector {
|
||||
vector[index] = math.Float32frombits(binary.LittleEndian.Uint32(encoded[4*index:]))
|
||||
}
|
||||
return vector, nil
|
||||
}
|
||||
|
||||
// Cosine is the dot product of two normalized vectors, summed in float64 in
|
||||
// index order without fused multiply-add so the same vectors give the same value on every platform. It
|
||||
// returns false for vectors of different dimensions.
|
||||
func (vector SemanticVector) Cosine(other SemanticVector) (float64, bool) {
|
||||
if len(vector) == 0 || len(vector) != len(other) {
|
||||
return 0, false
|
||||
}
|
||||
var sum float64
|
||||
for index := range vector {
|
||||
// The explicit conversion rounds the product before the addition,
|
||||
// so no platform fuses them into one multiply-add with another result.
|
||||
sum += float64(float64(vector[index]) * float64(other[index])) //nolint:gosec // the lengths are equal, checked above
|
||||
}
|
||||
return sum, true
|
||||
}
|
||||
Reference in new issue
Block a user