| |
| """Evaluate a SentenceTransformers retriever on Quarry. |
| |
| This reuses the localizer dev-eval representation: child and parent-summary texts are |
| encoded independently, then each corpus vector is |
| ``normalize(alpha * child + (1 - alpha) * parent)``. |
| """ |
| from __future__ import annotations |
|
|
| import argparse |
| from collections import defaultdict |
| from contextlib import nullcontext |
| from dataclasses import dataclass, replace |
| import gc |
| import hashlib |
| import json |
| import multiprocessing as mp |
| import os |
| from pathlib import Path |
| from queue import Empty |
| import shutil |
| import sqlite3 |
| import sys |
| import time |
| from typing import Iterable |
|
|
| import numpy as np |
|
|
| HARNESS_ROOT = Path(__file__).resolve().parent / "harness" |
| if str(HARNESS_ROOT) not in sys.path: |
| sys.path.insert(0, str(HARNESS_ROOT)) |
|
|
| from localize_sft_core import ( |
| swerank_document_text as swerank_document_text, |
| swerank_method_parent as swerank_method_parent, |
| ) |
|
|
| from eval_nano_local import ( |
| bucketed_encode, |
| collect_components, |
| compose_parent_matrix, |
| ) |
|
|
| PATCHPOINT_RETRIEVAL_INSTRUCTION = ( |
| "Given a github issue, identify the code that needs to be changed to fix the issue." |
| ) |
| BGE_CODE_TOKENIZER_CONTRACT = "bge-code-eos-fix-v1" |
|
|
|
|
| @dataclass(frozen=True) |
| class QueryWork: |
| repo: str |
| revision: str |
| task_id: str |
| query_id: str |
| query: str |
| language: str |
| gold_chunks: frozenset[int] |
| gold_files: frozenset[str] |
|
|
|
|
| @dataclass(frozen=True) |
| class DocumentVectors: |
| """One logical document matrix backed by a base cache and optional appended rows.""" |
|
|
| base: np.ndarray |
| overlay: np.ndarray | None = None |
|
|
| @property |
| def shape(self) -> tuple[int, int]: |
| overlay_rows = 0 if self.overlay is None else int(self.overlay.shape[0]) |
| return int(self.base.shape[0]) + overlay_rows, int(self.base.shape[1]) |
|
|
| def take(self, rows: np.ndarray) -> np.ndarray: |
| if self.overlay is None: |
| return self.base[rows] |
| base_rows = int(self.base.shape[0]) |
| output = np.empty((len(rows), self.shape[1]), dtype=np.float32) |
| from_base = rows < base_rows |
| if np.any(from_base): |
| output[from_base] = self.base[rows[from_base]] |
| if np.any(~from_base): |
| output[~from_base] = self.overlay[rows[~from_base] - base_rows] |
| return output |
|
|
|
|
| def read_jsonl(path: Path) -> list[dict]: |
| with path.open(encoding="utf-8") as handle: |
| return [json.loads(line) for line in handle if line.strip()] |
|
|
|
|
| def row_key(row: dict) -> tuple[str, str, str]: |
| return str(row["repo"]), str(row["task_id"]), str(row["query_id"]) |
|
|
|
|
| def validate_cuda_runtime(devices: list[str], expected_gpu_uuid: str | None) -> None: |
| cuda_devices = [device for device in devices if device.startswith("cuda")] |
| if not cuda_devices: |
| return |
| import torch |
|
|
| if not torch.cuda.is_available(): |
| raise RuntimeError("CUDA devices were requested but torch cannot access the NVIDIA driver") |
| expected_uuids = ( |
| [value.strip() for value in expected_gpu_uuid.split(",") if value.strip()] |
| if expected_gpu_uuid |
| else [] |
| ) |
| if expected_uuids and len(expected_uuids) != len(cuda_devices): |
| raise RuntimeError( |
| f"expected {len(cuda_devices)} GPU UUIDs for {cuda_devices}, got {expected_uuids}" |
| ) |
| visible: list[dict[str, object]] = [] |
| for position, device in enumerate(cuda_devices): |
| index = int(device.partition(":")[2] or 0) |
| if index >= torch.cuda.device_count(): |
| raise RuntimeError( |
| f"requested {device}, but only {torch.cuda.device_count()} CUDA devices are visible" |
| ) |
| properties = torch.cuda.get_device_properties(index) |
| actual_uuid = f"GPU-{properties.uuid}" |
| visible.append( |
| { |
| "device": device, |
| "name": properties.name, |
| "uuid": actual_uuid, |
| "memory_bytes": properties.total_memory, |
| } |
| ) |
| expected_uuid = expected_uuids[position] if expected_uuids else None |
| if expected_uuid and actual_uuid.lower() != expected_uuid.lower(): |
| raise RuntimeError( |
| f"{device} maps to {actual_uuid}, expected UUID {expected_uuid}" |
| ) |
| print(json.dumps({"event": "cuda_preflight", "visible": visible}), flush=True) |
|
|
|
|
| def _model_loading_encode_worker( |
| device: str, |
| model_path: str, |
| max_seq_length: int, |
| model_profile: str, |
| hf_instruct_family: str | None, |
| truncate_dim: int | None, |
| input_queue, |
| output_queue, |
| ready_queue, |
| ) -> None: |
| from sentence_transformers import SentenceTransformer |
|
|
| try: |
| model, event, _query_prompt, _document_prompt = _load_pool_worker_model( |
| device, |
| model_path, |
| max_seq_length, |
| model_profile, |
| hf_instruct_family, |
| truncate_dim, |
| ) |
| except BaseException as exc: |
| ready_queue.put( |
| { |
| "event": "pool_worker_error", |
| "device": device, |
| "error_type": exc.__class__.__name__, |
| "error": str(exc), |
| } |
| ) |
| raise |
| ready_queue.put(event) |
| encode_worker = getattr(SentenceTransformer, "_encode_multi_process_worker", None) |
| if encode_worker is None: |
| encode_worker = getattr(SentenceTransformer, "_multi_process_worker") |
| encode_worker(device, model, input_queue, output_queue) |
|
|
|
|
| def start_model_loading_pool( |
| model_path: str, |
| max_seq_length: int, |
| devices: list[str], |
| model_profile: str, |
| hf_instruct_family: str | None, |
| truncate_dim: int | None, |
| expected_query_prompt: str | None, |
| expected_document_prompt: str | None, |
| ) -> dict: |
| context = mp.get_context("spawn") |
| input_queue = context.Queue() |
| output_queue = context.Queue() |
| ready_queue = context.Queue() |
| processes = [] |
| for device in devices: |
| process = context.Process( |
| target=_model_loading_encode_worker, |
| args=( |
| device, |
| model_path, |
| max_seq_length, |
| model_profile, |
| hf_instruct_family, |
| truncate_dim, |
| input_queue, |
| output_queue, |
| ready_queue, |
| ), |
| daemon=True, |
| ) |
| process.start() |
| processes.append(process) |
| try: |
| event = ready_queue.get(timeout=300) |
| except Empty as exc: |
| for running in processes: |
| running.terminate() |
| raise RuntimeError(f"model worker on {device} did not report ready") from exc |
| try: |
| validate_pool_worker_profile_event( |
| event, |
| expected_device=device, |
| expected_query_prompt=expected_query_prompt, |
| expected_document_prompt=expected_document_prompt, |
| ) |
| except Exception: |
| for running in processes: |
| running.terminate() |
| raise |
| print(json.dumps(event), flush=True) |
| print(json.dumps({"event": "model_worker_ready", "device": device}), flush=True) |
| return {"input": input_queue, "output": output_queue, "processes": processes} |
|
|
|
|
| def resolve_gold_chunks( |
| db_dir: Path, query_rows: list[dict], gold_rows: list[dict], tasks: list[dict] |
| ) -> tuple[list[QueryWork], dict]: |
| if [row_key(row) for row in query_rows] != [row_key(row) for row in gold_rows]: |
| raise ValueError("queries and preimage gold rows are not exactly aligned") |
| language_by_task = {str(row["task_id"]): str(row["language"]) for row in tasks} |
| pairs_by_repo: dict[str, list[tuple[str, dict, dict]]] = defaultdict(list) |
| for query, gold in zip(query_rows, gold_rows, strict=True): |
| if str(query["revision"]) != str(gold["revision"]): |
| raise ValueError(f"revision mismatch for {row_key(query)}") |
| pairs_by_repo[str(query["repo"])].append((str(query["revision"]), query, gold)) |
|
|
| resolved: list[QueryWork] = [] |
| canonical_units = 0 |
| for repo, pairs in sorted(pairs_by_repo.items()): |
| db_path = db_dir / repo / "embeddings.db" |
| if not db_path.is_file(): |
| raise FileNotFoundError(f"missing PatchPoint DB: {db_path}") |
| connection = sqlite3.connect(db_path) |
| try: |
| requested_ids = sorted( |
| { |
| int(chunk_id) |
| for _revision, _query, gold in pairs |
| for chunk_id in gold.get("positive_chunk_ids", []) |
| } |
| ) |
| connection.execute("CREATE TEMP TABLE requested_gold (chunk_id INTEGER PRIMARY KEY)") |
| connection.executemany( |
| "INSERT INTO requested_gold (chunk_id) VALUES (?)", |
| ((chunk_id,) for chunk_id in requested_ids), |
| ) |
| rows = connection.execute( |
| """SELECT c.chunk_id, c.revision, c.path, c.codeunit_name |
| FROM chunks c JOIN requested_gold r ON r.chunk_id = c.chunk_id""" |
| ) |
| chunks = { |
| int(chunk_id): (str(chunk_revision), str(path), str(fqmn)) |
| for chunk_id, chunk_revision, path, fqmn in rows |
| } |
| finally: |
| connection.close() |
|
|
| for revision, query, gold in pairs: |
| gold_chunks = {int(chunk_id) for chunk_id in gold.get("positive_chunk_ids", [])} |
| if not gold_chunks: |
| raise ValueError(f"query {query['query_id']} has no canonical corpus-chunk gold") |
| missing = sorted(gold_chunks - chunks.keys()) |
| if missing: |
| raise ValueError(f"query {query['query_id']} references missing chunk IDs {missing[:10]}") |
| wrong_revisions = sorted( |
| chunk_id for chunk_id in gold_chunks if chunks[chunk_id][0] != revision |
| ) |
| if wrong_revisions: |
| raise ValueError( |
| f"query {query['query_id']} has chunk IDs from another revision: " |
| f"{wrong_revisions[:10]}" |
| ) |
| for unit in gold.get("positive_units", []): |
| fqmn = str(unit.get("fqmn") or "") |
| unit_chunks = {int(chunk_id) for chunk_id in unit.get("chunk_ids", [])} |
| if not fqmn or not unit_chunks: |
| raise ValueError( |
| f"query {query['query_id']} has a gold unit without FQMN/chunk IDs" |
| ) |
| if not unit_chunks <= gold_chunks: |
| raise ValueError( |
| f"query {query['query_id']} unit chunk IDs are absent from positive_chunk_ids" |
| ) |
| mismatched = sorted( |
| chunk_id |
| for chunk_id in unit_chunks |
| if chunks[chunk_id][2] != fqmn or chunks[chunk_id][1] != str(unit["path"]) |
| ) |
| if mismatched: |
| raise ValueError( |
| f"query {query['query_id']} has chunk/FQMN/path mismatch: {mismatched[:10]}" |
| ) |
| canonical_units += 1 |
| task_id = str(query["task_id"]) |
| resolved.append( |
| QueryWork( |
| repo=repo, |
| revision=revision, |
| task_id=task_id, |
| query_id=str(query["query_id"]), |
| query=str(query["query"]), |
| language=language_by_task[task_id], |
| gold_chunks=frozenset(gold_chunks), |
| gold_files=frozenset(chunks[chunk_id][1] for chunk_id in gold_chunks), |
| ) |
| ) |
| return resolved, { |
| "queries": len(resolved), |
| "canonical_units": canonical_units, |
| "missing_chunk_ids": 0, |
| "fqmn_mismatches": 0, |
| } |
|
|
|
|
| def retain_function_retrievable_queries( |
| work: list[QueryWork], db_dir: Path |
| ) -> tuple[list[QueryWork], dict]: |
| ids_by_repo: dict[str, set[int]] = defaultdict(set) |
| for item in work: |
| ids_by_repo[item.repo].update(item.gold_chunks) |
| metadata: dict[tuple[str, int], tuple[str, str]] = {} |
| for repo, chunk_ids in sorted(ids_by_repo.items()): |
| connection = sqlite3.connect(db_dir / repo / "embeddings.db") |
| try: |
| ordered = sorted(chunk_ids) |
| for start in range(0, len(ordered), 500): |
| page = ordered[start : start + 500] |
| placeholders = ",".join("?" for _ in page) |
| rows = connection.execute( |
| f"""SELECT chunk_id, path, codeunit_name FROM chunks |
| WHERE chunk_id IN ({placeholders})""", |
| page, |
| ) |
| for chunk_id, path, codeunit_name in rows: |
| metadata[(repo, int(chunk_id))] = (str(path), str(codeunit_name)) |
| finally: |
| connection.close() |
| retained: list[QueryWork] = [] |
| mixed_queries = 0 |
| dropped_queries = 0 |
| removed_gold_ids: set[tuple[str, int]] = set() |
| for item in work: |
| function_chunks = frozenset( |
| chunk_id |
| for chunk_id in item.gold_chunks |
| if metadata[(item.repo, chunk_id)][1] != "__chunkless_file_summary__" |
| ) |
| removed = item.gold_chunks - function_chunks |
| removed_gold_ids.update((item.repo, chunk_id) for chunk_id in removed) |
| if not function_chunks: |
| dropped_queries += 1 |
| continue |
| if removed: |
| mixed_queries += 1 |
| retained.append( |
| replace( |
| item, |
| gold_chunks=function_chunks, |
| gold_files=frozenset( |
| metadata[(item.repo, chunk_id)][0] for chunk_id in function_chunks |
| ), |
| ) |
| ) |
| audit = { |
| "input_queries": len(work), |
| "retained_queries": len(retained), |
| "dropped_chunkless_only_queries": dropped_queries, |
| "mixed_queries_with_chunkless_gold_removed": mixed_queries, |
| "distinct_chunkless_gold_ids_removed": len(removed_gold_ids), |
| } |
| print(json.dumps({"event": "function_retrievable_slice", **audit}), flush=True) |
| return retained, audit |
|
|
|
|
| def cache_digest(args: argparse.Namespace, work: list[QueryWork]) -> str: |
| payload = { |
| "version": 6, |
| "model": str(Path(args.model).resolve()) if Path(args.model).exists() else args.model, |
| "model_profile": args.model_profile, |
| "hf_instruct_family": ( |
| args.hf_instruct_family if args.model_profile == "hf-instruct" else None |
| ), |
| "max_seq_length": args.max_seq_length, |
| "truncate_dim": args.truncate_dim, |
| "document_shape": args.document_shape, |
| "function_retrievable_only": args.function_retrievable_only, |
| "tokenizer_contract": tokenizer_contract_marker(args), |
| "db_dir": str(args.db_dir.resolve()), |
| "final_dir": str(args.final_dir.resolve()), |
| "query_keys": [(item.repo, item.query_id, item.revision) for item in work], |
| } |
| return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()[:24] |
|
|
|
|
| def document_cache_identity(args: argparse.Namespace) -> str: |
| payload = { |
| "model": str(Path(args.model).resolve()) if Path(args.model).exists() else args.model, |
| "model_profile": args.model_profile, |
| "hf_instruct_family": ( |
| args.hf_instruct_family if args.model_profile == "hf-instruct" else None |
| ), |
| "max_seq_length": args.max_seq_length, |
| "truncate_dim": args.truncate_dim, |
| "document_shape": args.document_shape, |
| "tokenizer_contract": tokenizer_contract_marker(args), |
| } |
| return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()[:24] |
|
|
|
|
| def tokenizer_contract_marker(args: argparse.Namespace) -> str | None: |
| if args.model_profile == "hf-instruct" and args.hf_instruct_family == "bge-code": |
| return BGE_CODE_TOKENIZER_CONTRACT |
| return None |
|
|
|
|
| def find_pooling_module(model): |
| for module in model: |
| if module.__class__.__name__ == "Pooling": |
| return module |
| raise ValueError("hf-instruct profile expected a SentenceTransformers Pooling module") |
|
|
|
|
| def pooling_audit(pooling) -> dict[str, object]: |
| pooling_mode = getattr(pooling, "pooling_mode", None) |
| return { |
| "pooling_mode": pooling_mode, |
| "cls": bool(getattr(pooling, "pooling_mode_cls_token", False)) |
| or pooling_mode == "cls", |
| "mean": bool(getattr(pooling, "pooling_mode_mean_tokens", False)) |
| or pooling_mode == "mean", |
| "max": bool(getattr(pooling, "pooling_mode_max_tokens", False)) |
| or pooling_mode == "max", |
| "mean_sqrt_len": bool( |
| getattr(pooling, "pooling_mode_mean_sqrt_len_tokens", False) |
| ) |
| or pooling_mode == "mean_sqrt_len_tokens", |
| "weightedmean": bool( |
| getattr(pooling, "pooling_mode_weightedmean_tokens", False) |
| ) |
| or pooling_mode == "weightedmean", |
| "lasttoken": bool(getattr(pooling, "pooling_mode_lasttoken", False)) |
| or pooling_mode == "lasttoken", |
| "include_prompt": bool(getattr(pooling, "include_prompt", False)), |
| "word_embedding_dimension": ( |
| getattr(pooling, "word_embedding_dimension", None) |
| or getattr(pooling, "pooling_output_dimension", None) |
| ), |
| } |
|
|
|
|
| def require_last_token_pooling(model, family: str) -> dict[str, object]: |
| pooling = find_pooling_module(model) |
| actual = pooling_audit(pooling) |
| expected_enabled = { |
| "cls": False, |
| "mean": False, |
| "max": False, |
| "mean_sqrt_len": False, |
| "weightedmean": False, |
| "lasttoken": True, |
| "include_prompt": True, |
| } |
| mismatches = { |
| key: actual[key] |
| for key, expected in expected_enabled.items() |
| if actual[key] != expected |
| } |
| if mismatches: |
| raise ValueError( |
| f"hf-instruct {family} profile expected last-token-only pooling with " |
| f"include_prompt=true; actual={actual!r}" |
| ) |
| return actual |
|
|
|
|
| def resolve_hf_instruct_profile( |
| model, family: str, attn_implementation: str |
| ) -> tuple[str, None]: |
| bundled_prompts = dict(model.prompts) |
| pooling = require_last_token_pooling(model, family) |
| tokenizer_contract = None |
| if family == "qwen3": |
| expected_bundled_prompts = { |
| "query": ( |
| "Instruct: Given a web search query, retrieve relevant passages that " |
| "answer the query\nQuery:" |
| ), |
| "document": "", |
| } |
| if bundled_prompts != expected_bundled_prompts: |
| raise ValueError( |
| "hf-instruct qwen3 prompt mismatch: " |
| f"expected={expected_bundled_prompts!r}, actual={bundled_prompts!r}" |
| ) |
| query_prompt_text = f"Instruct: {PATCHPOINT_RETRIEVAL_INSTRUCTION}\nQuery:" |
| elif family == "bge-code": |
| tokenizer_contract = apply_bge_code_tokenizer_contract(model.tokenizer) |
| non_empty_prompts = { |
| name: prompt for name, prompt in bundled_prompts.items() if prompt |
| } |
| if non_empty_prompts: |
| raise ValueError( |
| "hf-instruct bge-code expects empty bundled ST prompts; " |
| f"actual={bundled_prompts!r}" |
| ) |
| query_prompt_text = f"<instruct>{PATCHPOINT_RETRIEVAL_INSTRUCTION}\n<query>" |
| else: |
| raise ValueError(f"unknown hf-instruct family {family!r}") |
| model.prompts["query"] = query_prompt_text |
| print( |
| json.dumps( |
| { |
| "event": "hf_instruct_profile_resolved", |
| "family": family, |
| "bundled_prompts": bundled_prompts, |
| "query_prompt": model.prompts["query"], |
| "document_prompt": None, |
| "pooling": pooling, |
| "padding_side": getattr(model.tokenizer, "padding_side", None), |
| "tokenizer_contract": tokenizer_contract, |
| "attn_implementation": attn_implementation, |
| } |
| ), |
| flush=True, |
| ) |
| return "query", None |
|
|
|
|
| def apply_bge_code_tokenizer_contract(tokenizer) -> dict[str, object]: |
| eos_token_id = getattr(tokenizer, "eos_token_id", None) |
| if eos_token_id is None: |
| raise ValueError("hf-instruct bge-code tokenizer must define eos_token_id") |
|
|
| tokenizer.add_eos_token = True |
| update_post_processor = getattr(tokenizer, "update_post_processor", None) |
| if callable(update_post_processor): |
| update_post_processor() |
| tokenizer.padding_side = "left" |
|
|
| examples = [ |
| "hello world", |
| "def f(x): return x + 1", |
| "SELECT * FROM users WHERE id = 1", |
| ] |
| observed_last_ids = [] |
| for example in examples: |
| input_ids = tokenizer(example, add_special_tokens=True)["input_ids"] |
| if not input_ids or input_ids[-1] != eos_token_id: |
| raise ValueError( |
| "hf-instruct bge-code tokenizer failed to append eos: " |
| f"text={example!r}, tail={input_ids[-5:]}" |
| ) |
| observed_last_ids.append(input_ids[-1]) |
|
|
| truncation_length = 5 |
| truncated_ids = tokenizer( |
| " ".join(["token"] * 64), |
| add_special_tokens=True, |
| truncation=True, |
| max_length=truncation_length, |
| )["input_ids"] |
| if len(truncated_ids) != truncation_length or truncated_ids[-1] != eos_token_id: |
| raise ValueError( |
| "hf-instruct bge-code tokenizer truncation must preserve final eos: " |
| f"max_length={truncation_length}, ids={truncated_ids}" |
| ) |
|
|
| return { |
| "marker": BGE_CODE_TOKENIZER_CONTRACT, |
| "class": tokenizer.__class__.__name__, |
| "module": tokenizer.__class__.__module__, |
| "eos_token_id": eos_token_id, |
| "add_eos_token": bool(getattr(tokenizer, "add_eos_token", False)), |
| "padding_side": getattr(tokenizer, "padding_side", None), |
| "observed_last_ids": observed_last_ids, |
| "truncated_length": len(truncated_ids), |
| "truncated_last_id": truncated_ids[-1], |
| } |
|
|
|
|
| def configure_model_profile( |
| model, |
| model_profile: str, |
| hf_instruct_family: str | None, |
| attn_implementation: str | None, |
| ) -> tuple[str, str | None]: |
| if model_profile == "voyage": |
| expected = { |
| "query": "Represent the query for retrieving supporting documents: ", |
| "document": "Represent the document for retrieval: ", |
| } |
| actual = {name: model.prompts.get(name) for name in expected} |
| if actual != expected: |
| raise ValueError(f"Voyage prompt mismatch: expected={expected!r}, actual={actual!r}") |
| return "query", "document" |
| if model_profile == "swerank-small": |
| expected_query = "Represent this query for searching relevant code: " |
| if model.prompts.get("query") != expected_query: |
| raise ValueError( |
| f"SweRank-small query prompt mismatch: expected={expected_query!r}, " |
| f"actual={model.prompts.get('query')!r}" |
| ) |
| return "query", None |
| if model_profile == "granite": |
| expected = { |
| "query": "Given a GitHub issue, retrieve code that must be changed to fix it.\nQuery: ", |
| "document": "Passage: Code chunk from repository.\n", |
| } |
| actual = {name: model.prompts.get(name) for name in expected} |
| if actual != expected: |
| raise ValueError(f"Granite prompt mismatch: expected={expected!r}, actual={actual!r}") |
| return "query", "document" |
| if model_profile == "nemotron-embed": |
| |
| |
| expected = {"query": "query: ", "document": "passage: "} |
| actual = {name: model.prompts.get(name) for name in expected} |
| if actual != expected: |
| raise ValueError( |
| f"Nemotron prompt mismatch: expected={expected!r}, actual={actual!r}" |
| ) |
| return "query", "document" |
| if model_profile == "hf-instruct": |
| if hf_instruct_family is None: |
| raise ValueError("--model-profile hf-instruct requires --hf-instruct-family") |
| if attn_implementation is None: |
| raise ValueError("hf-instruct requires an explicit attention implementation") |
| return resolve_hf_instruct_profile(model, hf_instruct_family, attn_implementation) |
| expected_query = ( |
| "Instruct: Given a github issue, identify the code that needs to be changed " |
| "to fix the issue.\nQuery: " |
| ) |
| if model.prompts.get("query") != expected_query: |
| raise ValueError( |
| f"SweRank-large query prompt mismatch: expected={expected_query!r}, " |
| f"actual={model.prompts.get('query')!r}" |
| ) |
| return "query", None |
|
|
|
|
| def _model_load_kwargs( |
| profile: str, |
| family: str | None, |
| truncate_dim: int | None, |
| device: str | None, |
| torch_module, |
| ) -> tuple[dict[str, object], str | None]: |
| model_kwargs: dict[str, object] = {"torch_dtype": torch_module.bfloat16} |
| attn_implementation = None |
| if profile in {"swerank-large", "hf-instruct"}: |
| attn_implementation = "sdpa" |
| model_kwargs["attn_implementation"] = attn_implementation |
| sentence_transformer_kwargs = { |
| |
| |
| "trust_remote_code": not is_bge_code_hf_instruct_profile(profile, family), |
| "model_kwargs": model_kwargs, |
| "truncate_dim": truncate_dim, |
| } |
| if device is not None: |
| sentence_transformer_kwargs["device"] = device |
| return sentence_transformer_kwargs, attn_implementation |
|
|
|
|
| def _build_profiled_model_with_constructor( |
| sentence_transformer_cls, |
| torch_module, |
| model_path: str, |
| profile: str, |
| family: str | None, |
| max_seq_length: int, |
| device: str | None, |
| truncate_dim: int | None, |
| ): |
| sentence_transformer_kwargs, attn_implementation = _model_load_kwargs( |
| profile, family, truncate_dim, device, torch_module |
| ) |
| model = sentence_transformer_cls(model_path, **sentence_transformer_kwargs) |
| model.max_seq_length = max_seq_length |
| if profile == "swerank-large" and model.tokenizer.padding_side != "left": |
| raise ValueError( |
| "SweRank-large requires the official tokenizer's left-padding contract, " |
| f"got {model.tokenizer.padding_side!r}" |
| ) |
| query_prompt, document_prompt = configure_model_profile( |
| model, profile, family, attn_implementation |
| ) |
| return model, query_prompt, document_prompt |
|
|
|
|
| def build_profiled_model( |
| model_path: str, |
| profile: str, |
| family: str | None, |
| max_seq_length: int, |
| device: str | None, |
| truncate_dim: int | None, |
| ): |
| import torch |
| from sentence_transformers import SentenceTransformer |
|
|
| return _build_profiled_model_with_constructor( |
| SentenceTransformer, |
| torch, |
| model_path, |
| profile, |
| family, |
| max_seq_length, |
| device, |
| truncate_dim, |
| ) |
|
|
|
|
| def load_sentence_transformer(args: argparse.Namespace): |
| device = "cpu" if args.load_per_worker_pool else None |
| return build_profiled_model( |
| args.model, |
| args.model_profile, |
| args.hf_instruct_family, |
| args.max_seq_length, |
| device, |
| args.truncate_dim, |
| ) |
|
|
|
|
| def is_bge_code_hf_instruct_profile(profile: str, family: str | None) -> bool: |
| return profile == "hf-instruct" and family == "bge-code" |
|
|
|
|
| def is_bge_code_hf_instruct(args: argparse.Namespace) -> bool: |
| return is_bge_code_hf_instruct_profile(args.model_profile, args.hf_instruct_family) |
|
|
|
|
| def resolved_prompt_text(model, prompt_name: str | None) -> str | None: |
| if prompt_name is None: |
| return None |
| return model.prompts.get(prompt_name) |
|
|
|
|
| def bge_code_eos_last_token_id_ok(model) -> bool: |
| eos_token_id = getattr(model.tokenizer, "eos_token_id", None) |
| if eos_token_id is None: |
| return False |
| input_ids = model.tokenizer("pool eos probe", add_special_tokens=True)["input_ids"] |
| return bool(input_ids) and input_ids[-1] == eos_token_id |
|
|
|
|
| def pool_worker_profile_event( |
| model, |
| device: str, |
| query_prompt_name: str | None, |
| document_prompt_name: str | None, |
| profile: str, |
| family: str | None, |
| ) -> dict[str, object]: |
| eos_last_token_id_ok = ( |
| bge_code_eos_last_token_id_ok(model) |
| if is_bge_code_hf_instruct_profile(profile, family) |
| else None |
| ) |
| return { |
| "event": "pool_worker_profile", |
| "device": device, |
| "query_prompt": resolved_prompt_text(model, query_prompt_name), |
| "document_prompt": resolved_prompt_text(model, document_prompt_name), |
| "eos_last_token_id_ok": eos_last_token_id_ok, |
| } |
|
|
|
|
| def validate_pool_worker_profile_event( |
| event: dict[str, object], |
| *, |
| expected_device: str, |
| expected_query_prompt: str | None, |
| expected_document_prompt: str | None, |
| ) -> None: |
| if event.get("event") == "pool_worker_error": |
| raise RuntimeError( |
| f"model worker {event.get('device')} failed during load: " |
| f"{event.get('error_type')}: {event.get('error')}" |
| ) |
| if event.get("event") != "pool_worker_profile": |
| raise RuntimeError(f"unexpected model worker readiness event: {event!r}") |
| if event.get("device") != expected_device: |
| raise RuntimeError( |
| f"model worker readiness mismatch: expected {expected_device}, " |
| f"got {event.get('device')}" |
| ) |
| if event.get("query_prompt") != expected_query_prompt: |
| raise RuntimeError( |
| "pool worker query prompt differs from main process: " |
| f"expected={expected_query_prompt!r}, actual={event.get('query_prompt')!r}, " |
| f"device={expected_device}" |
| ) |
| if event.get("document_prompt") != expected_document_prompt: |
| raise RuntimeError( |
| "pool worker document prompt differs from main process: " |
| f"expected={expected_document_prompt!r}, " |
| f"actual={event.get('document_prompt')!r}, device={expected_device}" |
| ) |
| if event.get("eos_last_token_id_ok") is False: |
| raise RuntimeError( |
| f"pool worker bge-code EOS contract failed on {expected_device}: {event!r}" |
| ) |
|
|
|
|
| def _load_pool_worker_model( |
| device: str, |
| model_path: str, |
| max_seq_length: int, |
| model_profile: str, |
| hf_instruct_family: str | None, |
| truncate_dim: int | None, |
| *, |
| sentence_transformer_cls=None, |
| torch_module=None, |
| ): |
| if sentence_transformer_cls is None or torch_module is None: |
| import torch |
| from sentence_transformers import SentenceTransformer |
|
|
| if sentence_transformer_cls is None: |
| sentence_transformer_cls = SentenceTransformer |
| if torch_module is None: |
| torch_module = torch |
| |
| |
| |
| |
| model, query_prompt, document_prompt = _build_profiled_model_with_constructor( |
| sentence_transformer_cls, |
| torch_module, |
| model_path, |
| model_profile, |
| hf_instruct_family, |
| max_seq_length, |
| "cpu", |
| truncate_dim, |
| ) |
| model.to(device) |
| event = pool_worker_profile_event( |
| model, |
| device, |
| query_prompt, |
| document_prompt, |
| model_profile, |
| hf_instruct_family, |
| ) |
| return model, event, query_prompt, document_prompt |
|
|
|
|
| def encode_smoke(args: argparse.Namespace) -> int: |
| model, query_prompt, document_prompt = load_sentence_transformer(args) |
| target_device = args.direct_device or args.devices.split(",")[0] |
| query_texts = ["Issue: the parser ignores quoted values in config files."] |
| document_texts = ["src/config.py\ndef parse_value(raw):\n return raw.strip()"] |
| pool = None |
| if args.load_per_worker_pool: |
| import torch |
|
|
| model.to("cpu") |
| torch.cuda.empty_cache() |
| pool = start_model_loading_pool( |
| args.model, |
| args.max_seq_length, |
| args.devices.split(","), |
| args.model_profile, |
| args.hf_instruct_family, |
| args.truncate_dim, |
| resolved_prompt_text(model, query_prompt), |
| resolved_prompt_text(model, document_prompt), |
| ) |
| try: |
| query_vector = bucketed_encode(model, pool, query_texts, query_prompt) |
| document_vector = bucketed_encode(model, pool, document_texts, document_prompt) |
| finally: |
| model.stop_multi_process_pool(pool) |
| else: |
| model.to(target_device) |
| query_vector = model.encode( |
| query_texts, |
| prompt_name=query_prompt, |
| batch_size=1, |
| normalize_embeddings=True, |
| show_progress_bar=False, |
| ) |
| document_vector = model.encode( |
| document_texts, |
| prompt_name=document_prompt, |
| batch_size=1, |
| normalize_embeddings=True, |
| show_progress_bar=False, |
| ) |
| print( |
| json.dumps( |
| { |
| "event": "encode_smoke_complete", |
| "device": target_device, |
| "query_prompt_name": query_prompt, |
| "document_prompt_name": document_prompt, |
| "query_shape": list(query_vector.shape), |
| "document_shape": list(document_vector.shape), |
| "query_norm": float(np.linalg.norm(query_vector[0])), |
| "document_norm": float(np.linalg.norm(document_vector[0])), |
| } |
| ), |
| flush=True, |
| ) |
| return 0 |
|
|
|
|
| def collect_swerank_components( |
| work: list[QueryWork], db_dir: Path |
| ) -> tuple[list[str], dict[tuple[str, str], int], list, dict]: |
| revisions_by_repo: dict[str, set[str]] = defaultdict(set) |
| for item in work: |
| revisions_by_repo[item.repo].add(item.revision) |
| texts: dict[str, int] = {} |
| unique_texts: list[str] = [] |
| text_index: dict[tuple[str, str], int] = {} |
| composes: list[tuple[str, str, str, str]] = [] |
| methods = 0 |
| top_level = 0 |
| for repo, revisions in sorted(revisions_by_repo.items()): |
| connection = sqlite3.connect(db_dir / repo / "embeddings.db") |
| try: |
| placeholders = ",".join("?" for _ in revisions) |
| rows = connection.execute( |
| f"""SELECT vector_key, path, codeunit_name, text, parent_text |
| FROM chunks WHERE revision IN ({placeholders})""", |
| sorted(revisions), |
| ) |
| seen: set[str] = set() |
| for vector_key, path, codeunit_name, source_text, parent_text in rows: |
| vector_key = str(vector_key) |
| if vector_key in seen: |
| continue |
| seen.add(vector_key) |
| if str(codeunit_name) == "__chunkless_file_summary__": |
| continue |
| document, is_method = swerank_document_text( |
| str(path), str(codeunit_name), str(source_text), str(parent_text) |
| ) |
| if is_method: |
| methods += 1 |
| else: |
| top_level += 1 |
| document_key = "swerank-v1:" + hashlib.sha256( |
| document.encode("utf-8") |
| ).hexdigest() |
| row = texts.get(document) |
| if row is None: |
| row = len(unique_texts) |
| texts[document] = row |
| unique_texts.append(document) |
| text_index[(repo, document_key)] = row |
| composes.append((repo, vector_key, document_key, document_key)) |
| finally: |
| connection.close() |
| audit = { |
| "format": "swerank-find_py_or_non_dict_with_path", |
| "unique_texts": len(unique_texts), |
| "vectors": len(composes), |
| "class_methods": methods, |
| "top_level_functions": top_level, |
| } |
| print(json.dumps({"event": "swerank_documents_collected", **audit}), flush=True) |
| return unique_texts, text_index, composes, audit |
|
|
|
|
| def save_cache(path: Path, doc_vectors: np.ndarray, text_index: dict, query_vectors: np.ndarray, work: list[QueryWork]) -> None: |
| temporary = path.with_name(path.name + ".tmp") |
| if temporary.exists(): |
| shutil.rmtree(temporary) |
| temporary.mkdir(parents=True) |
| np.save(temporary / "documents.npy", doc_vectors) |
| np.save(temporary / "queries.npy", query_vectors) |
| (temporary / "document-keys.json").write_text( |
| json.dumps([[repo, key, row] for (repo, key), row in text_index.items()]), encoding="utf-8" |
| ) |
| (temporary / "query-keys.json").write_text( |
| json.dumps([[item.repo, item.query_id] for item in work]), encoding="utf-8" |
| ) |
| if path.exists(): |
| shutil.rmtree(path) |
| temporary.rename(path) |
|
|
|
|
| def load_cache( |
| path: Path, composes: list, work: list[QueryWork] |
| ) -> tuple[DocumentVectors, dict, np.ndarray] | None: |
| files = [path / "documents.npy", path / "queries.npy", path / "document-keys.json", path / "query-keys.json"] |
| if not all(file.is_file() for file in files): |
| overlay_files = [ |
| path / "overlay-documents.npy", |
| path / "base-cache.json", |
| path / "queries.npy", |
| path / "document-keys.json", |
| path / "query-keys.json", |
| ] |
| if not all(file.is_file() for file in overlay_files): |
| return None |
| base_manifest = json.loads((path / "base-cache.json").read_text(encoding="utf-8")) |
| base_path = Path(str(base_manifest["path"])) |
| base_documents_path = base_path / "documents.npy" |
| if not base_documents_path.is_file(): |
| return None |
| base_documents = np.load(base_documents_path, mmap_mode="r") |
| overlay_documents = np.load(path / "overlay-documents.npy", mmap_mode="r") |
| if ( |
| list(base_documents.shape) != base_manifest["shape"] |
| or int(base_documents.shape[1]) != int(overlay_documents.shape[1]) |
| ): |
| return None |
| documents = DocumentVectors(base_documents, overlay_documents) |
| else: |
| documents = DocumentVectors(np.load(path / "documents.npy", mmap_mode="r")) |
| query_keys = json.loads((path / "query-keys.json").read_text(encoding="utf-8")) |
| if query_keys != [[item.repo, item.query_id] for item in work]: |
| return None |
| text_index = { |
| (str(repo), str(key)): int(row) |
| for repo, key, row in json.loads((path / "document-keys.json").read_text(encoding="utf-8")) |
| } |
| if any((repo, child) not in text_index or (repo, parent) not in text_index for repo, _vector, child, parent in composes): |
| return None |
| return ( |
| documents, |
| text_index, |
| np.load(path / "queries.npy", mmap_mode="r"), |
| ) |
|
|
|
|
| def reused_document_layout( |
| reuse_path: Path, |
| component_texts: list[str], |
| text_index: dict[tuple[str, str], int], |
| *, |
| reuse_below_tokens: int | None = None, |
| tokenizer=None, |
| tokenization_batch_size: int = 1024, |
| ) -> tuple[DocumentVectors, dict[tuple[str, str], int], list[str], dict]: |
| base_documents_path = reuse_path / "documents.npy" |
| base_keys_path = reuse_path / "document-keys.json" |
| if not base_documents_path.is_file() or not base_keys_path.is_file(): |
| raise ValueError(f"reuse cache is incomplete: {reuse_path}") |
| base_documents = np.load(base_documents_path, mmap_mode="r") |
| base_index = { |
| (str(repo), str(key)): int(row) |
| for repo, key, row in json.loads(base_keys_path.read_text(encoding="utf-8")) |
| } |
| excluded_rows: set[int] = set() |
| length_audit: dict[str, object] = {} |
| if reuse_below_tokens is not None: |
| if tokenizer is None: |
| raise ValueError("reuse_below_tokens requires a tokenizer") |
| if reuse_below_tokens < 0: |
| raise ValueError("reuse_below_tokens must be non-negative") |
| length_start = time.monotonic() |
| tokenization_candidates = [ |
| (row, text) |
| for row, text in enumerate(component_texts) |
| if len(text) > reuse_below_tokens |
| ] |
| for start in range(0, len(tokenization_candidates), tokenization_batch_size): |
| batch = tokenization_candidates[start : start + tokenization_batch_size] |
| encoded = tokenizer( |
| [text for _row, text in batch], |
| add_special_tokens=True, |
| padding=False, |
| truncation=False, |
| return_length=True, |
| ) |
| lengths = encoded.get("length") |
| if lengths is None: |
| lengths = [len(ids) for ids in encoded["input_ids"]] |
| for (row, _text), length in zip(batch, lengths, strict=True): |
| if int(length) > reuse_below_tokens: |
| excluded_rows.add(row) |
| length_audit = { |
| "reuse_below_tokens": reuse_below_tokens, |
| "char_safe_current_rows": len(component_texts) |
| - len(tokenization_candidates), |
| "char_prefilter_candidate_rows": len(tokenization_candidates), |
| "token_excluded_current_rows": len(excluded_rows), |
| "length_classification_seconds": time.monotonic() - length_start, |
| "tokenization_batch_size": tokenization_batch_size, |
| } |
| current_to_base: dict[int, int] = {} |
| for key, current_row in text_index.items(): |
| if current_row in excluded_rows: |
| continue |
| base_row = base_index.get(key) |
| if base_row is not None: |
| current_to_base.setdefault(current_row, base_row) |
| missing_rows = [ |
| row for row in range(len(component_texts)) if row not in current_to_base |
| ] |
| missing_position = {row: position for position, row in enumerate(missing_rows)} |
| base_rows = int(base_documents.shape[0]) |
| remapped = { |
| key: ( |
| current_to_base[current_row] |
| if current_row in current_to_base |
| else base_rows + missing_position[current_row] |
| ) |
| for key, current_row in text_index.items() |
| } |
| audit = { |
| "base_cache": str(reuse_path.resolve()), |
| "base_rows": base_rows, |
| "reused_current_rows": len(component_texts) - len(missing_rows), |
| "missing_current_rows": len(missing_rows), |
| } |
| audit.update(length_audit) |
| return ( |
| DocumentVectors(base_documents), |
| remapped, |
| [component_texts[row] for row in missing_rows], |
| audit, |
| ) |
|
|
|
|
| def save_overlay_cache( |
| path: Path, |
| base_path: Path, |
| base_documents: np.ndarray, |
| overlay_documents: np.ndarray, |
| text_index: dict, |
| query_vectors: np.ndarray, |
| work: list[QueryWork], |
| ) -> None: |
| temporary = path.with_name(path.name + ".tmp") |
| if temporary.exists(): |
| shutil.rmtree(temporary) |
| temporary.mkdir(parents=True) |
| np.save(temporary / "overlay-documents.npy", overlay_documents) |
| np.save(temporary / "queries.npy", query_vectors) |
| (temporary / "base-cache.json").write_text( |
| json.dumps( |
| {"path": str(base_path.resolve()), "shape": list(base_documents.shape)}, |
| sort_keys=True, |
| ), |
| encoding="utf-8", |
| ) |
| (temporary / "document-keys.json").write_text( |
| json.dumps([[repo, key, row] for (repo, key), row in text_index.items()]), |
| encoding="utf-8", |
| ) |
| (temporary / "query-keys.json").write_text( |
| json.dumps([[item.repo, item.query_id] for item in work]), encoding="utf-8" |
| ) |
| if path.exists(): |
| shutil.rmtree(path) |
| temporary.rename(path) |
|
|
|
|
| def update_document_store( |
| path: Path, |
| documents: DocumentVectors, |
| text_index: dict[tuple[str, str], int], |
| ) -> None: |
| current_items = list(text_index.items()) |
| if not current_items: |
| return |
| existing_documents_path = path / "documents.npy" |
| existing_keys_path = path / "document-keys.json" |
| existing_documents = None |
| existing_entries: list[tuple[str, str, int]] = [] |
| if existing_documents_path.is_file() and existing_keys_path.is_file(): |
| existing_documents = np.load(existing_documents_path, mmap_mode="r") |
| existing_entries = [ |
| (str(repo), str(key), int(row)) |
| for repo, key, row in json.loads( |
| existing_keys_path.read_text(encoding="utf-8") |
| ) |
| ] |
| if int(existing_documents.shape[1]) != documents.shape[1]: |
| raise ValueError( |
| f"docstore dimension mismatch: existing={existing_documents.shape[1]}, " |
| f"current={documents.shape[1]}" |
| ) |
|
|
| rows: list[tuple[str, str, int]] = [] |
| seen: set[tuple[str, str]] = set() |
| existing_sources: list[int] = [] |
| for repo, key, source_row in sorted(existing_entries, key=lambda item: item[2]): |
| cache_key = (repo, key) |
| if cache_key in seen: |
| continue |
| if existing_documents is None or not 0 <= source_row < int( |
| existing_documents.shape[0] |
| ): |
| raise ValueError( |
| f"docstore key row out of bounds: {(repo, key, source_row)!r}" |
| ) |
| seen.add(cache_key) |
| existing_sources.append(source_row) |
| rows.append((repo, key, len(rows))) |
|
|
| current_sources: list[int] = [] |
| for (repo, key), source_row in current_items: |
| cache_key = (str(repo), str(key)) |
| if cache_key in seen: |
| continue |
| seen.add(cache_key) |
| current_sources.append(int(source_row)) |
| rows.append((cache_key[0], cache_key[1], len(rows))) |
|
|
| temporary = path.with_name(f"{path.name}.tmp-{os.getpid()}-{time.time_ns()}") |
| if temporary.exists(): |
| shutil.rmtree(temporary) |
| temporary.parent.mkdir(parents=True, exist_ok=True) |
| temporary.mkdir() |
| try: |
| dtype = ( |
| existing_documents.dtype |
| if existing_documents is not None |
| else documents.base.dtype |
| ) |
| output = np.lib.format.open_memmap( |
| temporary / "documents.npy", |
| mode="w+", |
| dtype=dtype, |
| shape=(len(rows), documents.shape[1]), |
| ) |
| cursor = 0 |
| if existing_documents is not None and existing_sources: |
| existing_rows = np.asarray(existing_sources, dtype=np.int64) |
| output[cursor : cursor + len(existing_sources)] = existing_documents[ |
| existing_rows |
| ] |
| cursor += len(existing_sources) |
| if current_sources: |
| current_rows = np.asarray(current_sources, dtype=np.int64) |
| output[cursor : cursor + len(current_sources)] = documents.take( |
| current_rows |
| ) |
| output.flush() |
| (temporary / "document-keys.json").write_text( |
| json.dumps([[repo, key, row] for repo, key, row in rows]), |
| encoding="utf-8", |
| ) |
| old_path: Path | None = None |
| if path.exists(): |
| old_path = path.with_name( |
| f"{path.name}.old-{os.getpid()}-{time.time_ns()}" |
| ) |
| if old_path.exists(): |
| shutil.rmtree(old_path) |
| path.rename(old_path) |
| try: |
| temporary.rename(path) |
| except Exception: |
| if old_path is not None and old_path.exists() and not path.exists(): |
| old_path.rename(path) |
| raise |
| else: |
| if old_path is not None: |
| shutil.rmtree(old_path) |
| except Exception: |
| if temporary.exists(): |
| shutil.rmtree(temporary) |
| raise |
|
|
|
|
| def materialize_current_document_layout( |
| documents: DocumentVectors, |
| text_index: dict[tuple[str, str], int], |
| ) -> tuple[np.ndarray, dict[tuple[str, str], int]]: |
| source_rows = sorted(set(text_index.values())) |
| row_remap = {source_row: row for row, source_row in enumerate(source_rows)} |
| materialized = documents.take(np.asarray(source_rows, dtype=np.int64)) |
| remapped = {key: row_remap[source_row] for key, source_row in text_index.items()} |
| return materialized, remapped |
|
|
|
|
| def derive_truncated_cache( |
| source_path: Path, |
| target_path: Path, |
| composes: list, |
| work: list[QueryWork], |
| truncate_dim: int, |
| *, |
| block_size: int = 8192, |
| ) -> None: |
| source = load_cache(source_path, composes, work) |
| if source is None: |
| raise ValueError( |
| "truncation source must be a complete cache with identical document/query keys" |
| ) |
| documents, text_index, queries = source |
| if documents.overlay is not None: |
| raise ValueError("truncation source cannot be an overlay cache") |
| if not 0 < truncate_dim < documents.shape[1]: |
| raise ValueError( |
| f"truncate_dim must be below source dimension {documents.shape[1]}" |
| ) |
| temporary = target_path.with_name(target_path.name + ".tmp") |
| if temporary.exists(): |
| shutil.rmtree(temporary) |
| temporary.mkdir(parents=True) |
|
|
| def truncate(source_vectors: np.ndarray, output_path: Path) -> None: |
| output = np.lib.format.open_memmap( |
| output_path, |
| mode="w+", |
| dtype=np.float32, |
| shape=(int(source_vectors.shape[0]), truncate_dim), |
| ) |
| for start in range(0, len(source_vectors), block_size): |
| stop = min(start + block_size, len(source_vectors)) |
| block = np.array( |
| source_vectors[start:stop, :truncate_dim], |
| dtype=np.float32, |
| copy=True, |
| ) |
| norms = np.linalg.norm(block, axis=1) |
| nonzero = norms > 0 |
| block[nonzero] /= norms[nonzero, None] |
| output[start:stop] = block |
| output.flush() |
|
|
| truncate(documents.base, temporary / "documents.npy") |
| truncate(queries, temporary / "queries.npy") |
| (temporary / "document-keys.json").write_text( |
| json.dumps([[repo, key, row] for (repo, key), row in text_index.items()]), |
| encoding="utf-8", |
| ) |
| (temporary / "query-keys.json").write_text( |
| json.dumps([[item.repo, item.query_id] for item in work]), encoding="utf-8" |
| ) |
| if target_path.exists(): |
| shutil.rmtree(target_path) |
| temporary.rename(target_path) |
|
|
|
|
| def compose_document_matrix( |
| documents: DocumentVectors, |
| text_index: dict[tuple[str, str], int], |
| composes: list[tuple[str, str, str, str]], |
| alpha: float, |
| *, |
| workers: int, |
| block_size: int = 1024, |
| ) -> tuple[np.ndarray, dict[tuple[str, str], int]]: |
| if documents.overlay is None: |
| return compose_parent_matrix( |
| documents.base, text_index, composes, alpha, workers=workers |
| ) |
| child_rows = np.fromiter( |
| ( |
| text_index[(repo, child_key)] |
| for repo, _vector_key, child_key, _parent_key in composes |
| ), |
| dtype=np.int64, |
| count=len(composes), |
| ) |
| parent_rows = np.fromiter( |
| ( |
| text_index[(repo, parent_key)] |
| for repo, _vector_key, _child_key, parent_key in composes |
| ), |
| dtype=np.int64, |
| count=len(composes), |
| ) |
| output = np.empty((len(composes), documents.shape[1]), dtype=np.float32) |
| row_by_key = { |
| (repo, vector_key): row |
| for row, (repo, vector_key, _child, _parent) in enumerate(composes) |
| } |
| ranges = [ |
| (start, min(start + block_size, len(composes))) |
| for start in range(0, len(composes), block_size) |
| ] |
|
|
| def compose_block(bounds: tuple[int, int]) -> None: |
| start, stop = bounds |
| target = output[start:stop] |
| np.multiply(documents.take(child_rows[start:stop]), alpha, out=target) |
| target += documents.take(parent_rows[start:stop]) * (1.0 - alpha) |
| norms = np.linalg.norm(target, axis=1) |
| nonzero = norms > 0 |
| target[nonzero] /= norms[nonzero, None] |
|
|
| from concurrent.futures import ThreadPoolExecutor |
|
|
| with ThreadPoolExecutor(max_workers=max(1, workers)) as pool: |
| list(pool.map(compose_block, ranges)) |
| return output, row_by_key |
|
|
|
|
| def reciprocal_rank(ranked: list[int], gold: frozenset[int]) -> float: |
| return next((1.0 / rank for rank, chunk_id in enumerate(ranked, 1) if chunk_id in gold), 0.0) |
|
|
|
|
| def mean_dict(rows: Iterable[dict[str, float]], keys: list[str]) -> dict[str, float]: |
| materialized = list(rows) |
| return {key: sum(row[key] for row in materialized) / len(materialized) for key in keys} |
|
|
|
|
| def nested_macro(query_rows: list[dict], keys: list[str]) -> tuple[dict, dict]: |
| by_task: dict[tuple[str, str], list[dict]] = defaultdict(list) |
| for row in query_rows: |
| by_task[(row["repo"], row["task_id"])].append(row) |
| task_rows = [ |
| {"repo": rows[0]["repo"], "language": rows[0]["language"], **mean_dict(rows, keys)} |
| for rows in by_task.values() |
| ] |
| by_repo: dict[str, list[dict]] = defaultdict(list) |
| for row in task_rows: |
| by_repo[row["repo"]].append(row) |
| repo_rows = [ |
| {"repo": repo, "language": rows[0]["language"], **mean_dict(rows, keys)} |
| for repo, rows in sorted(by_repo.items()) |
| ] |
| by_language: dict[str, list[dict]] = defaultdict(list) |
| for row in repo_rows: |
| by_language[row["language"]].append(row) |
| language_rows = { |
| language: mean_dict(rows, keys) for language, rows in sorted(by_language.items()) |
| } |
| return mean_dict(language_rows.values(), keys), {"languages": language_rows, "repositories": repo_rows} |
|
|
|
|
| def build_evaluation_row( |
| item: QueryWork, |
| ranked_chunks: list[int], |
| ranked_files: list[str], |
| ks: tuple[int, ...], |
| ) -> dict: |
| row: dict[str, object] = { |
| "repo": item.repo, |
| "revision": item.revision, |
| "language": item.language, |
| "task_id": item.task_id, |
| "query_id": item.query_id, |
| "gold_chunks": sorted(item.gold_chunks), |
| "gold_files": sorted(item.gold_files), |
| "mrr": reciprocal_rank(ranked_chunks, item.gold_chunks), |
| "file_mrr": next( |
| ( |
| 1.0 / rank |
| for rank, path in enumerate(ranked_files, 1) |
| if path in item.gold_files |
| ), |
| 0.0, |
| ), |
| "ranked_chunks_top50": ranked_chunks[:50], |
| "ranked_files_top50": ranked_files[:50], |
| } |
| for k in ks: |
| top_chunks = set(ranked_chunks[:k]) |
| top_files = set(ranked_files[:k]) |
| row[f"acc@{k}"] = float(bool(top_chunks & item.gold_chunks)) |
| row[f"recall@{k}"] = len(top_chunks & item.gold_chunks) / len(item.gold_chunks) |
| row[f"file_acc@{k}"] = float(bool(top_files & item.gold_files)) |
| row[f"file_recall@{k}"] = len(top_files & item.gold_files) / len(item.gold_files) |
| return row |
|
|
|
|
| def score( |
| work: list[QueryWork], |
| db_dir: Path, |
| composed: np.ndarray, |
| composed_rows: dict[tuple[str, str], int], |
| query_vectors: np.ndarray, |
| ks: tuple[int, ...], |
| workers: int, |
| *, |
| include_chunkless: bool, |
| ) -> list[dict]: |
| from concurrent.futures import ThreadPoolExecutor |
|
|
| work_by_revision: dict[tuple[str, str], list[tuple[int, QueryWork]]] = defaultdict(list) |
| for index, item in enumerate(work): |
| work_by_revision[(item.repo, item.revision)].append((index, item)) |
|
|
| |
| |
| revisions_by_repo: dict[str, set[str]] = defaultdict(set) |
| for repo, revision in work_by_revision: |
| revisions_by_repo[repo].add(revision) |
| layouts: dict[tuple[str, str], tuple[np.ndarray, list[str], list[str]]] = {} |
| layout_start = time.monotonic() |
| for repo, revisions in sorted(revisions_by_repo.items()): |
| ordered_revisions = sorted(revisions) |
| placeholders = ",".join("?" for _ in ordered_revisions) |
| connection = sqlite3.connect(db_dir / repo / "embeddings.db") |
| try: |
| chunkless_clause = ( |
| "" if include_chunkless else "AND codeunit_name != '__chunkless_file_summary__'" |
| ) |
| rows = connection.execute( |
| f"""SELECT revision, chunk_id, vector_key, path FROM chunks |
| WHERE revision IN ({placeholders}) |
| {chunkless_clause} |
| ORDER BY revision, path, codeunit_name, chunk_id""", |
| ordered_revisions, |
| ) |
| grouped: dict[str, list[tuple[int, str, str]]] = defaultdict(list) |
| for revision, chunk_id, vector_key, path in rows: |
| grouped[str(revision)].append((int(chunk_id), str(vector_key), str(path))) |
| finally: |
| connection.close() |
| for revision in ordered_revisions: |
| entries = grouped.get(revision) |
| if not entries: |
| raise ValueError(f"no corpus chunks for {repo}@{revision}") |
| layouts[(repo, revision)] = ( |
| np.asarray([row[0] for row in entries], dtype=np.int64), |
| [row[1] for row in entries], |
| [row[2] for row in entries], |
| ) |
| print( |
| json.dumps( |
| { |
| "event": "scoring_layouts_loaded", |
| "repositories": len(revisions_by_repo), |
| "revisions": len(layouts), |
| "seconds": time.monotonic() - layout_start, |
| } |
| ), |
| flush=True, |
| ) |
|
|
| def score_revision(group: tuple[tuple[str, str], list[tuple[int, QueryWork]]]) -> list[dict]: |
| (repo, revision), items = group |
| chunk_ids, vector_keys, paths = layouts[(repo, revision)] |
| matrix = composed[[composed_rows[(repo, vector_key)] for vector_key in vector_keys]] |
| results: list[dict] = [] |
| for query_index, item in items: |
| order = np.argsort(matrix @ query_vectors[query_index])[::-1] |
| ranked_chunks = [int(chunk_ids[index]) for index in order] |
| ranked_files: list[str] = [] |
| seen_files: set[str] = set() |
| for index in order: |
| path = paths[int(index)] |
| if path not in seen_files: |
| seen_files.add(path) |
| ranked_files.append(path) |
| results.append(build_evaluation_row(item, ranked_chunks, ranked_files, ks)) |
| return results |
|
|
| try: |
| from threadpoolctl import threadpool_limits |
|
|
| blas_context = threadpool_limits(limits=1, user_api="blas") |
| except ImportError: |
| blas_context = nullcontext() |
| with blas_context: |
| with ThreadPoolExecutor(max_workers=max(1, workers)) as pool: |
| groups = pool.map(score_revision, sorted(work_by_revision.items())) |
| return [row for group in groups for row in group] |
|
|
|
|
| def main() -> int: |
| parser = argparse.ArgumentParser(description=__doc__) |
| here = Path(__file__).resolve().parent |
| parser.add_argument("--model", required=True) |
| parser.add_argument( |
| "--model-profile", |
| choices=( |
| "voyage", |
| "swerank-small", |
| "swerank-large", |
| "granite", |
| "hf-instruct", |
| "nemotron-embed", |
| ), |
| required=True, |
| ) |
| parser.add_argument("--hf-instruct-family", choices=("qwen3", "bge-code")) |
| parser.add_argument("--model-tag", required=True) |
| parser.add_argument("--final-dir", type=Path, default=here / "final") |
| parser.add_argument("--db-dir", type=Path, default=here / "production-db") |
| parser.add_argument("--output-dir", type=Path, default=here / "eval") |
| parser.add_argument("--vector-cache", type=Path, default=here / "eval-vector-cache") |
| parser.add_argument( |
| "--derive-truncated-cache", |
| type=Path, |
| help="Derive this run's vectors by truncating and renormalizing an identical wider cache", |
| ) |
| parser.add_argument( |
| "--document-shape", |
| choices=("parent-composed", "swerank"), |
| default="swerank", |
| ) |
| parser.add_argument("--devices", default="cuda:0") |
| parser.add_argument("--expected-gpu-uuid") |
| parser.add_argument( |
| "--direct-device", |
| help="Encode in the main process on this device instead of using a multiprocessing pool", |
| ) |
| parser.add_argument( |
| "--load-per-worker-pool", |
| action="store_true", |
| help="Have each legacy SentenceTransformers worker load the model instead of sharing it", |
| ) |
| parser.add_argument("--max-seq-length", type=int, default=8192) |
| parser.add_argument("--truncate-dim", type=int) |
| parser.add_argument( |
| "--checkpoint-dispatch-texts", |
| type=int, |
| default=20_000, |
| help="Texts per atomic embedding checkpoint inside each length bucket", |
| ) |
| parser.add_argument("--checkpoint-shard-index", type=int, default=0) |
| parser.add_argument("--checkpoint-shard-count", type=int, default=1) |
| parser.add_argument( |
| "--documents-shard-only", |
| action="store_true", |
| help="Encode this document checkpoint shard and exit before queries/finalization", |
| ) |
| parser.add_argument( |
| "--documents-shard-stop-after-batch-size", |
| type=int, |
| help="Stop a documents-only shard after processing this logical length bucket", |
| ) |
| parser.add_argument("--alpha", type=float, default=1.0) |
| parser.add_argument("--workers", type=int, default=max(1, (os.cpu_count() or 1) // 2)) |
| parser.add_argument("--preflight-only", action="store_true") |
| parser.add_argument( |
| "--encode-smoke-only", |
| action="store_true", |
| help="Load the selected embedding model, resolve prompts, encode one query/document, and exit", |
| ) |
| parser.add_argument( |
| "--documents-preflight-only", |
| action="store_true", |
| help="Resolve gold and collect document texts without loading an embedding model", |
| ) |
| parser.add_argument( |
| "--function-retrievable-only", |
| action="store_true", |
| help="Drop chunkless-only queries and remove chunkless gold from mixed queries", |
| ) |
| args = parser.parse_args() |
| if not 0.0 <= args.alpha <= 1.0: |
| parser.error("--alpha must be between zero and one") |
| if args.document_shape == "swerank" and args.alpha != 1.0: |
| parser.error("--document-shape swerank requires --alpha 1.0") |
| if args.model_profile == "hf-instruct": |
| if args.hf_instruct_family is None: |
| parser.error("--model-profile hf-instruct requires --hf-instruct-family") |
| if args.truncate_dim is not None: |
| parser.error("--model-profile hf-instruct leaves truncate_dim native; omit --truncate-dim") |
| elif args.hf_instruct_family is not None: |
| parser.error("--hf-instruct-family is only valid with --model-profile hf-instruct") |
| if args.derive_truncated_cache is not None and args.truncate_dim is None: |
| parser.error("--derive-truncated-cache requires --truncate-dim") |
| if args.checkpoint_shard_count < 1: |
| parser.error("--checkpoint-shard-count must be positive") |
| if not 0 <= args.checkpoint_shard_index < args.checkpoint_shard_count: |
| parser.error( |
| "--checkpoint-shard-index must be between zero and --checkpoint-shard-count" |
| ) |
| if args.checkpoint_shard_count > 1 and not args.documents_shard_only: |
| parser.error("--checkpoint sharding requires --documents-shard-only") |
| if ( |
| args.documents_shard_stop_after_batch_size is not None |
| and not args.documents_shard_only |
| ): |
| parser.error( |
| "--documents-shard-stop-after-batch-size requires --documents-shard-only" |
| ) |
| validate_cuda_runtime(args.devices.split(","), args.expected_gpu_uuid) |
| if args.encode_smoke_only: |
| if args.direct_device and args.load_per_worker_pool: |
| parser.error("--direct-device and --load-per-worker-pool are mutually exclusive") |
| return encode_smoke(args) |
|
|
| task_rows = read_jsonl(args.final_dir / "tasks.jsonl") |
| query_rows = read_jsonl(args.final_dir / "queries.jsonl") |
| gold_rows = read_jsonl(args.final_dir / "gold-preimage.jsonl") |
| work, gold_audit = resolve_gold_chunks(args.db_dir, query_rows, gold_rows, task_rows) |
| print(json.dumps({"event": "gold_resolved", **gold_audit}), flush=True) |
| slice_audit = None |
| if args.function_retrievable_only: |
| work, slice_audit = retain_function_retrievable_queries(work, args.db_dir) |
| if args.preflight_only: |
| return 0 |
|
|
| document_shape_audit = None |
| if args.document_shape == "swerank": |
| component_texts, text_index, composes, document_shape_audit = ( |
| collect_swerank_components(work, args.db_dir) |
| ) |
| else: |
| component_texts, text_index, composes = collect_components(work, args.db_dir) |
| if args.documents_preflight_only: |
| print( |
| json.dumps( |
| { |
| "event": "documents_preflight_complete", |
| "document_shape": args.document_shape, |
| "unique_texts": len(component_texts), |
| "document_keys": len(text_index), |
| "vectors": len(composes), |
| "document_shape_audit": document_shape_audit, |
| } |
| ), |
| flush=True, |
| ) |
| return 0 |
| digest = cache_digest(args, work) |
| cache_path = args.vector_cache / digest |
| docstore_identity = document_cache_identity(args) |
| docstore_path = args.vector_cache / "docstore" / docstore_identity |
| cached = load_cache(cache_path, composes, work) |
| if cached is None and args.derive_truncated_cache is not None: |
| derive_truncated_cache( |
| args.derive_truncated_cache, |
| cache_path, |
| composes, |
| work, |
| args.truncate_dim, |
| ) |
| print( |
| json.dumps( |
| { |
| "event": "vector_cache_derived", |
| "source": str(args.derive_truncated_cache), |
| "path": str(cache_path), |
| "truncate_dim": args.truncate_dim, |
| } |
| ), |
| flush=True, |
| ) |
| cached = load_cache(cache_path, composes, work) |
| if cached is None: |
| raise RuntimeError("derived vector cache failed its completeness check") |
| if cached is None: |
| import torch |
|
|
| reused_documents = None |
| reused_text_index = None |
| missing_component_texts = component_texts |
| if ( |
| (docstore_path / "documents.npy").is_file() |
| and (docstore_path / "document-keys.json").is_file() |
| ): |
| ( |
| reused_documents, |
| reused_text_index, |
| missing_component_texts, |
| docstore_audit, |
| ) = reused_document_layout( |
| docstore_path, |
| component_texts, |
| text_index, |
| reuse_below_tokens=None, |
| ) |
| else: |
| docstore_audit = { |
| "base_cache": str(docstore_path.resolve()), |
| "base_rows": 0, |
| "reused_current_rows": 0, |
| "missing_current_rows": len(component_texts), |
| } |
| print( |
| json.dumps( |
| { |
| "event": "docstore_reuse", |
| "identity": docstore_identity, |
| "reused": docstore_audit["reused_current_rows"], |
| "missing": docstore_audit["missing_current_rows"], |
| "base_rows": docstore_audit["base_rows"], |
| } |
| ), |
| flush=True, |
| ) |
| print( |
| json.dumps( |
| { |
| "event": "model_load", |
| "model": args.model, |
| "devices": args.devices.split(","), |
| } |
| ), |
| flush=True, |
| ) |
| model, query_prompt, document_prompt = load_sentence_transformer(args) |
|
|
| pool = None |
| if args.direct_device and args.load_per_worker_pool: |
| parser.error("--direct-device and --load-per-worker-pool are mutually exclusive") |
| if args.direct_device: |
| model.to(args.direct_device) |
| elif args.load_per_worker_pool: |
| model.to("cpu") |
| torch.cuda.empty_cache() |
| pool = start_model_loading_pool( |
| args.model, |
| args.max_seq_length, |
| args.devices.split(","), |
| args.model_profile, |
| args.hf_instruct_family, |
| args.truncate_dim, |
| resolved_prompt_text(model, query_prompt), |
| resolved_prompt_text(model, document_prompt), |
| ) |
| else: |
| pool = model.start_multi_process_pool(target_devices=args.devices.split(",")) |
| try: |
| encoded_documents = bucketed_encode( |
| model, |
| pool, |
| missing_component_texts, |
| document_prompt, |
| cache_path / "partial-documents", |
| checkpoint_dispatch_texts=args.checkpoint_dispatch_texts, |
| checkpoint_shard_index=args.checkpoint_shard_index, |
| checkpoint_shard_count=args.checkpoint_shard_count, |
| checkpoint_stop_after_batch_size=( |
| args.documents_shard_stop_after_batch_size |
| ), |
| ) |
| if not args.documents_shard_only: |
| queries = bucketed_encode( |
| model, |
| pool, |
| [item.query for item in work], |
| query_prompt, |
| cache_path / "partial-queries", |
| checkpoint_dispatch_texts=args.checkpoint_dispatch_texts, |
| ) |
| finally: |
| if pool is not None: |
| model.stop_multi_process_pool(pool) |
| if args.documents_shard_only: |
| print( |
| json.dumps( |
| { |
| "event": "document_shard_complete", |
| "shard_index": args.checkpoint_shard_index, |
| "shard_count": args.checkpoint_shard_count, |
| } |
| ), |
| flush=True, |
| ) |
| return 0 |
| del model |
| gc.collect() |
| if reused_documents is None: |
| documents = DocumentVectors(encoded_documents) |
| else: |
| documents = DocumentVectors(reused_documents.base, encoded_documents) |
| text_index = reused_text_index |
| encoded_documents, text_index = materialize_current_document_layout( |
| documents, text_index |
| ) |
| documents = DocumentVectors(encoded_documents) |
| save_cache(cache_path, encoded_documents, text_index, queries, work) |
| update_document_store(docstore_path, documents, text_index) |
| print( |
| json.dumps({"event": "vector_cache_write", "path": str(cache_path)}), |
| flush=True, |
| ) |
| else: |
| documents, text_index, queries = cached |
| print(json.dumps({"event": "vector_cache_hit", "path": str(cache_path)}), flush=True) |
|
|
| compose_start = time.monotonic() |
| composed, composed_rows = compose_document_matrix( |
| documents, text_index, composes, args.alpha, workers=args.workers |
| ) |
| print( |
| json.dumps( |
| { |
| "event": "composition_complete", |
| "alpha": args.alpha, |
| "vectors": len(composes), |
| "seconds": time.monotonic() - compose_start, |
| "workers": args.workers, |
| } |
| ), |
| flush=True, |
| ) |
| ks = (1, 3, 5, 10, 15, 20, 30, 50) |
| scoring_start = time.monotonic() |
| evaluations = score( |
| work, |
| args.db_dir, |
| composed, |
| composed_rows, |
| queries, |
| ks, |
| args.workers, |
| include_chunkless=args.document_shape == "parent-composed", |
| ) |
| metric_keys = ["mrr", "file_mrr"] + [ |
| f"{prefix}@{k}" |
| for k in ks |
| for prefix in ("acc", "recall", "file_acc", "file_recall") |
| ] |
| metrics, breakdown = nested_macro(evaluations, metric_keys) |
| output = { |
| "benchmark": "PatchPoint", |
| "model": args.model, |
| "model_profile": args.model_profile, |
| "model_tag": args.model_tag, |
| "document_shape": args.document_shape, |
| "alpha": args.alpha, |
| "max_seq_length": args.max_seq_length, |
| "embedding_dimension": int(documents.shape[1]), |
| "truncate_dim": args.truncate_dim, |
| "aggregation": "macro query-within-task, task-within-repository, repository-within-language, language", |
| "counts": { |
| "queries": len(evaluations), |
| "tasks": len({(row["repo"], row["task_id"]) for row in evaluations}), |
| "repositories": len({row["repo"] for row in evaluations}), |
| "languages": len({row["language"] for row in evaluations}), |
| }, |
| "gold_resolution": gold_audit, |
| "evaluation_slice": slice_audit, |
| "document_shape_audit": document_shape_audit, |
| "metrics": metrics, |
| "breakdown": breakdown, |
| "queries": evaluations, |
| } |
| args.output_dir.mkdir(parents=True, exist_ok=True) |
| alpha_tag = f"{args.alpha:g}".replace(".", "") |
| output_path = args.output_dir / f"{args.model_tag}-alpha{alpha_tag}.json" |
| output_path.write_text(json.dumps(output, indent=2, sort_keys=True) + "\n", encoding="utf-8") |
| print( |
| json.dumps( |
| { |
| "event": "evaluation_complete", |
| "output": str(output_path), |
| "seconds": time.monotonic() - scoring_start, |
| "metrics": metrics, |
| } |
| ), |
| flush=True, |
| ) |
| return 0 |
|
|
|
|
| if __name__ == "__main__": |
| raise SystemExit(main()) |
|
|