utils.py 24.3 KB
Newer Older
1 2
import os
import sys
J
JinHai-CN 已提交
3
import random
4
import pdb
J
JinHai-CN 已提交
5 6
import string
import struct
G
groot 已提交
7
import logging
J
JinHai-CN 已提交
8 9 10
import time, datetime
import copy
import numpy as np
11
from sklearn import preprocessing
12
from milvus import Milvus, DataType
J
JinHai-CN 已提交
13

14
port = 19530
15
epsilon = 0.000001
D
del-zhenwu 已提交
16 17
default_flush_interval = 1
big_flush_interval = 1000
18
dimension = 128
19 20
nb = 6000
top_k = 10
21
segment_row_count = 5000
22 23
default_float_vec_field_name = "float_vector"
default_binary_vec_field_name = "binary_vector"
24

25
# TODO:
D
del-zhenwu 已提交
26
all_index_types = [
27 28 29 30 31 32 33 34 35 36
    "FLAT",
    "IVF_FLAT",
    "IVF_SQ8",
    "IVF_SQ8_HYBRID",
    "IVF_PQ",
    "HNSW",
    # "NSG",
    "ANNOY",
    "BIN_FLAT",
    "BIN_IVF_FLAT"
D
del-zhenwu 已提交
37 38
]

39 40 41 42 43 44 45 46
default_index_params = [
    {"nlist": 1024},
    {"nlist": 1024},
    {"nlist": 1024},
    {"nlist": 1024},
    {"nlist": 1024, "m": 16},
    {"M": 48, "efConstruction": 500},
    # {"search_length": 50, "out_degree": 40, "candidate_pool_size": 100, "knng": 50},
47
    {"n_trees": 50},
48 49 50
    {"nlist": 1024},
    {"nlist": 1024}
]
51

J
JinHai-CN 已提交
52

53 54
def index_cpu_not_support():
    return ["IVF_SQ8_HYBRID"]
D
del-zhenwu 已提交
55 56


57 58
def binary_support():
    return ["BIN_FLAT", "BIN_IVF_FLAT"]
D
del-zhenwu 已提交
59 60


61 62
def delete_support():
    return ["FLAT", "IVF_FLAT", "IVF_SQ8", "IVF_SQ8_HYBRID", "IVF_PQ"]
J
JinHai-CN 已提交
63

G
groot 已提交
64

65 66
def ivf():
    return ["FLAT", "IVF_FLAT", "IVF_SQ8", "IVF_SQ8_HYBRID", "IVF_PQ"]
J
JinHai-CN 已提交
67 68


D
del-zhenwu 已提交
69 70 71 72
def binary_metrics():
    return ["JACCARD", "HAMMING", "TANIMOTO", "SUBSTRUCTURE", "SUPERSTRUCTURE"]


73 74 75 76 77 78
def l2(x, y):
    return np.linalg.norm(np.array(x) - np.array(y))


def ip(x, y):
    return np.inner(np.array(x), np.array(y))
G
groot 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98


def jaccard(x, y):
    x = np.asarray(x, np.bool)
    y = np.asarray(y, np.bool)
    return 1 - np.double(np.bitwise_and(x, y).sum()) / np.double(np.bitwise_or(x, y).sum())


def hamming(x, y):
    x = np.asarray(x, np.bool)
    y = np.asarray(y, np.bool)
    return np.bitwise_xor(x, y).sum()


def tanimoto(x, y):
    x = np.asarray(x, np.bool)
    y = np.asarray(y, np.bool)
    return -np.log2(np.double(np.bitwise_and(x, y).sum()) / np.double(np.bitwise_or(x, y).sum()))


D
del-zhenwu 已提交
99 100 101 102 103 104 105 106 107 108 109 110
def substructure(x, y):
    x = np.asarray(x, np.bool)
    y = np.asarray(y, np.bool)
    return 1 - np.double(np.bitwise_and(x, y).sum()) / np.count_nonzero(y)


