forked from cosdata/cosdata
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest.py
539 lines (438 loc) · 18.2 KB
/
test.py
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
import requests
import json
import numpy as np
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
import urllib3
import random
# Suppress only the single InsecureRequestWarning from urllib3 needed for this script
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# Define your dynamic variables
token = None
host = "https://127.0.0.1:8443"
base_url = f"{host}/vectordb"
def generate_headers():
return {"Authorization": f"Bearer {token}", "Content-type": "application/json"}
def create_session():
url = f"{host}/auth/create-session"
data = {"username": "admin", "password": "admin"}
response = requests.post(
url, headers=generate_headers(), data=json.dumps(data), verify=False
)
session = response.json()
global token
token = session["access_token"]
return token
def create_db(name, description=None, dimension=1024):
url = f"{base_url}/collections"
data = {
"name": name,
"description": description,
"dense_vector": {
"enabled": True,
"auto_create_index": False,
"dimension": dimension,
},
"sparse_vector": {"enabled": False, "auto_create_index": False},
"metadata_schema": None,
"config": {"max_vectors": None, "replication_factor": None},
}
response = requests.post(
url, headers=generate_headers(), data=json.dumps(data), verify=False
)
return response.json()
def create_explicit_index(name):
data = {
"name": name, # Name of the index
"distance_metric_type": "cosine", # Type of distance metric (e.g., cosine, euclidean)
"quantization": {"type": "auto", "properties": {"sample_threshold": 100}},
"index": {
"type": "hnsw",
"properties": {
"num_layers": 7,
"max_cache_size": 1000,
"ef_construction": 512,
"ef_search": 256,
"neighbors_count": 32,
"layer_0_neighbors_count": 64,
},
},
}
response = requests.post(
f"{base_url}/collections/{name}/indexes/dense",
headers=generate_headers(),
data=json.dumps(data),
verify=False,
)
return response.json()
# Function to create database (collection)
def create_db_old(vector_db_name, dimensions, max_val, min_val):
url = f"{base_url}/collections"
data = {
"vector_db_name": vector_db_name,
"dimensions": dimensions,
"max_val": max_val,
"min_val": min_val,
}
response = requests.post(
url, headers=generate_headers(), data=json.dumps(data), verify=False
)
return response.json()
# Function to find a database (collection) by Id
def find_collection(id):
url = f"{base_url}/collections/{id}"
response = requests.get(url, headers=generate_headers(), verify=False)
return response.json()
def create_transaction(collection_name):
url = f"{base_url}/collections/{collection_name}/transactions"
data = {"index_type": "dense"}
response = requests.post(
url, data=json.dumps(data), headers=generate_headers(), verify=False
)
return response.json()
def create_vector_in_transaction(collection_name, transaction_id, vector):
url = f"{base_url}/collections/{collection_name}/transactions/{transaction_id}/vectors"
data = {"id": vector["id"], "values": vector["values"], "metadata": {}}
print(f"Request URL: {url}")
print(f"Request Data: {json.dumps(data)}")
response = requests.post(
url, headers=generate_headers(), data=json.dumps(data), verify=False
)
print(f"Response Status: {response.status_code}")
print(f"Response Text: {response.text}")
if response.status_code not in [200, 204]:
raise Exception(f"Failed to create vector: {response.status_code}")
return response.json() if response.text else None
def upsert_in_transaction(collection_name, transaction_id, vectors):
url = (
f"{base_url}/collections/{collection_name}/transactions/{transaction_id}/upsert"
)
data = {"index_type": "dense", "vectors": vectors}
print(f"Request URL: {url}")
print(f"Request Vectors Count: {len(vectors)}")
response = requests.post(
url, headers=generate_headers(), data=json.dumps(data), verify=False
)
print(f"Response Status: {response.status_code}")
if response.status_code not in [200, 204]:
raise Exception(f"Failed to create vector: {response.status_code}")
def upsert_vectors_in_transaction(collection_name, transaction_id, vectors):
url = f"{base_url}/collections/{collection_name}/transactions/{transaction_id}/vectors"
data = {"index_type": "dense", "vectors": vectors}
response = requests.post(
url, headers=generate_headers(), data=json.dumps(data), verify=False
)
return response.json()
def commit_transaction(collection_name, transaction_id):
url = (
f"{base_url}/collections/{collection_name}/transactions/{transaction_id}/commit"
)
data = {"index_type": "dense"}
response = requests.post(
url, data=json.dumps(data), headers=generate_headers(), verify=False
)
if response.status_code not in [200, 204]:
print(f"Error response: {response.text}")
raise Exception(f"Failed to commit transaction: {response.status_code}")
return response.json() if response.text else None
def abort_transaction(collection_name, transaction_id):
url = (
f"{base_url}/collections/{collection_name}/transactions/{transaction_id}/abort"
)
data = {"index_type": "dense"}
response = requests.post(
url, data=json.dumps(data), headers=generate_headers(), verify=False
)
return response.json()
# Function to upsert vectors
def upsert_vector(vector_db_name, vectors):
url = f"{base_url}/upsert"
data = {"vector_db_name": vector_db_name, "vectors": vectors}
response = requests.post(
url, headers=generate_headers(), data=json.dumps(data), verify=False
)
return response.json()
# Function to search vector
def ann_vector_old(idd, vector_db_name, vector):
url = f"{base_url}/search"
data = {"vector_db_name": vector_db_name, "vector": vector}
response = requests.post(
url, headers=generate_headers(), data=json.dumps(data), verify=False
)
return (idd, response.json())
def ann_vector(idd, vector_db_name, vector):
url = f"{base_url}/search"
data = {"vector_db_name": vector_db_name, "vector": vector, "nn_count": 5}
response = requests.post(
url, headers=generate_headers(), data=json.dumps(data), verify=False
)
if response.status_code != 200:
print(f"Error response: {response.text}")
raise Exception(f"Failed to search vector: {response.status_code}")
result = response.json()
# Handle empty results gracefully
if not result.get("RespVectorKNN", {}).get("knn"):
return (idd, {"RespVectorKNN": {"knn": []}})
return (idd, result)
# Function to fetch vector
def fetch_vector(vector_db_name, vector_id):
url = f"{base_url}/fetch"
data = {"vector_db_name": vector_db_name, "vector_id": vector_id}
response = requests.post(
url, headers=generate_headers(), data=json.dumps(data), verify=False
)
return response.json()
# Function to generate a random vector with given constraints
def generate_random_vector(rows, dimensions, min_val, max_val):
return np.random.uniform(min_val, max_val, (rows, dimensions)).tolist()
def generate_random_vector_with_id(id, length):
values = np.random.uniform(-1, 1, length).tolist()
return {"id": id, "values": values}
def perturb_vector(vector, perturbation_degree):
# Generate the perturbation
perturbation = np.random.uniform(
-perturbation_degree, perturbation_degree, len(vector["values"])
)
# Apply the perturbation and clamp the values within the range of -1 to 1
perturbed_values = np.array(vector["values"]) + perturbation
clamped_values = np.clip(perturbed_values, -1, 1)
vector["values"] = clamped_values.tolist()
return vector
def dot_product(vec1, vec2):
return sum(v1 * v2 for v1, v2 in zip(vec1, vec2))
def magnitude(vec):
return np.sqrt(sum(v**2 for v in vec))
def cosine_similarity(vec1, vec2):
dot_prod = dot_product(vec1, vec2)
magnitude_vec1 = magnitude(vec1)
magnitude_vec2 = magnitude(vec2)
if magnitude_vec1 == 0 or magnitude_vec2 == 0:
return 0.0 # Handle the case where one or both vectors are zero vectors
return dot_prod / (magnitude_vec1 * magnitude_vec2)
def generate_perturbation(base_vector, idd, perturbation_degree, dimensions):
# Generate the perturbation
perturbation = np.random.uniform(
-perturbation_degree, perturbation_degree, dimensions
)
# Apply the perturbation and clamp the values within the range of -1 to 1
# perturbed_values = base_vector["values"] + perturbation
perturbed_values = np.array(base_vector["values"]) + perturbation
clamped_values = np.clip(perturbed_values, -1, 1)
perturbed_vector = {"id": idd, "values": clamped_values.tolist()}
# print(base_vector["values"][:10])
# print( perturbed_vector["values"][:10] )
# cs = cosine_similarity(base_vector["values"], perturbed_vector["values"] )
# print ("cosine similarity of perturbed vec: ", row_ct, cs)
return perturbed_vector
# if np.random.rand() < 0.01: # 1 in 100 probability
# shortlisted_vectors.append(perturbed_vector)
def process_base_vector_batch(
req_ct, base_idx, vector_db_name, transaction_id, dimensions, perturbation_degree
):
try:
# Generate one base vector
base_vector = generate_random_vector_with_id(
req_ct * 10000 + base_idx * 100, dimensions
)
# Create batch containing base vector and its perturbations
batch_vectors = [base_vector] # Start with base vector
# Generate 99 perturbations for this base vector
for i in range(99):
perturbed_vector = generate_perturbation(
base_vector,
req_ct * 10000
+ base_idx * 100
+ i
+ 1, # Unique ID for each perturbation
perturbation_degree,
dimensions,
)
batch_vectors.append(perturbed_vector)
# Submit this base vector and its perturbations as one batch
upsert_in_transaction(vector_db_name, transaction_id, batch_vectors)
print(
f"Upsert complete for base vector {base_idx} and its {len(batch_vectors) - 1} perturbations"
)
return (
base_idx,
generate_perturbation(
base_vector,
req_ct * 10000
+ base_idx * 100
+ i
+ 1, # Unique ID for each perturbation
perturbation_degree,
dimensions,
),
batch_vectors,
)
except Exception as e:
print(f"Error processing base vector {base_idx}: {e}")
raise
def cosine_similarity(vec1, vec2):
# Convert inputs to numpy arrays
vec1 = np.asarray(vec1)
vec2 = np.asarray(vec2)
# Check if vectors have the same length
if vec1.shape != vec2.shape:
raise ValueError("Vectors must have the same length")
# Calculate magnitudes
magnitude1 = np.linalg.norm(vec1)
magnitude2 = np.linalg.norm(vec2)
# Check for zero vectors
if magnitude1 == 0 or magnitude2 == 0:
raise ValueError("Cannot compute cosine similarity for zero vectors")
# Calculate dot product
dot_product = np.dot(vec1, vec2)
# Calculate cosine similarity
cosine_sim = dot_product / (magnitude1 * magnitude2)
return cosine_sim
def bruteforce_search(vectors, query, k=5):
similarities = []
for vector in vectors:
similarity = cosine_similarity(query["values"], vector["values"])
similarities.append((vector["id"], similarity))
similarities.sort(key=lambda x: x[1], reverse=True)
return similarities[:k]
def generate_vectors(req_ct, batch_count, batch_size, dimensions, perturbation_degree):
vectors = []
for base_idx in range(batch_count):
base_vector = generate_random_vector_with_id(
(req_ct * batch_count * batch_size) + (base_idx * batch_size), dimensions
)
vectors.append(base_vector)
for i in range(batch_size - 1):
perturbed_vector = generate_perturbation(
base_vector,
(req_ct * batch_count * batch_size)
+ (base_idx * batch_size + i + 1), # Unique ID for each perturbation
perturbation_degree,
dimensions,
)
vectors.append(perturbed_vector)
# Shuffle the vectors
np.random.shuffle(vectors)
return vectors
def search(vectors, vector_db_name, query):
ann_response = ann_vector(query["id"], vector_db_name, query["values"])
bruteforce_result = bruteforce_search(vectors, query, 5)
return (ann_response, bruteforce_result)
if __name__ == "__main__":
# Create database
vector_db_name = "testdb"
dimensions = 1024
max_val = 1.0
min_val = -1.0
perturbation_degree = 0.95 # Degree of perturbation
batch_size = 100
batch_count = 1000
session_response = create_session()
print("Session Response:", session_response)
create_collection_response = create_db(
name=vector_db_name,
description="Test collection for vector database",
dimension=dimensions,
)
print("Create Collection(DB) Response:", create_collection_response)
# create_explicit_index(vector_db_name)
start_time = time.time()
shortlisted_vectors = []
for req_ct in range(1):
transaction_id = None
try:
# Create a new transaction
transaction_response = create_transaction(vector_db_name)
transaction_id = transaction_response["transaction_id"]
print(f"Created transaction: {transaction_id}")
vectors = generate_vectors(
req_ct, batch_count, batch_size, dimensions, perturbation_degree
)
# Process vectors concurrently
with ThreadPoolExecutor(max_workers=32) as executor:
futures = []
for base_idx in range(batch_count):
futures.append(
executor.submit(
upsert_in_transaction,
vector_db_name,
transaction_id,
vectors[
base_idx * batch_size : (base_idx * batch_size)
+ batch_size
],
)
)
if random.random() < 0.9:
continue
shortlisted_vectors.append(
generate_perturbation(
vectors[base_idx * batch_size],
base_idx,
perturbation_degree,
dimensions,
)
)
# Collect results
for future in as_completed(futures):
try:
future.result()
except Exception as e:
print(f"Error in future: {e}")
# Commit the transaction after all vectors are inserted
commit_response = commit_transaction(vector_db_name, transaction_id)
print(f"Committed transaction {transaction_id}: {commit_response}")
transaction_id = None
except Exception as e:
print(f"Error in transaction: {e}")
if transaction_id:
try:
abort_transaction(vector_db_name, transaction_id)
print(f"Aborted transaction {transaction_id} due to error")
except Exception as abort_error:
print(f"Error aborting transaction: {abort_error}")
# End time
end_time = time.time()
# Search vector concurrently using perturbed vectors
best_matches_server = []
best_matches_bruteforce = []
with ThreadPoolExecutor(max_workers=32) as executor:
futures = []
for query in shortlisted_vectors:
futures.append(executor.submit(search, vectors, vector_db_name, query))
for i, future in enumerate(as_completed(futures)):
try:
((idr, ann_response), (bruteforce_results)) = future.result()
if (
"RespVectorKNN" in ann_response
and "knn" in ann_response["RespVectorKNN"]
):
print(f"ANN Vector Response:")
print(" Server:")
for j, match in enumerate(ann_response["RespVectorKNN"]["knn"][:5]):
id = match[0]
cs = match[1]["CosineSimilarity"]
print(f" {j + 1}: {id} ({cs})")
best_matches_server.append(
ann_response["RespVectorKNN"]["knn"][0][1]["CosineSimilarity"]
) # Collect the second item in the knn list
print(" Brute force:")
for j, result in enumerate(bruteforce_results):
cs = result[1]
id = result[0]
print(f" {j + 1}: {id} ({cs})")
best_matches_bruteforce.append(bruteforce_results[0][1])
except Exception as e:
print(f"Error in ANN vector {i + 1}: {e}")
if best_matches_server:
best_match_server_average = sum(best_matches_server) / len(best_matches_server)
best_match_bruteforce_average = sum(best_matches_bruteforce) / len(
best_matches_bruteforce
)
print(f"\n\nBest Match Server Average: {best_match_server_average}")
print(f"Best Match Brute force Average: {best_match_bruteforce_average}")
else:
print("No valid matches found.")
# Calculate elapsed time
elapsed_time = end_time - start_time
# Print elapsed time
print(f"Elapsed time: {elapsed_time} seconds")