source-data / anns /compute_workload_stats.py
ouliten's picture
Duplicate from rbachkaniwala3/stream2llm-data
23a7a20
Raw
History Blame Contribute Delete
5.71 kB
#!/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()