def superstructure(x, y):
    x = np.asarray(x, np.bool)
    y = np.asarray(y, np.bool)
    return 1 - np.double(np.bitwise_and(x, y).sum()) / np.count_nonzero(x)


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
def get_milvus(host, port, uri=None, handler=None, **kwargs):
    if handler is None:
        handler = "GRPC"
    try_connect = kwargs.get("try_connect", True)
    if uri is not None:
        milvus = Milvus(uri=uri, handler=handler, try_connect=try_connect)
    else:
        milvus = Milvus(host=host, port=port, handler=handler, try_connect=try_connect)
    return milvus


def disable_flush(connect):
    connect.set_config("storage", "auto_flush_interval", big_flush_interval)


def enable_flush(connect):
    # reset auto_flush_interval=1
    connect.set_config("storage", "auto_flush_interval", default_flush_interval)
    config_value = connect.get_config("storage", "auto_flush_interval")
    assert config_value == str(default_flush_interval)


def gen_inaccuracy(num):
    return num / 255.0


137
def gen_vectors(num, dim, is_normal=True):
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
    vectors = [[random.random() for _ in range(dim)] for _ in range(num)]
    vectors = preprocessing.normalize(vectors, axis=1, norm='l2')
    return vectors.tolist()


# def gen_vectors(num, dim, seed=np.random.RandomState(1234), is_normal=False):
#     xb = seed.rand(num, dim).astype("float32")
#     xb = preprocessing.normalize(xb, axis=1, norm='l2')
#     return xb.tolist()


def gen_binary_vectors(num, dim):
    raw_vectors = []
    binary_vectors = []
    for i in range(num):
        raw_vector = [random.randint(0, 1) for i in range(dim)]
        raw_vectors.append(raw_vector)
        binary_vectors.append(bytes(np.packbits(raw_vector, axis=-1).tolist()))
    return raw_vectors, binary_vectors


159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
def gen_binary_sub_vectors(vectors, length):
    raw_vectors = []
    binary_vectors = []
    dim = len(vectors[0])
    for i in range(length):
        raw_vector = [0 for i in range(dim)]
        vector = vectors[i]
        for index, j in enumerate(vector):
            if j == 1:
                raw_vector[index] = 1
        raw_vectors.append(raw_vector)
        binary_vectors.append(bytes(np.packbits(raw_vector, axis=-1).tolist()))
    return raw_vectors, binary_vectors


def gen_binary_super_vectors(vectors, length):
    raw_vectors = []
    binary_vectors = []
    dim = len(vectors[0])
    for i in range(length):
        cnt_1 = np.count_nonzero(vectors[i])
180
        raw_vector = [1 for i in range(dim)]
181 182 183 184
        raw_vectors.append(raw_vector)
        binary_vectors.append(bytes(np.packbits(raw_vector, axis=-1).tolist()))
    return raw_vectors, binary_vectors

J
JinHai-CN 已提交
185

Y
yukun 已提交
186 187 188
def gen_int_attr(row_num):
    return [random.randint(0, 255) for _ in range(row_num)]

189

Y
yukun 已提交
190 191
def gen_float_attr(row_num):
    return [random.uniform(0, 255) for _ in range(row_num)]
J
JinHai-CN 已提交
192 193


Z
zhenwu 已提交
194
def gen_unique_str(str_value=None):
J
JinHai-CN 已提交
195
    prefix = "".join(random.choice(string.ascii_letters + string.digits) for _ in range(8))
196
    return "test_" + prefix if str_value is None else str_value + "_" + prefix
J
JinHai-CN 已提交
197 198


199 200 201
def gen_single_filter_fields():
    fields = []
    for data_type in DataType:
D
del-zhenwu 已提交
202
        if data_type in [DataType.INT32, DataType.INT64, DataType.FLOAT, DataType.DOUBLE]:
203 204 205 206 207 208
            fields.append({"field": data_type.name, "type": data_type})
    return fields


def gen_single_vector_fields():
    fields = []
