File size: 5,706 Bytes
23a7a20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Compute ANNS workload statistics for evaluation."""

import os
import json
import pandas as pd
import numpy as np
from transformers import AutoTokenizer
import argparse


def parse_pipeline_pool(pool_str: str):
    """Parse pipeline pool string to extract document IDs."""
    pool_str = pool_str.strip('()')
    if not pool_str:
        return []
    return [doc_id.strip() for doc_id in pool_str.split(',')]


def main():
    parser = argparse.ArgumentParser(description="Compute ANNS workload statistics")
    parser.add_argument("--corpus-prefix",
                        default="retrieved_corpus_content",
                        help="Prefix for corpus content part files")
    parser.add_argument("--query-map",
                        default="query_trace_map_5k.json",
                        help="Path to query trace map JSON file")
    parser.add_argument("--trace-dir",
                        default="res",
                        help="Directory containing trace CSV files")
    parser.add_argument("--max-queries",
                        type=int,
                        default=500,
                        help="Maximum number of queries to process")
    parser.add_argument("--tokenizer-model",
                        default="meta-llama/Llama-3.1-8B-Instruct",
                        help="HuggingFace tokenizer model")
    parser.add_argument("--output-dir",
                        default="tables",
                        help="Output directory for statistics file")

    args = parser.parse_args()

    # Load corpus
    print("Loading corpus content...")
    corpus_content = {}
    part_num = 0
    while True:
        part_file = f"{args.corpus_prefix}.{part_num}.json"
        if not os.path.exists(part_file):
            break
        print(f"  Loading {part_file}...")
        with open(part_file, 'r') as f:
            part_data = json.load(f)
            corpus_content.update(part_data)
        part_num += 1

    print(f"Loaded {len(corpus_content)} documents")

    # Load query map
    with open(args.query_map, 'r') as f:
        query_trace_map = json.load(f)

    # Load tokenizer
    print("Loading tokenizer...")
    try:
        tokenizer = AutoTokenizer.from_pretrained(
            args.tokenizer_model, local_files_only=True)
    except:
        tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_model)

    # Process queries
    query_items = list(query_trace_map.items())[:args.max_queries]
    print(f"Processing {len(query_items)} queries...")

    total_query_tokens = []
    query_durations = []

    for query_id, query_info in query_items:
        # Read trace file
        trace_path = os.path.join(args.trace_dir, query_info['trace_file'])
        if not os.path.exists(trace_path):
            continue

        try:
            df = pd.read_csv(trace_path)
            if df.empty:
                continue

            # Get duration
            start_time_us = df['StartTime_us'].iloc[0]
            end_time_us = df['EndTime_us'].iloc[-1]
            duration_secs = (end_time_us - start_time_us) / 1e6
            query_durations.append(duration_secs)

            # Get pipeline pool and tokenize
            final_row = df.iloc[-1]
            pipeline_pool_str = str(final_row['PipelinePool']).strip('()')
            if pipeline_pool_str:
                doc_ids = [d.strip() for d in pipeline_pool_str.split(',')]
            else:
                doc_ids = []

            # Tokenize query
            query_tokens = len(
                tokenizer.encode(query_info['query'],
                                 truncation=False,
                                 add_special_tokens=True))

            # Tokenize documents
            total_doc_tokens = 0
            for doc_id in doc_ids:
                if doc_id not in corpus_content:
                    continue
                doc_text = corpus_content[doc_id]
                doc_tokens = len(
                    tokenizer.encode(doc_text,
                                     truncation=False,
                                     add_special_tokens=True))
                total_doc_tokens += doc_tokens

            total_tokens = query_tokens + total_doc_tokens
            total_query_tokens.append(total_tokens)

        except Exception as e:
            continue

    # Compute statistics and save to file
    os.makedirs(args.output_dir, exist_ok=True)
    output_file = os.path.join(args.output_dir, "workload_stats_anns.txt")

    with open(output_file, 'w') as f:
        f.write("\n" + "=" * 70 + "\n")
        f.write("ANNS WORKLOAD STATISTICS\n")
        f.write("=" * 70 + "\n")

        if total_query_tokens:
            total_query_tokens = np.array(total_query_tokens)
            f.write(f"\nTotal Tokens per Query (n={len(total_query_tokens)})\n")
            f.write(f"  Mean: {total_query_tokens.mean():.0f} tokens\n")
            f.write(f"  P50: {np.percentile(total_query_tokens, 50):.0f} tokens\n")
            f.write(f"  P75: {np.percentile(total_query_tokens, 75):.0f} tokens\n")
            f.write(f"  P95: {np.percentile(total_query_tokens, 95):.0f} tokens\n")

        if query_durations:
            query_durations = np.array(query_durations)
            f.write(f"\nQuery Duration (n={len(query_durations)})\n")
            f.write(f"  Mean: {query_durations.mean():.3f} seconds\n")
            f.write(f"  P50: {np.percentile(query_durations, 50):.3f} seconds\n")
            f.write(f"  P75: {np.percentile(query_durations, 75):.3f} seconds\n")
            f.write(f"  P95: {np.percentile(query_durations, 95):.3f} seconds\n")

        f.write("=" * 70 + "\n")


if __name__ == "__main__":
    main()