-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfvecs_normalize.py
More file actions
144 lines (108 loc) · 4.43 KB
/
fvecs_normalize.py
File metadata and controls
144 lines (108 loc) · 4.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#!/usr/bin/env python3
import argparse
import os
import shutil
import struct
import numpy as np
def read_fvecs(fname):
fname = os.path.expanduser(fname)
data = np.fromfile(fname, dtype=np.float32)
if data.size == 0:
return np.empty((0, 0), dtype=np.float32)
dim = struct.unpack("<I", data[:1].tobytes())[0]
if dim <= 0:
raise ValueError(f"Invalid dimension {dim} in {fname}")
row_width = dim + 1
if data.size % row_width != 0:
raise ValueError(
f"File size is not consistent with fvecs format: "
f"{fname}, dim={dim}, float_count={data.size}"
)
data = data.reshape(-1, row_width)
dims = data[:, 0].view(np.int32)
if not np.all(dims == dim):
raise ValueError(f"Inconsistent vector dimensions in {fname}")
return np.ascontiguousarray(data[:, 1:], dtype=np.float32)
def write_fvecs(fname, arr):
arr = np.asarray(arr, dtype=np.float32)
if arr.ndim != 2:
raise ValueError(f"Expected 2D array, got shape {arr.shape}")
n, d = arr.shape
fname = os.path.expanduser(fname)
d_repr = struct.unpack("<f", np.uint32(d))[0]
formatted = np.concatenate(
(np.full((n, 1), d_repr, dtype=np.float32), arr),
axis=1
)
if n > 0:
assert struct.unpack("<I", formatted[0, 0].tobytes()) == (d,)
with open(fname, "wb") as f:
formatted.tofile(f)
def normalization_error_stats(vecs):
norms = np.linalg.norm(vecs, axis=1)
errors = np.abs(norms - 1.0)
if errors.size == 0:
return {
"max_abs_error": 0.0,
"mean_abs_error": 0.0,
}
return {
"max_abs_error": float(np.max(errors)),
"mean_abs_error": float(np.mean(errors)),
}
def check_normalization(vecs, tol=1e-3):
"""
Returns True if all vectors in the array are approximately normalized
(L2 norm close to 1 within the specified tolerance).
"""
norms = np.linalg.norm(vecs, axis=1)
return np.all(np.abs(norms - 1) < tol)
def normalize_vectors(arr):
arr = np.asarray(arr, dtype=np.float32)
if arr.ndim != 2:
raise ValueError(f"Expected 2D array, got shape {arr.shape}")
norms = np.linalg.norm(arr, axis=1, keepdims=True)
norms[norms == 0] = 1.0
return np.ascontiguousarray(arr / norms, dtype=np.float32)
def main():
parser = argparse.ArgumentParser(description="Normalize vectors in an fvecs file.")
parser.add_argument("--input", required=True, help="Input fvecs file")
parser.add_argument("--output", required=True, help="Output normalized fvecs file")
parser.add_argument(
"--tolerance",
type=float,
default=1e-3,
help="Tolerance for considering vectors already normalized (default: 1e-3)",
)
args = parser.parse_args()
if args.tolerance < 0:
raise ValueError("--tolerance must be non-negative")
vectors = read_fvecs(args.input)
normalized_before = check_normalization(vectors, tol=args.tolerance)
before_stats = normalization_error_stats(vectors)
print(f"Normalization tolerance: {args.tolerance}")
print("Vectors normalized before:", "Yes" if normalized_before else "No")
print(f"Max abs norm error before: {before_stats['max_abs_error']:.8g}")
print(f"Mean abs norm error before: {before_stats['mean_abs_error']:.8g}")
print(f"Vectors: {vectors.shape[0]}")
print(f"Dimension: {vectors.shape[1] if vectors.size > 0 else 0}")
input_path = os.path.expanduser(args.input)
output_path = os.path.expanduser(args.output)
if normalized_before:
print("Input is already normalized. Skipping normalization.")
if os.path.abspath(input_path) != os.path.abspath(output_path):
shutil.copyfile(input_path, output_path)
print(f"Copied input to output without changes: {output_path}")
else:
print("Input and output are the same file. No action needed.")
return
normalized = normalize_vectors(vectors)
normalized_after = check_normalization(normalized, tol=args.tolerance)
after_stats = normalization_error_stats(normalized)
print("Vectors normalized after:", "Yes" if normalized_after else "No")
print(f"Max abs norm error after: {after_stats['max_abs_error']:.8g}")
print(f"Mean abs norm error after: {after_stats['mean_abs_error']:.8g}")
write_fvecs(output_path, normalized)
print(f"Wrote normalized file to: {output_path}")
if __name__ == "__main__":
main()