209 210 211
    for data_type in [DataType.FLOAT_VECTOR, DataType.BINARY_VECTOR]:
        field = {"field": data_type.name, "type": data_type, "params": {"dim": dimension}}
        fields.append(field)
212 213 214
    return fields


215
def gen_default_fields(auto_id=True):
216 217 218 219
    default_fields = {
        "fields": [
            {"field": "int64", "type": DataType.INT64},
            {"field": "float", "type": DataType.FLOAT},
220
            {"field": default_float_vec_field_name, "type": DataType.FLOAT_VECTOR, "params": {"dim": dimension}},
221
        ],
222
        "segment_row_count": segment_row_count,
223
        "auto_id" : auto_id 
224
    }
D
del-zhenwu 已提交
225 226 227
    return default_fields


228
def gen_binary_default_fields(auto_id=True):
D
del-zhenwu 已提交
229 230 231 232 233 234
    default_fields = {
        "fields": [
            {"field": "int64", "type": DataType.INT64},
            {"field": "float", "type": DataType.FLOAT},
            {"field": default_binary_vec_field_name, "type": DataType.BINARY_VECTOR, "params": {"dim": dimension}}
        ],
235 236
        "segment_row_count": segment_row_count,
        "auto_id" : auto_id 
D
del-zhenwu 已提交
237
    }
238 239 240 241 242 243
    return default_fields


def gen_entities(nb, is_normal=False):
    vectors = gen_vectors(nb, dimension, is_normal)
    entities = [
244 245
        {"field": "int64", "type": DataType.INT64, "values": [i for i in range(nb)]},
        {"field": "float", "type": DataType.FLOAT, "values": [float(i) for i in range(nb)]},
246
        {"field": default_float_vec_field_name, "type": DataType.FLOAT_VECTOR, "values": vectors}
247 248 249 250 251 252 253
    ]
    return entities


def gen_binary_entities(nb):
    raw_vectors, vectors = gen_binary_vectors(nb, dimension)
    entities = [
254 255
        {"field": "int64", "type": DataType.INT64, "values": [i for i in range(nb)]},
        {"field": "float", "type": DataType.FLOAT, "values": [float(i) for i in range(nb)]},
256
        {"field": default_binary_vec_field_name, "type": DataType.BINARY_VECTOR, "values": vectors}
257 258 259 260 261 262 263
    ]
    return raw_vectors, entities


def gen_entities_by_fields(fields, nb, dimension):
    entities = []
    for field in fields:
D
del-zhenwu 已提交
264
        if field["type"] in [DataType.INT32, DataType.INT64]:
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
            field_value = [1 for i in range(nb)]
        elif field["type"] in [DataType.FLOAT, DataType.DOUBLE]:
            field_value = [3.0 for i in range(nb)]
        elif field["type"] == DataType.BINARY_VECTOR:
            field_value = gen_binary_vectors(nb, dimension)[1]
        elif field["type"] == DataType.FLOAT_VECTOR:
            field_value = gen_vectors(nb, dimension)
        field.update({"values": field_value})
        entities.append(field)
    return entities


def assert_equal_entity(a, b):
    pass


281
def gen_query_vectors(field_name, entities, top_k, nq, search_params={"nprobe": 10}, rand_vector=False,
282
                      metric_type="L2"):
283 284 285 286 287 288
    if rand_vector is True:
        dimension = len(entities[-1]["values"][0])
        query_vectors = gen_vectors(nq, dimension)
    else:
        query_vectors = entities[-1]["values"][:nq]
    must_param = {"vector": {field_name: {"topk": top_k, "query": query_vectors, "params": search_params}}}
289
    must_param["vector"][field_name]["metric_type"] = metric_type
290 291
    query = {
        "bool": {
292
            "must": [must_param]
293 294 295 296 297
        }
    }
    return query, query_vectors


298 299 300 301 302 303 304 305 306
def update_query_expr(src_query, keep_old=True, expr=None):
    tmp_query = copy.deepcopy(src_query)
    if expr is not None:
        tmp_query["bool"].update(expr)
    if keep_old is not True:
        tmp_query["bool"].pop("must")
    return tmp_query


D
del-zhenwu 已提交
307 308 309 310
def gen_default_vector_expr(default_query):
    return default_query["bool"]["must"][0]


T
ThreadDao 已提交
311
def gen_default_term_expr(keyword="term", field="int64", values=None):
312
    if values is None:
D
del-zhenwu 已提交
313
        values = [i for i in range(nb // 2)]
T
ThreadDao 已提交
314
    expr = {keyword: {field: {"values": values}}}
315 316 317
    return expr


T
ThreadDao 已提交
318 319 320 321 322 323 324 325
def update_term_expr(src_term, terms):
    tmp_term = copy.deepcopy(src_term)
    for term in terms:
        tmp_term["term"].update(term)
    return tmp_term


def gen_default_range_expr(keyword="range", field="int64", ranges=None):
326
    if ranges is None:
D
del-zhenwu 已提交
327
        ranges = {"GT": 1, "LT": nb // 2}
T
ThreadDao 已提交
328
    expr = {keyword: {field: ranges}}
329 330 331
    return expr


T
ThreadDao 已提交
332 333 334 335 336 337 338
def update_range_expr(src_range, ranges):
    tmp_range = copy.deepcopy(src_range)
    for range in ranges:
        tmp_range["range"].update(range)
    return tmp_range


339 340
def gen_invalid_range():
    range = [
Y
yukun 已提交
341 342 343
        {"range": 1},
        {"range": {}},
        {"range": []},
T
ThreadDao 已提交
344
        {"range": {"range": {"int64": {"GT": 0, "LT": nb // 2}}}}
345 346 347 348 349 350 351
    ]
    return range


def gen_valid_ranges():
    ranges = [
        {"GT": 0, "LT": nb//2},
352
        {"GT": nb // 2, "LT": nb*2},
353 354 355 356 357 358 359 360 361 362 363
        {"GT": 0},
        {"LT": nb},
        {"GT": -1, "LT": top_k},
    ]
    return ranges


def gen_invalid_term():
    terms = [
        {"term": 1},
        {"term": []},
T
ThreadDao 已提交
364 365
        {"term": {}},
        {"term": {"term": {"int64": {"values": [i for i in range(nb // 2)]}}}}
366 367 368 369
    ]
    return terms


370 371 372 373 374 375 376 377 378 379 380
def add_field_default(default_fields, type=DataType.INT64, field_name=None):
    tmp_fields = copy.deepcopy(default_fields)
    if field_name is None:
        field_name = gen_unique_str()
    field = {
        "field": field_name,
        "type": type
    }
    tmp_fields["fields"].append(field)
    return tmp_fields

381

382
def add_field(entities, field_name=None):
383
    nb = len(entities[0]["values"])
384 385 386
    tmp_entities = copy.deepcopy(entities)
    if field_name is None:
        field_name = gen_unique_str()
387
    field = {
388 389 390
        "field": field_name,
        "type": DataType.INT64,
        "values": [i for i in range(nb)]
391
    }
392 393
    tmp_entities.append(field)
    return tmp_entities
394 395 396 397 398 399


def add_vector_field(entities, is_normal=False):
    nb = len(entities[0]["values"])
    vectors = gen_vectors(nb, dimension, is_normal)
    field = {
400
        "field": gen_unique_str(),
401 402 403 404 405 406 407
        "type": DataType.FLOAT_VECTOR,
        "values": vectors
    }
    entities.append(field)
    return entities


408 409 410 411 412 413 414 415
# def update_fields_metric_type(fields, metric_type):
#     tmp_fields = copy.deepcopy(fields)
#     if metric_type in ["L2", "IP"]:
#         tmp_fields["fields"][-1]["type"] = DataType.FLOAT_VECTOR
#     else:
#         tmp_fields["fields"][-1]["type"] = DataType.BINARY_VECTOR
#     tmp_fields["fields"][-1]["params"]["metric_type"] = metric_type
#     return tmp_fields
416 417 418 419 420 421 422 423 424 425 426 427 428


def remove_field(entities):
    del entities[0]
    return entities


def remove_vector_field(entities):
    del entities[-1]
    return entities


def update_field_name(entities, old_name, new_name):
D
del-zhenwu 已提交
429 430
    tmp_entities = copy.deepcopy(entities)
    for item in tmp_entities:
431 432
        if item["field"] == old_name:
            item["field"] = new_name
D
del-zhenwu 已提交
433
    return tmp_entities
434 435 436


def update_field_type(entities, old_name, new_name):
D
del-zhenwu 已提交
437 438
    tmp_entities = copy.deepcopy(entities)
    for item in tmp_entities:
439 440
        if item["field"] == old_name:
            item["type"] = new_name
D
del-zhenwu 已提交
441
    return tmp_entities
442 443 444


def update_field_value(entities, old_type, new_value):
D
del-zhenwu 已提交
445 446
    tmp_entities = copy.deepcopy(entities)
    for item in tmp_entities:
447
        if item["type"] == old_type:
D
del-zhenwu 已提交
448 449 450
            for index, value in enumerate(item["values"]):
                item["values"][index] = new_value
    return tmp_entities
451 452 453 454 455 456 457 458 459 460


def add_vector_field(nb, dimension=dimension):
    field_name = gen_unique_str()
    field = {
        "field": field_name,
        "type": DataType.FLOAT_VECTOR,
        "values": gen_vectors(nb, dimension)
    }
    return field_name
461

462

463
def gen_segment_row_counts():
464
    sizes = [
465 466 467 468
        1,
        2,
        1024,
        4096
469 470
    ]
    return sizes
J
JinHai-CN 已提交
471 472 473 474


def gen_invalid_ips():
    ips = [
475 476 477 478 479 480 481 482 483 484 485 486 487 488
        # "255.0.0.0",
        # "255.255.0.0",
        # "255.255.255.0",
        # "255.255.255.255",
        "127.0.0",
        # "123.0.0.2",
        "12-s",
        " ",
        "12 s",
        "BB。A",
        " siede ",
        "(mn)",
        "中文",
        "a".join("a" for _ in range(256))
J
JinHai-CN 已提交
489 490 491 492 493 494 495
    ]
    return ips


def gen_invalid_uris():
    ip = None
    uris = [
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
        " ",
        "中文",
        # invalid protocol
        # "tc://%s:%s" % (ip, port),
        # "tcp%s:%s" % (ip, port),

        # # invalid port
        # "tcp://%s:100000" % ip,
        # "tcp://%s: " % ip,
        # "tcp://%s:19540" % ip,
        # "tcp://%s:-1" % ip,
        # "tcp://%s:string" % ip,

        # invalid ip
        "tcp:// :19530",
        # "tcp://123.0.0.1:%s" % port,
        "tcp://127.0.0:19530",
        # "tcp://255.0.0.0:%s" % port,
        # "tcp://255.255.0.0:%s" % port,
        # "tcp://255.255.255.0:%s" % port,
        # "tcp://255.255.255.255:%s" % port,
        "tcp://\n:19530",
J
JinHai-CN 已提交
518 519 520 521
    ]
    return uris


522 523
def gen_invalid_strs():
    strings = [
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
        1,
        [1],
        None,
        "12-s",
        " ",
        # "",
        # None,
        "12 s",
        "BB。A",
        "c|c",
        " siede ",
        "(mn)",
        "pip+",
        "=c",
        "中文",
        "a".join("a" for i in range(256))
J
JinHai-CN 已提交
540
    ]
541
    return strings
J
JinHai-CN 已提交
542 543


544 545
def gen_invalid_field_types():
    field_types = [
546 547 548 549 550 551
        # 1,
        "=c",
        # 0,
        None,
        "",
        "a".join("a" for i in range(256))
J
JinHai-CN 已提交
552
    ]
553
    return field_types
J
JinHai-CN 已提交
554 555


556 557
def gen_invalid_metric_types():
    metric_types = [
558 559 560 561 562 563
        1,
        "=c",
        0,
        None,
        "",
        "a".join("a" for i in range(256))
J
JinHai-CN 已提交
564
    ]
565
    return metric_types
J
JinHai-CN 已提交
566 567


568 569
# TODO:
def gen_invalid_ints():
570
    int_values = [
571 572 573 574 575
        # 1.0,
        None,
        [1, 2, 3],
        " ",
        "",
576
        -1,
577 578 579 580
        "String",
        "=c",
        "中文",
        "a".join("a" for i in range(256))
J
JinHai-CN 已提交
581
    ]
582
    return int_values
J
JinHai-CN 已提交
583 584


585 586
def gen_invalid_params():
    params = [
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
        9999999999,
        -1,
        # None,
        [1, 2, 3],
        (1, 2),
        {"a": 1},
        " ",
        "",
        "String",
        "12-s",
        "BB。A",
        " siede ",
        "(mn)",
        "pip+",
        "=c",
        "中文"
J
JinHai-CN 已提交
603
    ]
604
    return params
J
JinHai-CN 已提交
605 606 607 608


def gen_invalid_vectors():
    invalid_vectors = [
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
        "1*2",
        [],
        [1],
        [1, 2],
        [" "],
        ['a'],
        [None],
        None,
        (1, 2),
        {"a": 1},
        " ",
        "",
        "String",
        "12-s",
        "BB。A",
        " siede ",
        "(mn)",
        "pip+",
        "=c",
        "中文",
        "a".join("a" for i in range(256))
J
JinHai-CN 已提交
630 631 632 633
    ]
    return invalid_vectors


634
def gen_invaild_search_params():
D
del-zhenwu 已提交
635
    invalid_search_key = 100
636
    search_params = []
D
del-zhenwu 已提交
637
    for index_type in all_index_types:
638
        if index_type == "FLAT":
D
del-zhenwu 已提交
639
            continue
640 641
        search_params.append({"index_type": index_type, "search_params": {"invalid_key": invalid_search_key}})
        if index_type in delete_support():
642
            for nprobe in gen_invalid_params():
643
                ivf_search_params = {"index_type": index_type, "search_params": {"nprobe": nprobe}}
644
                search_params.append(ivf_search_params)
645
        elif index_type == "HNSW":
646
            for ef in gen_invalid_params():
647
                hnsw_search_param = {"index_type": index_type, "search_params": {"ef": ef}}
648
                search_params.append(hnsw_search_param)
649
        elif index_type == "NSG":
D
del-zhenwu 已提交
650
            for search_length in gen_invalid_params():
651
                nsg_search_param = {"index_type": index_type, "search_params": {"search_length": search_length}}
D
del-zhenwu 已提交
652
                search_params.append(nsg_search_param)
653 654
            search_params.append({"index_type": index_type, "search_params": {"invalid_key": 100}})
        elif index_type == "ANNOY":
D
del-zhenwu 已提交
655 656 657
            for search_k in gen_invalid_params():
                if isinstance(search_k, int):
                    continue
658
                annoy_search_param = {"index_type": index_type, "search_params": {"search_k": search_k}}
D
del-zhenwu 已提交
659
                search_params.append(annoy_search_param)
660 661 662 663
    return search_params


def gen_invalid_index():
J
JinHai-CN 已提交
664
    index_params = []
665 666
    for index_type in gen_invalid_strs():
        index_param = {"index_type": index_type, "params": {"nlist": 1024}}
667 668
        index_params.append(index_param)
    for nlist in gen_invalid_params():
669
        index_param = {"index_type": "IVF_FLAT", "params": {"nlist": nlist}}
670 671
        index_params.append(index_param)
    for M in gen_invalid_params():
672
        index_param = {"index_type": "HNSW", "params": {"M": M, "efConstruction": 100}}
J
JinHai-CN 已提交
673
        index_params.append(index_param)
674
    for efConstruction in gen_invalid_params():
675
        index_param = {"index_type": "HNSW", "params": {"M": 16, "efConstruction": efConstruction}}
J
JinHai-CN 已提交
676
        index_params.append(index_param)
D
del-zhenwu 已提交
677
    for search_length in gen_invalid_params():
678 679
        index_param = {"index_type": "NSG",
                       "params": {"search_length": search_length, "out_degree": 40, "candidate_pool_size": 50,
680
                                  "knng": 100}}
D
del-zhenwu 已提交
681 682
        index_params.append(index_param)
    for out_degree in gen_invalid_params():
683 684
        index_param = {"index_type": "NSG",
                       "params": {"search_length": 100, "out_degree": out_degree, "candidate_pool_size": 50,
685
                                  "knng": 100}}
D
del-zhenwu 已提交
686 687
        index_params.append(index_param)
    for candidate_pool_size in gen_invalid_params():
688
        index_param = {"index_type": "NSG", "params": {"search_length": 100, "out_degree": 40,
689 690
                                                       "candidate_pool_size": candidate_pool_size,
                                                       "knng": 100}}
D
del-zhenwu 已提交
691
        index_params.append(index_param)
692 693 694 695
    index_params.append({"index_type": "IVF_FLAT", "params": {"invalid_key": 1024}})
    index_params.append({"index_type": "HNSW", "params": {"invalid_key": 16, "efConstruction": 100}})
    index_params.append({"index_type": "NSG",
                         "params": {"invalid_key": 100, "out_degree": 40, "candidate_pool_size": 300,
696
                                    "knng": 100}})
D
del-zhenwu 已提交
697
    for invalid_n_trees in gen_invalid_params():
698
        index_params.append({"index_type": "ANNOY", "params": {"n_trees": invalid_n_trees}})
D
del-zhenwu 已提交
699

J
JinHai-CN 已提交
700 701 702
    return index_params


703 704 705 706 707 708 709 710 711 712
def gen_index():
    nlists = [1, 1024, 16384]
    pq_ms = [128, 64, 32, 16, 8, 4]
    Ms = [5, 24, 48]
    efConstructions = [100, 300, 500]
    search_lengths = [10, 100, 300]
    out_degrees = [5, 40, 300]
    candidate_pool_sizes = [50, 100, 300]
    knngs = [5, 100, 300]

J
JinHai-CN 已提交
713
    index_params = []
D
del-zhenwu 已提交
714
    for index_type in all_index_types:
715
        if index_type in ["FLAT", "BIN_FLAT", "BIN_IVF_FLAT"]:
716
            index_params.append({"index_type": index_type, "index_param": {"nlist": 1024}})
717
        elif index_type in ["IVF_FLAT", "IVF_SQ8", "IVF_SQ8_HYBRID"]:
718 719 720
            ivf_params = [{"index_type": index_type, "index_param": {"nlist": nlist}} \
                          for nlist in nlists]
            index_params.extend(ivf_params)
721 722
        elif index_type == "IVF_PQ":
            IVFPQ_params = [{"index_type": index_type, "index_param": {"nlist": nlist, "m": m}} \
723 724
                            for nlist in nlists \
                            for m in pq_ms]
725 726
            index_params.extend(IVFPQ_params)
        elif index_type == "HNSW":
727 728 729 730
            hnsw_params = [{"index_type": index_type, "index_param": {"M": M, "efConstruction": efConstruction}} \
                           for M in Ms \
                           for efConstruction in efConstructions]
            index_params.extend(hnsw_params)
731
        elif index_type == "NSG":
D
del-zhenwu 已提交
732 733 734 735 736 737 738 739
            nsg_params = [{"index_type": index_type,
                           "index_param": {"search_length": search_length, "out_degree": out_degree,
                                           "candidate_pool_size": candidate_pool_size, "knng": knng}} \
                          for search_length in search_lengths \
                          for out_degree in out_degrees \
                          for candidate_pool_size in candidate_pool_sizes \
                          for knng in knngs]
            index_params.extend(nsg_params)
J
JinHai-CN 已提交
740

741
    return index_params
J
JinHai-CN 已提交
742 743


744
def gen_simple_index():
J
JinHai-CN 已提交
745
    index_params = []
D
del-zhenwu 已提交
746
    for i in range(len(all_index_types)):
747 748
        if all_index_types[i] in binary_support():
            continue
749
        dic = {"index_type": all_index_types[i], "metric_type": "L2"}
750
        dic.update({"params": default_index_params[i]})
751 752 753 754 755 756 757 758 759
        index_params.append(dic)
    return index_params


def gen_binary_index():
    index_params = []
    for i in range(len(all_index_types)):
        if all_index_types[i] in binary_support():
            dic = {"index_type": all_index_types[i]}
760
            dic.update({"params": default_index_params[i]})
761
            index_params.append(dic)
762
    return index_params
J
JinHai-CN 已提交
763 764


765
def get_search_param(index_type):
766
    search_params = {"metric_type": "L2"}
767
    if index_type in ivf() or index_type in binary_support():
768
        search_params.update({"nprobe": 32})
769
    elif index_type == "HNSW":
770
        search_params.update({"ef": 64})
771
    elif index_type == "NSG":
772
        search_params.update({"search_length": 100})
773
    elif index_type == "ANNOY":
774
        search_params.update({"search_k": 1000})
775
    else:
776 777 778
        logging.getLogger().error("Invalid index_type.")
        raise Exception("Invalid index_type.")
    return search_params
J
JinHai-CN 已提交
779

780

781 782 783 784 785
def assert_equal_vector(v1, v2):
    if len(v1) != len(v2):
        assert False
    for i in range(len(v1)):
        assert abs(v1[i] - v2[i]) < epsilon
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837


def restart_server(helm_release_name):
    res = True
    timeout = 120
    from kubernetes import client, config
    client.rest.logger.setLevel(logging.WARNING)

    namespace = "milvus"
    # service_name = "%s.%s.svc.cluster.local" % (helm_release_name, namespace)
    config.load_kube_config()
    v1 = client.CoreV1Api()
    pod_name = None
    # config_map_names = v1.list_namespaced_config_map(namespace, pretty='true')
    # body = {"replicas": 0}
    pods = v1.list_namespaced_pod(namespace)
    for i in pods.items:
        if i.metadata.name.find(helm_release_name) != -1 and i.metadata.name.find("mysql") == -1:
            pod_name = i.metadata.name
            break
            # v1.patch_namespaced_config_map(config_map_name, namespace, body, pretty='true')
    # status_res = v1.read_namespaced_service_status(helm_release_name, namespace, pretty='true')
    # print(status_res)
    if pod_name is not None:
        try:
            v1.delete_namespaced_pod(pod_name, namespace)
        except Exception as e:
            logging.error(str(e))
            logging.error("Exception when calling CoreV1Api->delete_namespaced_pod")
            res = False
            return res
        time.sleep(5)
        # check if restart successfully
        pods = v1.list_namespaced_pod(namespace)
        for i in pods.items:
            pod_name_tmp = i.metadata.name
            if pod_name_tmp.find(helm_release_name) != -1:
                logging.debug(pod_name_tmp)
                start_time = time.time()
                while time.time() - start_time > timeout:
                    status_res = v1.read_namespaced_pod_status(pod_name_tmp, namespace, pretty='true')
                    if status_res.status.phase == "Running":
                        break
                    time.sleep(1)
                if time.time() - start_time > timeout:
                    logging.error("Restart pod: %s timeout" % pod_name_tmp)
                    res = False
                    return res
    else:
        logging.error("Pod: %s not found" % helm_release_name)
        res = False
    return res