Quarry / harness /localize_sft_data.py
jbellis-brokk's picture
Publish Quarry v1
780ecbf verified
Raw
History Blame Contribute Delete
146 kB
#!/usr/bin/env python3
from __future__ import annotations
import argparse
from collections import Counter, deque
import concurrent.futures
from typing import TYPE_CHECKING, Callable, Iterable, Mapping, Sequence
from dataclasses import dataclass, field
from datetime import datetime, timezone
import hashlib
import json
import multiprocessing
import os
from pathlib import Path
import queue
import socket
import sqlite3
import struct
import subprocess
import sys
import tempfile
import threading
import time
import traceback
import uuid
if TYPE_CHECKING:
from localize_sft_core import TaskRecord
try:
from tqdm.auto import tqdm
except ImportError: # pragma: no cover - fallback for minimal environments
class tqdm: # type: ignore[no-redef]
def __init__(
self,
*,
total: int = 0,
desc: str = "",
unit: str = "",
dynamic_ncols: bool = False,
) -> None:
self.total = total
self.desc = desc
self.unit = unit
self.current = 0
self.postfix = ""
self._print()
def update(self, n: int = 1) -> None:
self.current += n
self._print()
def set_postfix_str(self, text: str) -> None:
self.postfix = text
self._print()
def close(self) -> None:
print(file=sys.stderr, flush=True)
def _print(self) -> None:
suffix = f" {self.postfix}" if self.postfix else ""
total = self.total if self.total > 0 else "?"
print(
f"\r{self.desc}: {self.current}/{total} {self.unit}{suffix}",
end="",
file=sys.stderr,
flush=True,
)
try:
from localizer_path import add_repo_paths
except ModuleNotFoundError:
from localizer.localizer_path import add_repo_paths
add_repo_paths()
from localize_sft_core import ( # noqa: E402
BifrostChunkExtractor,
BuildDbStats,
CHUNKLESS_FILE_SUMMARY_CODEUNIT,
DEFAULT_CLONES_DIR,
DEFAULT_COMMITS_ROOT,
DEFAULT_EMBEDDINGS_DIR,
DEFAULT_EXTRACT_WORKERS,
DEFAULT_NEGATIVES_PER_ROW,
DEFAULT_SCAN_TOP_K,
DEFAULT_TASKS_DIR,
DEFAULT_TASK_LIMIT_PER_LANGUAGE,
DEFAULT_TASK_LIMIT_PER_REPO,
GRANITE_MODEL,
HARD_NEGATIVES,
MAX_SEQ_LENGTH,
compare_eval_reports,
configure_cuda_visibility,
assert_query_side_compatible,
active_revisions_for_records,
active_revisions_for_repo_records,
build_chunkless_file_chunks_with_client,
build_chunkless_passage_text,
doctor_checks,
ensure_cache_compatible,
evaluate_records,
export_training_examples,
filter_records_by_base_revision_window,
group_tasks_by_repo,
has_chunkless_augment_marker,
indexed_revisions,
init_embeddings_db,
insert_chunk_rows,
iter_missing_vector_work_pages,
make_chunkless_file_chunk,
materialize_worktree,
read_cache_manifest,
make_bifrost_chunk_extractor,
make_embedder_with_manifest,
mark_chunkless_augment_done,
mine_ready_negatives,
planned_vector_pipeline_pages,
planned_remaining_unique_revisions,
print_doctor,
prune_orphan_chunks_for_repo,
read_selection,
selection_content_hash,
selection_sidecar_payload,
set_selection_hash_metadata,
short_selection_hash,
reconcile_helper_path,
refresh_repo_positives_worker,
revision_chunk_index,
revision_chunk_paths_set,
load_revision_vector_matrix,
requested_repo_filter,
select_tasks,
stream_recovered_repos,
tracked_source_files,
verify_selection_hash_against_dbs,
vector_cache_dir,
write_missing_vectors,
write_eval_report,
write_selection,
build_repo_db,
)
def export_train_repo_worker(
repo: str,
records: Sequence[object],
db_dir: Path,
negative_files: Sequence[Path],
output: Path,
split: str,
negatives_per_row: int,
max_positives_per_task: int,
selection_hash: str | None,
) -> dict[str, object]:
stats = export_training_examples(
records, # type: ignore[arg-type]
db_dir=db_dir,
negative_files=negative_files,
output=output,
split=split,
negatives_per_row=negatives_per_row,
max_positives_per_task=max_positives_per_task,
)
return {
"repo": repo,
"output": str(output),
"selection_hash": selection_hash,
"rows": stats.rows,
"tasks_exported": stats.tasks_exported,
"skipped_no_positive": stats.skipped_no_positive,
"skipped_too_few_negatives": stats.skipped_too_few_negatives,
"positives_per_task_max": stats.positives_per_task_max,
"mined_negatives_per_task_max": stats.mined_negatives_per_task_max,
"target_files_per_task_max": stats.target_files_per_task_max,
"positive_chunks_per_target_file_max": stats.positive_chunks_per_target_file_max,
"exported_gold_file_groups_per_task_max": stats.exported_gold_file_groups_per_task_max,
"missing_gold_file_groups_per_task_max": stats.missing_gold_file_groups_per_task_max,
"task_weight_exported_sum_min": stats.task_weight_exported_sum_min,
"fraction_tasks_with_partial_positive_coverage": stats.fraction_tasks_with_partial_positive_coverage,
"positive_slot_old_hunk": stats.positive_slot_old_hunk,
"positive_slot_class_summary_fallback": stats.positive_slot_class_summary_fallback,
"positive_slot_file_summary_fallback": stats.positive_slot_file_summary_fallback,
"valid_positive_slots_1": stats.valid_positive_slots_1,
"valid_positive_slots_2": stats.valid_positive_slots_2,
"valid_positive_slots_3": stats.valid_positive_slots_3,
"valid_positive_slots_4": stats.valid_positive_slots_4,
"valid_positive_negative_pairs": stats.valid_positive_negative_pairs,
"rows_with_3_plus_old_hunks": stats.rows_with_3_plus_old_hunks,
"rows_with_4_old_hunks": stats.rows_with_4_old_hunks,
"fallback_only_rows": stats.fallback_only_rows,
}
def concatenate_jsonl_shards(shard_paths: Sequence[Path], output: Path) -> None:
output.parent.mkdir(parents=True, exist_ok=True)
with output.open("wb") as out:
for shard_path in shard_paths:
if not shard_path.exists():
continue
with shard_path.open("rb") as src:
while True:
chunk = src.read(1024 * 1024)
if not chunk:
break
out.write(chunk)
def aggregate_parallel_export_stats(rows: Sequence[dict[str, object]], output: Path) -> dict[str, object]:
int_fields = [
"rows",
"tasks_exported",
"skipped_no_positive",
"skipped_too_few_negatives",
"positive_slot_old_hunk",
"positive_slot_class_summary_fallback",
"positive_slot_file_summary_fallback",
"valid_positive_slots_1",
"valid_positive_slots_2",
"valid_positive_slots_3",
"valid_positive_slots_4",
"valid_positive_negative_pairs",
"rows_with_3_plus_old_hunks",
"rows_with_4_old_hunks",
"fallback_only_rows",
]
max_fields = [
"positives_per_task_max",
"mined_negatives_per_task_max",
"target_files_per_task_max",
"positive_chunks_per_target_file_max",
"exported_gold_file_groups_per_task_max",
"missing_gold_file_groups_per_task_max",
]
summary: dict[str, object] = {"output": str(output), "repo_workers": len(rows)}
for field_name in int_fields:
summary[field_name] = sum(int(row.get(field_name, 0)) for row in rows)
for field_name in max_fields:
summary[field_name] = max((int(row.get(field_name, 0)) for row in rows), default=0)
mins = [
float(row["task_weight_exported_sum_min"])
for row in rows
if float(row.get("task_weight_exported_sum_min", 0.0)) > 0.0
]
summary["task_weight_exported_sum_min"] = min(mins) if mins else 0.0
exported = int(summary["tasks_exported"])
if exported:
partial_tasks = sum(
float(row.get("fraction_tasks_with_partial_positive_coverage", 0.0))
* int(row.get("tasks_exported", 0))
for row in rows
)
summary["fraction_tasks_with_partial_positive_coverage"] = partial_tasks / exported
else:
summary["fraction_tasks_with_partial_positive_coverage"] = 0.0
summary["note"] = "parallel export aggregates exact counts/maxima; percentile fields are omitted"
return summary
def _warn_stderr(message: str) -> None:
print(message, file=sys.stderr)
def write_selection_artifacts(records: Sequence[object], legacy_output: Path) -> tuple[Path, Path, dict[str, object]]:
typed_records = list(records)
selection_hash = selection_content_hash(typed_records) # type: ignore[arg-type]
short_hash = short_selection_hash(selection_hash)
created_at = datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
dated_name = f"selection-{created_at[:10].replace('-', '')}-{short_hash}.jsonl"
canonical_path = legacy_output.parent / dated_name
sidecar_path = legacy_output.parent / f"{canonical_path.stem}.meta.json"
write_selection(typed_records, canonical_path) # type: ignore[arg-type]
sidecar = selection_sidecar_payload(typed_records, created_at=created_at) # type: ignore[arg-type]
sidecar_path.write_text(json.dumps(sidecar, indent=2, sort_keys=True), encoding="utf-8")
write_selection(typed_records, legacy_output) # type: ignore[arg-type]
return canonical_path, sidecar_path, sidecar
@dataclass(frozen=True)
class GpuWorkerSpec:
gpu: str
repo_workers: int
batch_size: int | None = None
def parse_single_gpu_worker(value: str) -> GpuWorkerSpec:
parts = value.split(":")
if len(parts) not in (1, 2) or not parts[0]:
raise argparse.ArgumentTypeError("expected GPU[:BATCH_SIZE]")
try:
batch_size = int(parts[1]) if len(parts) == 2 else None
except ValueError as exc:
raise argparse.ArgumentTypeError("batch size must be an integer") from exc
if batch_size is not None and batch_size < 1:
raise argparse.ArgumentTypeError("batch size must be >= 1")
return GpuWorkerSpec(parts[0], 1, batch_size)
@dataclass(frozen=True)
class NativeGpuWorkerSpec:
gpu: str
batch_size: int | None = None
@dataclass(frozen=True)
class NativeWorkerRuntime:
key: str
spec: NativeGpuWorkerSpec
def parse_native_gpu_worker(value: str) -> NativeGpuWorkerSpec:
parts = value.split(":")
if len(parts) not in (1, 2) or not parts[0]:
raise argparse.ArgumentTypeError("expected GPU[:BATCH_SIZE]")
try:
batch_size = int(parts[1]) if len(parts) == 2 else None
except ValueError as exc:
raise argparse.ArgumentTypeError("batch size must be an integer") from exc
if batch_size is not None and batch_size < 1:
raise argparse.ArgumentTypeError("batch size must be >= 1")
return NativeGpuWorkerSpec(parts[0], batch_size)
def parse_repo_shard(value: str) -> tuple[int, int]:
try:
index_text, count_text = value.split("/", 1)
index = int(index_text)
count = int(count_text)
except ValueError as exc:
raise argparse.ArgumentTypeError("--repo-shard must be INDEX/COUNT") from exc
if count <= 0:
raise argparse.ArgumentTypeError("--repo-shard count must be positive")
if index < 0 or index >= count:
raise argparse.ArgumentTypeError("--repo-shard index must satisfy 0 <= index < count")
return index, count
def repo_shard_index(repo: str, shard_count: int) -> int:
digest = hashlib.blake2b(repo.encode("utf-8"), digest_size=8).digest()
return int.from_bytes(digest, byteorder="big") % shard_count
def filter_records_by_repo_shard(
records: Sequence[TaskRecord],
repo_shard: tuple[int, int] | None,
) -> list[TaskRecord]:
if repo_shard is None:
return list(records)
shard_index, shard_count = repo_shard
return [
record
for record in records
if repo_shard_index(record.repo, shard_count) == shard_index
]
def _native_worker_runtimes(workers: Sequence[NativeGpuWorkerSpec]) -> list[NativeWorkerRuntime]:
physical_counts = Counter(worker.gpu for worker in workers)
seen: Counter[str] = Counter()
runtimes: list[NativeWorkerRuntime] = []
for spec in workers:
ordinal = seen[spec.gpu]
seen[spec.gpu] += 1
key = spec.gpu if physical_counts[spec.gpu] == 1 else f"{spec.gpu}.{ordinal}"
runtimes.append(NativeWorkerRuntime(key, spec))
return runtimes
def selected_repos_from_grouped(
grouped: dict[str, list],
args: argparse.Namespace,
) -> list[str]:
repos = sorted(grouped)
requested = requested_repo_filter(args)
if requested is not None:
repos = [repo for repo in repos if repo in requested]
if args.limit_repos is not None:
repos = repos[: args.limit_repos]
return repos
def repo_records_for_args(
repo: str,
grouped: dict[str, list],
args: argparse.Namespace,
) -> list:
records = grouped[repo]
if getattr(args, "max_tasks_per_repo", None) is not None:
records = records[: args.max_tasks_per_repo]
start_base = getattr(args, "start_base_revision", None)
end_base = getattr(args, "end_base_revision", None)
if start_base is None and end_base is None:
return records
return filter_records_by_base_revision_window(
records,
args.clones_dir / repo,
start_base_revision=start_base,
end_base_revision=end_base,
)
def _short_repo_name(repo: object) -> str:
text = str(repo)
if "__" in text:
return text.rsplit("__", 1)[1]
if "/" in text:
return text.rsplit("/", 1)[1]
return text
def _clone_repos_for_build(
repos: Sequence[str],
*,
clones_dir: Path,
progress: tqdm,
clone_workers: int,
debug: bool,
) -> tuple[list[str], int]:
available: list[str] = []
errors = 0
clone_stream = stream_recovered_repos(
repos,
clones_dir,
workers=clone_workers,
)
try:
for repo, clone_error in clone_stream:
progress.set_postfix_str(_short_repo_name(repo))
progress.update(1)
if clone_error is None:
available.append(repo)
else:
errors += 1
if debug:
print(json.dumps({"repo": repo, "error": clone_error}, sort_keys=True), file=sys.stderr)
else:
print(f"error: {_short_repo_name(repo)} clone failed: {clone_error}", file=sys.stderr)
finally:
clone_stream.close()
return available, errors
def _db_progress_event(queue: object, repo: str, revision: str, completed: int, total_tasks: int) -> None:
put = getattr(queue, "put")
put({"event": "revision", "repo": repo, "revision": revision, "completed": completed, "total_tasks": total_tasks})
def _db_log_event(queue: object, repo: str, message: str) -> None:
put = getattr(queue, "put")
put({"event": "log", "repo": repo, "message": message})
def _extract_task_progress(message: str) -> tuple[int, int] | None:
marker = "task="
index = message.find(marker)
if index < 0:
return None
start = index + len(marker)
end = start
while end < len(message) and message[end] not in {" ", "\t", ","}:
end += 1
value = message[start:end]
if "/" not in value:
return None
left, right = value.split("/", 1)
try:
current = int(left)
total = int(right)
except ValueError:
return None
if current < 0 or total < 0:
return None
return current, total
def build_db_worker_entry(
records: Sequence,
*,
clones_dir: Path,
db_dir: Path,
selection_hash: str | None,
bifrost_library: Path | None,
resume: bool,
extract_workers: int,
progress_queue: object | None,
bifrost_cache_dir: Path | None = None,
is_big: bool = False,
big_repo_gate: object | None = None,
revision_overrides: Mapping[str, str] | None = None,
) -> BuildDbStats:
repo = records[0].repo if records else "<empty>"
# Memory packing: a big repo holds extract_workers heavy bifrost analyzers. The
# cross-process gate (Semaphore) caps how many big repos run concurrently so the
# many cheap small repos can fill repo_workers without ever stacking two giants
# (which OOM-stalls). Small repos never touch the gate.
gate = big_repo_gate if (is_big and big_repo_gate is not None) else None
if gate is not None:
gate.acquire()
previous_bifrost_cache = os.environ.get("BIFROST_CACHE_DIR")
if bifrost_cache_dir is not None:
bifrost_cache_dir.mkdir(parents=True, exist_ok=True)
os.environ["BIFROST_CACHE_DIR"] = str(bifrost_cache_dir)
try:
stats = build_repo_db(
records,
clones_dir=clones_dir,
embeddings_dir=db_dir,
selection_hash=selection_hash,
chunk_extractor=make_bifrost_chunk_extractor(bifrost_library),
progress=(
(lambda message, current_repo=repo: _db_log_event(progress_queue, current_repo, message))
if progress_queue is not None
else None
),
on_revision=(
(lambda current_repo, revision, completed, total_tasks: _db_progress_event(
progress_queue, current_repo, revision, completed, total_tasks
))
if progress_queue is not None
else None
),
resume=resume,
extract_workers=extract_workers,
revision_overrides=revision_overrides,
)
return stats
except Exception as exc:
error_text = traceback.format_exc()
return BuildDbStats(
repo=repo,
tasks=len(records),
revisions=0,
chunks=0,
positives=0,
skipped=True,
error=error_text or repr(exc),
)
finally:
if bifrost_cache_dir is not None:
if previous_bifrost_cache is None:
os.environ.pop("BIFROST_CACHE_DIR", None)
else:
os.environ["BIFROST_CACHE_DIR"] = previous_bifrost_cache
if gate is not None:
gate.release()
def _load_seeded_chunkless_rows(
seed_dir: Path | None,
repo: str,
) -> dict[tuple[str, str], str]:
if seed_dir is None:
return {}
path = seed_dir / repo / "synthetic_rows.jsonl"
if not path.is_file():
return {}
seeded: dict[tuple[str, str], str] = {}
with path.open(encoding="utf-8") as handle:
for line_number, raw_line in enumerate(handle, start=1):
line = raw_line.strip()
if not line:
continue
row = json.loads(line)
if not isinstance(row, dict):
raise ValueError(f"{path}:{line_number}: expected object")
revision = str(row.get("revision", ""))
file_path = str(row.get("path", ""))
text = str(row.get("text", ""))
if revision and file_path and text:
seeded[(revision, file_path)] = text
return seeded
@dataclass
class _ChunklessMemoEntry:
event: threading.Event
text: str = ""
ready: bool = False
class _ChunklessContentMemo:
def __init__(self) -> None:
self._lock = threading.Lock()
self._entries: dict[str, _ChunklessMemoEntry] = {}
self.memo_hits = 0
self.bifrost_calls = 0
def prime(self, content_hash: str, text: str) -> None:
with self._lock:
entry = self._entries.get(content_hash)
if entry is None:
ready = threading.Event()
ready.set()
self._entries[content_hash] = _ChunklessMemoEntry(
event=ready,
text=text,
ready=True,
)
return
if not entry.ready:
entry.text = text
entry.ready = True
entry.event.set()
def get_or_build(self, content_hash: str, builder: Callable[[], str]) -> str:
wait_for: threading.Event | None = None
with self._lock:
entry = self._entries.get(content_hash)
if entry is not None:
if entry.ready:
self.memo_hits += 1
return entry.text
wait_for = entry.event
else:
wait_for = threading.Event()
self._entries[content_hash] = _ChunklessMemoEntry(event=wait_for)
self.bifrost_calls += 1
wait_for = None
if wait_for is not None:
wait_for.wait()
with self._lock:
entry = self._entries[content_hash]
self.memo_hits += 1
return entry.text
text = builder()
with self._lock:
entry = self._entries[content_hash]
entry.text = text
entry.ready = True
entry.event.set()
return text
def _worktree_file_hash(worktree: Path, path: str) -> str | None:
file_path = worktree / path
try:
data = file_path.read_bytes()
except OSError:
return None
return hashlib.sha256(data).hexdigest()
def _prime_chunkless_seed_memo(
memo: _ChunklessContentMemo,
worktree: Path,
revision: str,
seeded: dict[tuple[str, str], str],
) -> None:
for (seed_revision, path), text in seeded.items():
if seed_revision != revision:
continue
content_hash = _worktree_file_hash(worktree, path)
if content_hash is not None:
memo.prime(content_hash, text)
def _reconcile_augmented_vectors(
repo_revisions: Sequence[tuple[str, Sequence[str]]],
*,
db_dir: Path,
vector_cache_dirs: Sequence[Path],
model: str,
batch_size: int,
max_seq_length: int,
page_size: int,
) -> list[dict[str, object]]:
if not repo_revisions or not vector_cache_dirs:
return []
summaries: list[dict[str, object]] = []
for cache_dir in vector_cache_dirs:
on_disk = read_cache_manifest(cache_dir)
if on_disk is None:
raise RuntimeError(f"no vector cache manifest at {cache_dir}")
embed_texts, expected_manifest = make_embedder_with_manifest(
model,
batch_size=batch_size,
max_seq_length=max_seq_length,
role="passage",
)
ensure_cache_compatible(cache_dir, expected_manifest) # type: ignore[arg-type]
manifest_digest = expected_manifest.digest() # type: ignore[union-attr]
embed_lock = threading.Lock()
def locked_embed_texts(texts: list[str]) -> list[list[float]]:
with embed_lock:
return embed_texts(texts) # type: ignore[misc]
def reconcile_repo(repo_revision: tuple[str, Sequence[str]]) -> tuple[str, int]:
repo, revisions = repo_revision
written = 0
for page in iter_missing_vector_work_pages(
repo,
revisions,
db_dir=db_dir,
vector_cache_dir=cache_dir,
manifest_digest=manifest_digest,
page_size=page_size,
):
written += write_missing_vectors(
cache_dir,
repo,
page.chunks,
locked_embed_texts,
manifest_digest=manifest_digest,
batch_size=batch_size,
page_size=page_size,
)
return repo, written
repo_counts: dict[str, int] = {}
# Each reconcile thread spawns a helper whose `GROUP BY/ORDER BY vector_key` spills a large
# SQLite sort temp; an os.cpu_count()-sized pool on a high-core box runs dozens concurrently
# and can fill the temp volume (saw 64-way concurrency blow past a 700G disk). Cap via
# LOCALIZE_RECONCILE_WORKERS so concurrent spills stay bounded (pair with SQLITE_TMPDIR=/dev/shm).
default_workers = min(max(1, os.cpu_count() or 1), len(repo_revisions))
env_cap = os.environ.get("LOCALIZE_RECONCILE_WORKERS")
workers = min(max(1, int(env_cap)), len(repo_revisions)) if env_cap else default_workers
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
futures = [pool.submit(reconcile_repo, item) for item in repo_revisions]
for future in concurrent.futures.as_completed(futures):
repo, written = future.result()
repo_counts[repo] = written
summaries.append(
{
"vector_cache_dir": str(cache_dir),
"manifest_digest": manifest_digest,
"vectors_written": sum(repo_counts.values()),
"repo_counts": dict(sorted(repo_counts.items())),
}
)
return summaries
def augment_chunkless_repo_worker(
repo: str,
*,
db_dir: Path,
clones_dir: Path,
seed_dir: Path | None,
seed_only: bool,
revisions: Sequence[str] | None,
summary_workers: int,
vector_cache_dirs: Sequence[Path],
model: str,
batch_size: int,
max_seq_length: int,
page_size: int,
dry_run: bool,
) -> dict[str, object]:
repo_path = clones_dir / repo
db_path = db_dir / repo / "embeddings.db"
if not repo_path.is_dir():
raise FileNotFoundError(f"missing clone for {repo}: {repo_path}")
if not db_path.exists():
raise FileNotFoundError(f"missing embeddings DB for {repo}: {db_path}")
seeded = _load_seeded_chunkless_rows(seed_dir, repo)
conn = init_embeddings_db(db_path)
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=NORMAL")
try:
available_revisions = indexed_revisions(conn)
selected_revisions = available_revisions if revisions is None else [
rev for rev in revisions if rev in available_revisions
]
if seed_only:
seeded_revisions = {revision for revision, _path in seeded}
selected_revisions = [rev for rev in selected_revisions if rev in seeded_revisions]
pending_revisions = [rev for rev in selected_revisions if not has_chunkless_augment_marker(conn, rev)]
summary: dict[str, object] = {
"repo": repo,
"revisions_seen": len(selected_revisions),
"revisions_processed": len(pending_revisions),
"chunkless_candidates": 0,
"chunkless_inserted": 0,
"chunkless_skipped": 0,
"seeded_rows_used": 0,
"memo_hits": 0,
"bifrost_calls": 0,
"dry_run": dry_run,
"seed_only": seed_only,
}
if dry_run:
for revision in pending_revisions:
indexed_paths = revision_chunk_paths_set(conn, revision)
candidates = [
path
for path in tracked_source_files(repo_path, revision)
if path not in indexed_paths
]
summary["chunkless_candidates"] = int(summary["chunkless_candidates"]) + len(candidates)
return summary
extractor = BifrostChunkExtractor()
content_memo = _ChunklessContentMemo()
for revision in pending_revisions:
indexed_paths = revision_chunk_paths_set(conn, revision)
candidate_paths = [
path
for path in tracked_source_files(repo_path, revision)
if path not in indexed_paths
]
summary["chunkless_candidates"] = int(summary["chunkless_candidates"]) + len(candidate_paths)
synthetic_chunks = [
make_chunkless_file_chunk(
repo=repo,
revision=revision,
path=path,
text=seeded[(revision, path)],
)
for path in candidate_paths
if (revision, path) in seeded
]
summary["seeded_rows_used"] = int(summary["seeded_rows_used"]) + len(synthetic_chunks)
unseeded_paths = [path for path in candidate_paths if (revision, path) not in seeded]
skipped_paths: list[str] = []
if unseeded_paths and not seed_only:
with materialize_worktree(repo_path, revision) as worktree:
_prime_chunkless_seed_memo(content_memo, worktree, revision, seeded)
existing_paths = [path for path in unseeded_paths if (worktree / path).is_file()]
with extractor.open_client(worktree) as summary_client:
def memoized_passage_builder(path: str) -> str:
content_hash = _worktree_file_hash(worktree, path)
if content_hash is None:
return ""
return content_memo.get_or_build(
content_hash,
lambda: build_chunkless_passage_text(summary_client, path),
)
built_chunks, skipped_paths = build_chunkless_file_chunks_with_client(
summary_client,
worktree,
repo,
revision,
existing_paths,
summary_workers=summary_workers,
passage_builder=memoized_passage_builder,
)
synthetic_chunks.extend(built_chunks)
before = int(
conn.execute(
"""
SELECT COUNT(*)
FROM chunk_rows
WHERE revision = ?
AND codeunit_name = ?
""",
(revision, CHUNKLESS_FILE_SUMMARY_CODEUNIT),
).fetchone()[0]
)
conn.execute("BEGIN")
try:
insert_chunk_rows(conn, synthetic_chunks, or_ignore=True)
mark_chunkless_augment_done(conn, revision)
conn.commit()
except Exception:
conn.rollback()
raise
after = int(
conn.execute(
"""
SELECT COUNT(*)
FROM chunk_rows
WHERE revision = ?
AND codeunit_name = ?
""",
(revision, CHUNKLESS_FILE_SUMMARY_CODEUNIT),
).fetchone()[0]
)
summary["chunkless_inserted"] = int(summary["chunkless_inserted"]) + max(0, after - before)
summary["chunkless_skipped"] = int(summary["chunkless_skipped"]) + len(skipped_paths)
summary["memo_hits"] = content_memo.memo_hits
summary["bifrost_calls"] = content_memo.bifrost_calls
summary["selected_revisions"] = list(selected_revisions)
return summary
finally:
conn.close()
def _plan_build_db_repo(
repo: str,
*,
grouped: dict[str, list],
args: argparse.Namespace,
) -> tuple[str, list, int]:
records_for_repo = repo_records_for_args(repo, grouped, args)
count, _remaining = planned_remaining_unique_revisions(
records_for_repo,
repo_path=args.clones_dir / repo,
db_path=args.db_dir / repo / "embeddings.db",
resume=not args.no_resume,
)
return repo, records_for_repo, count
def _plan_build_db_repos(
repos: Sequence[str],
*,
grouped: dict[str, list],
args: argparse.Namespace,
) -> tuple[dict[str, list], dict[str, int]]:
repo_records: dict[str, list] = {}
revision_counts: dict[str, int] = {}
if not repos:
return repo_records, revision_counts
workers = max(1, min(len(repos), args.repo_workers))
progress = tqdm(total=len(repos), desc="plan db", unit="repo", dynamic_ncols=True)
try:
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
futures = {
pool.submit(_plan_build_db_repo, repo, grouped=grouped, args=args): repo
for repo in repos
}
for future in concurrent.futures.as_completed(futures):
repo = futures[future]
progress.set_postfix_str(_short_repo_name(repo))
planned_repo, records_for_repo, count = future.result()
if records_for_repo:
repo_records[planned_repo] = records_for_repo
revision_counts[planned_repo] = count
progress.update(1)
finally:
progress.close()
return repo_records, revision_counts
def _repo_tree_bytes(repo_path: Path) -> int:
total = 0
for root, dirs, files in os.walk(repo_path):
if ".git" in dirs:
dirs.remove(".git")
for name in files:
try:
total += os.path.getsize(os.path.join(root, name))
except OSError:
pass
return total
def _pack_repos_by_size(
repos: Sequence[str],
*,
clones_dir: Path,
big_bytes: int,
) -> tuple[list[str], set[str]]:
"""Order repos so memory-heavy 'big' repos are spread evenly among the many cheap
'small' ones, and return the set of bigs. The extraction ProcessPool is FIFO, so this
list order *is* the schedule: spacing bigs far apart keeps worker slots filled with
small repos instead of blocking on the big-repo gate. Pairs with the Semaphore guard
in build_db_worker_entry, which is the hard 'at most N bigs in flight' guarantee."""
sizes: dict[str, int] = {}
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as pool:
fut = {pool.submit(_repo_tree_bytes, clones_dir / r): r for r in repos}
for f in concurrent.futures.as_completed(fut):
sizes[fut[f]] = f.result()
bigs = sorted((r for r in repos if sizes.get(r, 0) >= big_bytes), key=lambda r: -sizes[r])
smalls = sorted((r for r in repos if sizes.get(r, 0) < big_bytes), key=lambda r: -sizes[r])
if not bigs:
return smalls, set()
gap = max(1, len(smalls) // (len(bigs) + 1))
ordered: list[str] = []
bi = 0
for i, repo in enumerate(smalls):
if i % gap == 0 and bi < len(bigs):
ordered.append(bigs[bi])
bi += 1
ordered.append(repo)
ordered.extend(bigs[bi:])
return ordered, set(bigs)
def _send_frame(sock: socket.socket, payload: dict[str, object]) -> None:
data = json.dumps(payload, separators=(",", ":")).encode("utf-8")
sock.sendall(struct.pack("<I", len(data)) + data)
def _recv_exact(sock: socket.socket, size: int) -> bytes:
chunks: list[bytes] = []
remaining = size
while remaining:
chunk = sock.recv(remaining)
if not chunk:
raise EOFError("native worker closed the socket")
chunks.append(chunk)
remaining -= len(chunk)
return b"".join(chunks)
def _recv_frame(sock: socket.socket) -> dict[str, object]:
header = _recv_exact(sock, 4)
size = struct.unpack("<I", header)[0]
if size == 0:
return {}
return json.loads(_recv_exact(sock, size).decode("utf-8"))
class NativeGpuWorker:
def __init__(
self,
*,
helper: Path,
worker_key: str,
gpu: NativeGpuWorkerSpec,
vector_cache_dir: Path,
manifest_digest: str,
batch_size: int,
max_seq_length: int,
model: str,
target_padded_tokens: int,
target_attention_tokens: int,
encode_dtype: str,
attn_implementation: str,
) -> None:
self.helper = helper
self.worker_key = worker_key
self.gpu = gpu
self.vector_cache_dir = vector_cache_dir
self.manifest_digest = manifest_digest
self.batch_size = gpu.batch_size if gpu.batch_size is not None else batch_size
self.max_seq_length = max_seq_length
self.model = model
self.target_padded_tokens = target_padded_tokens
self.target_attention_tokens = target_attention_tokens
self.encode_dtype = encode_dtype
self.attn_implementation = attn_implementation
self.socket_path: Path | None = None
self.process: subprocess.Popen[str] | None = None
self.sock: socket.socket | None = None
self.lock = threading.Lock()
self.reader: threading.Thread | None = None
self.events: "queue.Queue[dict[str, object]]" = queue.Queue()
def start(self, temp_dir: Path) -> None:
safe_key = self.worker_key.replace("/", "_").replace(":", "_").replace(".", "_")
self.socket_path = temp_dir / f"native-gpu-{safe_key}.sock"
try:
self.socket_path.unlink()
except FileNotFoundError:
pass
command = [
# Launch the worker with the SAME interpreter as the parent build
# (e.g. .venv312, which already has torch/transformers/bifrost) rather
# than the helper's `uv run` shebang, which re-syncs the entire fat
# localizer env (PyQt6/scipy/CUDA) from a cold cache and blows the
# connect deadline. Inheriting sys.executable keeps worker and parent
# on one proven env.
sys.executable,
str(self.helper),
"gpu-worker",
"--gpu",
self.gpu.gpu,
"--socket",
str(self.socket_path),
"--batch-size",
str(self.batch_size),
"--max-seq-length",
str(self.max_seq_length),
"--model",
self.model,
"--target-padded-tokens",
str(self.target_padded_tokens),
"--target-attention-tokens",
str(self.target_attention_tokens),
"--encode-dtype",
self.encode_dtype,
"--attn-implementation",
self.attn_implementation,
]
self.process = subprocess.Popen(command, text=True)
deadline = time.monotonic() + 30.0
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
while True:
try:
sock.connect(str(self.socket_path))
break
except OSError:
if self.process.poll() is not None:
raise RuntimeError(f"native gpu worker {self.gpu.gpu} exited with code {self.process.returncode}")
if time.monotonic() >= deadline:
self.process.terminate()
raise RuntimeError(f"timed out connecting to native gpu worker {self.gpu.gpu}")
time.sleep(0.05)
self.sock = sock
self.reader = threading.Thread(target=self._read_events, daemon=True)
self.reader.start()
def _read_events(self) -> None:
assert self.sock is not None
while True:
try:
event = _recv_frame(self.sock)
except EOFError:
self.events.put({"event": "worker_closed", "gpu": self.gpu.gpu})
return
except Exception as exc:
self.events.put({"event": "worker_error", "gpu": self.gpu.gpu, "error": repr(exc)})
return
if not event:
continue
self.events.put(event)
if event.get("event") == "shutdown_ack":
return
def submit_page(self, task: "NativePageTask") -> None:
cache_dir = vector_cache_dir(self.vector_cache_dir, task.repo, manifest_digest=self.manifest_digest)
with self.lock:
if self.sock is None:
raise RuntimeError(f"native gpu worker {self.gpu.gpu} is not connected")
_send_frame(
self.sock,
{
"event": "submit_page",
"repo": task.repo,
"revision": task.revision,
"page": task.page,
"page_count": task.page_count,
"batch_size": task.batch_size or self.batch_size,
"cache_dir": str(cache_dir),
"manifest_digest": self.manifest_digest,
"components": task.components,
"vectors": task.vectors,
},
)
def shutdown(self) -> int:
if self.sock is not None:
try:
with self.lock:
_send_frame(self.sock, {"event": "shutdown"})
except OSError:
pass
if self.reader is not None:
self.reader.join(timeout=5)
if self.sock is not None:
self.sock.close()
if self.process is None:
return 0
try:
return self.process.wait(timeout=10)
except subprocess.TimeoutExpired:
self.process.terminate()
return self.process.wait(timeout=10)
@dataclass
class NativePageTask:
repo: str
revision: str
page: int
page_count: int
components: list[dict[str, object]]
vectors: list[dict[str, str]]
work_units: int
source: str = "build"
batch_size: int = 0
excluded_gpus: tuple[str, ...] = ()
preferred_gpus: tuple[str, ...] = ()
max_estimated_tokens: int = 0
started_at: float = 0.0
@dataclass
class BatchTelemetry:
shards: int = 0
components: int = 0
vectors: int = 0
elapsed_seconds: float = 0.0
encode_seconds: float = 0.0
tokens: int = 0
padded_tokens: int = 0
attention_tokens: int = 0
ewma_components_per_second: float = 0.0
ewma_vectors_per_second: float = 0.0
ewma_tokens_per_second: float = 0.0
ewma_padded_tokens_per_second: float = 0.0
@dataclass
class GpuTelemetry:
gpu: str
configured_batch_size: int
autotune_candidates: tuple[int, ...] = ()
batch_profiles: dict[int, BatchTelemetry] = field(default_factory=dict)
locked_batch_size: int = 0
pages: int = 0
shards: int = 0
components: int = 0
components_written: int = 0
vectors: int = 0
composed_written: int = 0
elapsed_seconds: float = 0.0
encode_seconds: float = 0.0
read_seconds: float = 0.0
write_seconds: float = 0.0
compose_seconds: float = 0.0
tokens: int = 0
padded_tokens: int = 0
attention_tokens: int = 0
micro_batches: int = 0
ewma_components_per_second: float = 0.0
ewma_vectors_per_second: float = 0.0
ewma_tokens_per_second: float = 0.0
ewma_padded_tokens_per_second: float = 0.0
current_batch_size: int = 0
current_max_seq_length: int = 0
first_started_at: float = 0.0
measured_at: float = 0.0
backoffs: int = 0
def __post_init__(self) -> None:
self.current_batch_size = self.configured_batch_size
@property
def measured(self) -> bool:
if self.autotune_candidates:
return self.locked_batch_size > 0
return self.shards >= 3
@property
def weight(self) -> float:
if self.ewma_padded_tokens_per_second > 0.0:
return self.ewma_padded_tokens_per_second
if self.ewma_tokens_per_second > 0.0:
return self.ewma_tokens_per_second
if self.ewma_components_per_second > 0.0:
return self.ewma_components_per_second * 512.0
return float(max(1, self.configured_batch_size))
def _batch_autotune_candidates(configured_batch_size: int) -> tuple[int, ...]:
candidates = {max(1, configured_batch_size)}
batch = max(1, configured_batch_size)
while batch > 64:
batch = max(64, batch // 2)
candidates.add(batch)
if configured_batch_size <= 64 and configured_batch_size > 16:
candidates.add(max(16, configured_batch_size // 2))
return tuple(sorted(candidates, reverse=True))
def _choose_autotune_batch(profile: GpuTelemetry) -> int:
if profile.locked_batch_size > 0:
return profile.locked_batch_size
if not profile.autotune_candidates:
return profile.current_batch_size
for candidate in profile.autotune_candidates:
if profile.batch_profiles.get(candidate, BatchTelemetry()).shards < 2:
profile.current_batch_size = candidate
return candidate
best = max(
profile.autotune_candidates,
key=lambda candidate: profile.batch_profiles.get(candidate, BatchTelemetry()).ewma_components_per_second,
)
profile.locked_batch_size = best
profile.current_batch_size = best
return best
def _pop_next_eligible_task(
pending: "deque[NativePageTask]",
worker: NativeGpuWorker,
) -> NativePageTask | None:
blocked: deque[NativePageTask] = deque()
while pending:
candidate = pending.popleft()
physical_gpu = worker.gpu.gpu
if physical_gpu in candidate.excluded_gpus:
blocked.append(candidate)
elif candidate.preferred_gpus and physical_gpu not in candidate.preferred_gpus:
blocked.append(candidate)
else:
pending.extend(blocked)
return candidate
pending.extend(blocked)
return None
def _wait_for_worker_revision(
worker: NativeGpuWorker,
repo: str,
revision: str,
*,
timeout_seconds: float = 1800.0,
) -> dict[str, object]:
deadline = time.monotonic() + timeout_seconds
while True:
timeout = max(0.0, deadline - time.monotonic())
if timeout == 0.0:
raise TimeoutError(f"timed out waiting for native worker {worker.gpu.gpu} on {repo} {revision}")
if worker.process is not None and worker.process.poll() is not None:
raise RuntimeError(f"native gpu worker {worker.gpu.gpu} exited with code {worker.process.returncode}")
try:
event = worker.events.get(timeout=min(timeout, 1.0))
except queue.Empty:
continue
event_type = event.get("event")
if event_type in {"ready", "shutdown_ack"}:
continue
if event_type in {"worker_closed", "worker_error"}:
raise RuntimeError(str(event))
if str(event.get("repo", "")) == repo and str(event.get("revision", "")) == revision:
return event
def _submit_native_pages(
native_workers: Sequence[NativeGpuWorker],
pending: "deque[NativePageTask]",
in_flight: dict[NativeGpuWorker, NativePageTask],
next_worker: int,
telemetry: dict[str, GpuTelemetry],
) -> tuple[int, int, int]:
submitted = 0
submitted_existing = 0
idle_workers = [worker for worker in native_workers if worker not in in_flight]
for worker in idle_workers:
if not pending:
break
task = _pop_next_eligible_task(pending, worker)
if task is None:
continue
task.started_at = time.monotonic()
profile = telemetry[worker.worker_key]
if profile.first_started_at == 0.0:
profile.first_started_at = task.started_at
task.batch_size = _choose_autotune_batch(profile)
worker.submit_page(task)
in_flight[worker] = task
submitted += 1
if task.source == "existing":
submitted_existing += 1
return submitted, submitted_existing, next_worker
def _is_fatal_native_worker_config_error(event: dict[str, object]) -> bool:
message = " ".join(str(event.get(key, "")) for key in ("message", "error", "traceback")).lower()
return (
"flashattention2" in message
or "flashattention 2" in message
or "flash_attn" in message
or "attn_implementation" in message
or "importerror" in message
or "package is not installed" in message
or "no package metadata was found" in message
)
def _handle_native_worker_event(
native_workers: Sequence[NativeGpuWorker],
worker: NativeGpuWorker,
event: dict[str, object],
pending: "deque[NativePageTask]",
in_flight: dict[NativeGpuWorker, NativePageTask],
telemetry: dict[str, GpuTelemetry],
scheduler_stats: dict[str, float],
progress: tqdm,
*,
errors: int,
) -> int:
event_type = event.get("event")
if event_type in {"ready", "shutdown_ack"}:
return errors
if event_type in {"worker_closed", "worker_error"}:
raise RuntimeError(str(event))
if event_type not in {"progress", "error"}:
return errors
task = in_flight.get(worker)
if task is None:
raise RuntimeError(f"native gpu worker {worker.gpu.gpu} returned {event_type} with no in-flight page")
repo = str(event.get("repo", ""))
revision = str(event.get("revision", ""))
page = int(event.get("page", -1))
if repo != task.repo or revision != task.revision or page != task.page:
raise RuntimeError(
f"native gpu worker {worker.gpu.gpu} returned out-of-order event "
f"{repo} {revision} page={page}; expected {task.repo} {task.revision} page={task.page}"
)
in_flight.pop(worker, None)
if event_type == "error":
if _is_fatal_native_worker_config_error(event):
raise RuntimeError(f"fatal native worker configuration error: {event}")
excluded = tuple(sorted(set(task.excluded_gpus + (worker.gpu.gpu,))))
preferred_gpus = task.preferred_gpus
has_eligible_worker = any(
candidate.gpu.gpu not in excluded
and (not preferred_gpus or candidate.gpu.gpu in preferred_gpus)
for candidate in native_workers
)
if not has_eligible_worker and preferred_gpus:
preferred_gpus = ()
has_eligible_worker = any(candidate.gpu.gpu not in excluded for candidate in native_workers)
if has_eligible_worker:
pending.append(
NativePageTask(
task.repo,
task.revision,
task.page,
task.page_count,
task.components,
task.vectors,
task.work_units,
source=task.source,
excluded_gpus=excluded,
preferred_gpus=preferred_gpus,
max_estimated_tokens=task.max_estimated_tokens,
)
)
progress.set_postfix_str(
f"{_short_repo_name(task.repo)} retrying {task.revision[:12]} page={task.page} without gpu {worker.gpu.gpu}"
)
else:
errors += 1
print(json.dumps(event, sort_keys=True), file=sys.stderr)
else:
profile = telemetry[worker.worker_key]
elapsed = float(event.get("elapsed_seconds", 0.0) or 0.0)
encode_elapsed = float(event.get("encode_seconds", 0.0) or 0.0)
read_elapsed = float(event.get("read_seconds", 0.0) or 0.0)
write_elapsed = float(event.get("write_seconds", 0.0) or 0.0)
compose_elapsed = float(event.get("compose_seconds", 0.0) or 0.0)
components = int(event.get("components", 0) or 0)
components_written = int(event.get("components_written", 0) or 0)
vectors = int(event.get("vectors", 0) or 0)
composed = int(event.get("composed_written", 0) or 0)
tokens = int(float(event.get("tokens", 0.0) or 0.0))
padded_tokens = int(float(event.get("padded_tokens", 0.0) or 0.0))
attention_tokens = int(float(event.get("attention_tokens", 0.0) or 0.0))
micro_batches = int(float(event.get("micro_batches", 0.0) or 0.0))
page_count = int(event.get("page_count", task.page_count) or task.page_count)
profile.shards += 1
profile.pages += page_count
profile.components += components
profile.components_written += components_written
profile.vectors += vectors
profile.composed_written += composed
profile.elapsed_seconds += elapsed
profile.encode_seconds += encode_elapsed
profile.read_seconds += read_elapsed
profile.write_seconds += write_elapsed
profile.compose_seconds += compose_elapsed
profile.tokens += tokens
profile.padded_tokens += padded_tokens
profile.attention_tokens += attention_tokens
profile.micro_batches += micro_batches
profile.current_batch_size = int(event.get("batch_size", profile.current_batch_size) or profile.current_batch_size)
profile.current_max_seq_length = int(
event.get("max_seq_length", profile.current_max_seq_length) or profile.current_max_seq_length
)
if elapsed > 0.0:
components_per_second = components / elapsed
vectors_per_second = vectors / elapsed
tokens_per_second = tokens / encode_elapsed if encode_elapsed > 0.0 else 0.0
padded_tokens_per_second = padded_tokens / encode_elapsed if encode_elapsed > 0.0 else 0.0
alpha = 0.35
batch_profile = profile.batch_profiles.setdefault(profile.current_batch_size, BatchTelemetry())
batch_profile.shards += 1
batch_profile.components += components
batch_profile.vectors += vectors
batch_profile.elapsed_seconds += elapsed
batch_profile.encode_seconds += encode_elapsed
batch_profile.tokens += tokens
batch_profile.padded_tokens += padded_tokens
batch_profile.attention_tokens += attention_tokens
if batch_profile.ewma_components_per_second <= 0.0:
batch_profile.ewma_components_per_second = components_per_second
batch_profile.ewma_vectors_per_second = vectors_per_second
batch_profile.ewma_tokens_per_second = tokens_per_second
batch_profile.ewma_padded_tokens_per_second = padded_tokens_per_second
else:
batch_profile.ewma_components_per_second = (
(1.0 - alpha) * batch_profile.ewma_components_per_second + alpha * components_per_second
)
batch_profile.ewma_vectors_per_second = (
(1.0 - alpha) * batch_profile.ewma_vectors_per_second + alpha * vectors_per_second
)
if tokens_per_second > 0.0:
batch_profile.ewma_tokens_per_second = (
(1.0 - alpha) * batch_profile.ewma_tokens_per_second + alpha * tokens_per_second
)
if padded_tokens_per_second > 0.0:
batch_profile.ewma_padded_tokens_per_second = (
(1.0 - alpha) * batch_profile.ewma_padded_tokens_per_second
+ alpha * padded_tokens_per_second
)
if profile.ewma_components_per_second <= 0.0:
profile.ewma_components_per_second = components_per_second
profile.ewma_vectors_per_second = vectors_per_second
profile.ewma_tokens_per_second = tokens_per_second
profile.ewma_padded_tokens_per_second = padded_tokens_per_second
else:
profile.ewma_components_per_second = (
(1.0 - alpha) * profile.ewma_components_per_second + alpha * components_per_second
)
profile.ewma_vectors_per_second = (
(1.0 - alpha) * profile.ewma_vectors_per_second + alpha * vectors_per_second
)
if tokens_per_second > 0.0:
profile.ewma_tokens_per_second = (
(1.0 - alpha) * profile.ewma_tokens_per_second + alpha * tokens_per_second
)
if padded_tokens_per_second > 0.0:
profile.ewma_padded_tokens_per_second = (
(1.0 - alpha) * profile.ewma_padded_tokens_per_second + alpha * padded_tokens_per_second
)
if profile.autotune_candidates and profile.locked_batch_size <= 0:
if all(profile.batch_profiles.get(candidate, BatchTelemetry()).shards >= 2 for candidate in profile.autotune_candidates):
profile.locked_batch_size = max(
profile.autotune_candidates,
key=lambda candidate: profile.batch_profiles[candidate].ewma_components_per_second,
)
profile.current_batch_size = profile.locked_batch_size
print(
json.dumps(
{
"event": "gpu_batch_autotune_settled",
"gpu": worker.worker_key,
"physical_gpu": worker.gpu.gpu,
"selected_batch_size": profile.locked_batch_size,
"candidates": {
str(candidate): {
"components_per_second": profile.batch_profiles[candidate].ewma_components_per_second,
"shards": profile.batch_profiles[candidate].shards,
}
for candidate in profile.autotune_candidates
},
},
sort_keys=True,
),
file=sys.stderr,
flush=True,
)
if profile.measured and profile.measured_at == 0.0:
profile.measured_at = time.monotonic()
if all(item.measured for item in telemetry.values()):
if scheduler_stats["settled_at"] == 0.0:
scheduler_stats["settled_at"] = time.monotonic()
scheduler_stats["post_settle_started_at"] = scheduler_stats["settled_at"]
_save_gpu_profile_cache(
scheduler_stats["profile_cache_path"], # type: ignore[arg-type]
str(scheduler_stats["profile_cache_key"]),
telemetry,
)
print(
json.dumps(
{
"event": "gpu_autotune_settled",
"settle_seconds": scheduler_stats["settled_at"] - scheduler_stats["run_started_at"],
"gpus": {
gpu: {
"batch_size": item.current_batch_size,
"components_per_second": item.ewma_components_per_second,
"padded_tokens_per_second": item.ewma_padded_tokens_per_second,
"tokens_per_second": item.ewma_tokens_per_second,
"vectors_per_second": item.ewma_vectors_per_second,
}
for gpu, item in sorted(telemetry.items())
},
},
sort_keys=True,
),
file=sys.stderr,
flush=True,
)
else:
scheduler_stats["post_settle_pages"] += float(page_count)
scheduler_stats["post_settle_components"] += float(components)
scheduler_stats["post_settle_vectors"] += float(vectors)
scheduler_stats["post_settle_composed"] += float(composed)
progress.update(page_count)
measured = sum(1 for item in telemetry.values() if item.measured)
total = len(telemetry)
gpu_summary = " ".join(
f"g{gpu}:{item.ewma_components_per_second:.1f}c/s@b{item.current_batch_size}"
for gpu, item in sorted(telemetry.items())
)
progress.set_postfix_str(
f"{event.get('message', _short_repo_name(task.repo))} measured={measured}/{total} {gpu_summary}"
)
return errors
def _drain_native_worker_events(
native_workers: Sequence[NativeGpuWorker],
pending: "deque[NativePageTask]",
in_flight: dict[NativeGpuWorker, NativePageTask],
telemetry: dict[str, GpuTelemetry],
scheduler_stats: dict[str, float],
progress: tqdm,
*,
errors: int,
) -> int:
for worker in native_workers:
while True:
try:
event = worker.events.get_nowait()
except queue.Empty:
break
errors = _handle_native_worker_event(
native_workers,
worker,
event,
pending,
in_flight,
telemetry,
scheduler_stats,
progress,
errors=errors,
)
return errors
def _wait_for_native_worker_event(
native_workers: Sequence[NativeGpuWorker],
pending: "deque[NativePageTask]",
in_flight: dict[NativeGpuWorker, NativePageTask],
telemetry: dict[str, GpuTelemetry],
scheduler_stats: dict[str, float],
progress: tqdm,
*,
errors: int,
) -> int:
while True:
for worker, task in list(in_flight.items()):
if worker.process is not None and worker.process.poll() is not None:
raise RuntimeError(f"native gpu worker {worker.gpu.gpu} exited with code {worker.process.returncode}")
previous_in_flight = len(in_flight)
errors = _drain_native_worker_events(
native_workers,
pending,
in_flight,
telemetry,
scheduler_stats,
progress,
errors=errors,
)
if len(in_flight) < previous_in_flight:
return errors
time.sleep(0.05)
def _build_embedding_manifest(args: argparse.Namespace) -> str:
_, passage_manifest = make_embedder_with_manifest(
args.model,
device="cpu",
batch_size=args.batch_size,
max_seq_length=args.max_seq_length,
role="passage",
)
ensure_cache_compatible(
args.vector_cache_dir,
passage_manifest,
force_new_cache=args.force_new_cache,
recreate_manifest=args.recreate_manifest,
)
manifest_digest = passage_manifest.digest()
native_runtime_contract = {
"native_attn_implementation": args.native_attn_implementation,
"native_encode_dtype": args.native_encode_dtype,
}
if native_runtime_contract == {
"native_attn_implementation": "default",
"native_encode_dtype": "float32",
}:
return manifest_digest
payload = json.dumps(
{
"base_manifest_digest": manifest_digest,
**native_runtime_contract,
},
sort_keys=True,
)
return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:32]
def _native_helper_path() -> Path:
override = os.environ.get("LOCALIZE_NATIVE_HELPER")
if override:
return Path(override)
return Path(__file__).resolve().parent / "tools" / "native_localizer_helper" / "native_localizer_helper.py"
def _native_page_size(workers: Sequence[NativeGpuWorkerSpec], default_batch_size: int) -> int:
largest_batch = max((worker.batch_size or default_batch_size) for worker in workers)
return max(256, min(2048, largest_batch * 4))
def _gpu_profile_cache_path(args: argparse.Namespace) -> Path:
return args.vector_cache_dir / "gpu-autotune-profiles.json"
def _gpu_profile_cache_key(args: argparse.Namespace, manifest_digest: str) -> str:
workers = args.gpu_worker or [NativeGpuWorkerSpec("0", args.batch_size)]
return json.dumps(
{
"autotune_version": 3,
"manifest_digest": manifest_digest,
"max_seq_length": args.max_seq_length,
"model": args.model,
"native_attn_implementation": args.native_attn_implementation,
"native_encode_dtype": args.native_encode_dtype,
"native_fixed_batches": args.native_fixed_batches,
"native_long_page_gpu": args.native_long_page_gpu,
"native_long_token_threshold": args.native_long_token_threshold,
"native_planner_max_components": args.native_planner_max_components,
"native_planner_target_tokens": args.native_planner_target_tokens,
"native_shard_pages": args.native_shard_pages,
"native_target_attention_tokens": args.native_target_attention_tokens,
"native_target_padded_tokens": args.native_target_padded_tokens,
"workers": [
{
"key": runtime.key,
"gpu": runtime.spec.gpu,
"batch_size": runtime.spec.batch_size or args.batch_size,
"candidates": (
[]
if args.native_fixed_batches
else _batch_autotune_candidates(runtime.spec.batch_size or args.batch_size)
),
}
for runtime in _native_worker_runtimes(workers)
],
},
sort_keys=True,
)
def _load_gpu_profile_cache(path: Path, key: str) -> dict[str, dict[str, float]]:
try:
data = json.loads(path.read_text())
except (FileNotFoundError, json.JSONDecodeError):
return {}
profiles = data.get(key, {})
if not isinstance(profiles, dict):
return {}
loaded: dict[str, dict[str, float]] = {}
for gpu, profile in profiles.items():
if not isinstance(profile, dict):
continue
try:
loaded[str(gpu)] = {
"batch_size": float(profile["batch_size"]),
"components_per_second": float(profile["components_per_second"]),
"padded_tokens_per_second": float(profile.get("padded_tokens_per_second", 0.0)),
"tokens_per_second": float(profile.get("tokens_per_second", 0.0)),
"vectors_per_second": float(profile.get("vectors_per_second", 0.0)),
}
except (KeyError, TypeError, ValueError):
continue
return loaded
def _save_gpu_profile_cache(path: Path, key: str, telemetry: dict[str, GpuTelemetry]) -> None:
try:
data = json.loads(path.read_text())
except (FileNotFoundError, json.JSONDecodeError):
data = {}
data[key] = {
gpu: {
"batch_size": profile.current_batch_size,
"components_per_second": profile.ewma_components_per_second,
"padded_tokens_per_second": profile.ewma_padded_tokens_per_second,
"tokens_per_second": profile.ewma_tokens_per_second,
"vectors_per_second": profile.ewma_vectors_per_second,
}
for gpu, profile in sorted(telemetry.items())
if profile.measured and profile.ewma_components_per_second > 0.0
}
path.parent.mkdir(parents=True, exist_ok=True)
temp_path = path.with_name(f"{path.name}.{os.getpid()}.{uuid.uuid4().hex}.tmp")
temp_path.write_text(json.dumps(data, indent=2, sort_keys=True) + "\n")
temp_path.replace(path)
def _estimated_planner_tokens(text: str, max_seq_length: int) -> int:
return min(max_seq_length, max(1, (len(text) + 2) // 3 + 16))
def _planner_bucket_limits(
page_size: int,
*,
target_tokens: int = 65_536,
max_items: int | None = None,
) -> tuple[int, int]:
if max_items is None:
max_items = min(256, max(1, page_size))
return max(32, int(max_items)), max(1, int(target_tokens))
def _bucket_shard_tasks(
*,
repo: str,
revision: str,
source: str,
next_page: int,
components: dict[str, dict[str, object]],
vectors: list[dict[str, str]],
page_size: int,
planner_target_tokens: int = 65_536,
planner_max_components: int | None = None,
long_token_threshold: int = 0,
long_page_gpus: Sequence[str] = (),
) -> tuple[list[NativePageTask], int]:
if not components:
if not vectors:
return [], next_page
return [
NativePageTask(
repo=repo,
revision=revision,
page=next_page,
page_count=1,
components=[],
vectors=vectors,
work_units=max(1, len(vectors) * 32),
source=source,
)
], next_page + 1
max_items, target_tokens = _planner_bucket_limits(
page_size,
target_tokens=planner_target_tokens,
max_items=planner_max_components,
)
ordered_components = sorted(
components.values(),
key=lambda item: (int(item["estimated_tokens"]), str(item["key"])),
reverse=True,
)
buckets: list[list[dict[str, object]]] = []
current: list[dict[str, object]] = []
current_tokens = 0
for component in ordered_components:
tokens = int(component["estimated_tokens"])
if current and (len(current) >= max_items or current_tokens + tokens > target_tokens):
buckets.append(current)
current = []
current_tokens = 0
current.append(component)
current_tokens += tokens
if current:
buckets.append(current)
if not buckets:
buckets.append([])
key_to_bucket: dict[str, int] = {}
for bucket_index, bucket in enumerate(buckets):
for component in bucket:
key_to_bucket[str(component["key"])] = bucket_index
bucket_vectors: list[list[dict[str, str]]] = [[] for _ in buckets]
for vector in vectors:
referenced = [
key
for key in (vector.get("component_key", ""), vector.get("parent_component_key", ""))
if key in components
]
if referenced:
bucket_index = max(
(key_to_bucket[key] for key in referenced),
key=lambda index: sum(
int(components[key]["estimated_tokens"])
for key in referenced
if key_to_bucket.get(key) == index
),
)
else:
bucket_index = 0
bucket_vectors[bucket_index].append(vector)
tasks: list[NativePageTask] = []
for bucket_index, bucket in enumerate(buckets):
component_keys = {str(component["key"]) for component in bucket}
for vector in bucket_vectors[bucket_index]:
for key in (vector.get("component_key", ""), vector.get("parent_component_key", "")):
if key in components:
component_keys.add(key)
task_components = sorted(
(components[key] for key in component_keys),
key=lambda item: (int(item["estimated_tokens"]), str(item["key"])),
reverse=True,
)
task_vectors = bucket_vectors[bucket_index]
if not task_components and not task_vectors:
continue
work_tokens = sum(int(item["estimated_tokens"]) for item in task_components)
work_units = max(1, work_tokens + len(task_vectors) * 32)
max_estimated_tokens = max((int(item["estimated_tokens"]) for item in task_components), default=0)
preferred_gpus = (
tuple(str(gpu) for gpu in long_page_gpus)
if long_token_threshold > 0 and max_estimated_tokens >= long_token_threshold
else ()
)
tasks.append(
NativePageTask(
repo=repo,
revision=revision,
page=next_page,
page_count=1,
components=task_components,
vectors=task_vectors,
work_units=work_units,
source=source,
preferred_gpus=preferred_gpus,
max_estimated_tokens=max_estimated_tokens,
)
)
next_page += 1
return tasks, next_page
def _repo_page_tasks(
repo: str,
revisions: Sequence[str],
*,
args: argparse.Namespace,
manifest_digest: str,
page_size: int,
source: str = "build",
) -> Iterable[NativePageTask]:
revision_label = revisions[0] if len(revisions) == 1 else "reconcile"
shard_pages = max(1, int(getattr(args, "native_shard_pages", 1) or 1))
next_task_page = 0
shard_count = 0
shard_components: dict[str, dict[str, object]] = {}
shard_vectors: list[dict[str, str]] = []
def flush_shard() -> list[NativePageTask]:
nonlocal next_task_page, shard_count, shard_components, shard_vectors
if shard_count == 0:
return []
tasks, next_task_page = _bucket_shard_tasks(
repo=repo,
revision=revision_label,
source=source,
next_page=next_task_page,
components=shard_components,
vectors=shard_vectors,
page_size=page_size,
planner_target_tokens=args.native_planner_target_tokens,
planner_max_components=args.native_planner_max_components,
long_token_threshold=args.native_long_token_threshold,
long_page_gpus=args.native_long_page_gpu,
)
shard_count = 0
shard_components = {}
shard_vectors = []
return tasks
for page, work in enumerate(
planned_vector_pipeline_pages(
repo,
revisions,
db_dir=args.db_dir,
vector_cache_dir=args.vector_cache_dir,
manifest_digest=manifest_digest,
page_size=page_size,
dedupe_components_across_pages=False,
)
):
for item in work.components:
if item.key not in shard_components:
shard_components[item.key] = {
"key": item.key,
"text": item.text,
"estimated_tokens": _estimated_planner_tokens(item.text, args.max_seq_length),
}
shard_vectors.extend(
{
"vector_key": item.vector_key,
"component_key": item.component_key,
"parent_component_key": item.parent_component_key,
}
for item in work.vectors
)
shard_count += 1
if shard_count < shard_pages:
continue
for task in flush_shard():
yield task
for task in flush_shard():
yield task
def _collect_repo_page_tasks(
repo: str,
revisions: Sequence[str],
*,
args: argparse.Namespace,
manifest_digest: str,
page_size: int,
source: str,
) -> list[NativePageTask]:
return list(
_repo_page_tasks(
repo,
revisions,
args=args,
manifest_digest=manifest_digest,
page_size=page_size,
source=source,
)
)
def _existing_vector_revisions(
repo: str,
*,
grouped: dict[str, list],
args: argparse.Namespace,
) -> tuple[str, list[str]]:
return (
repo,
active_revisions_for_repo_records(
repo,
repo_records_for_args(repo, grouped, args),
db_dir=args.db_dir,
),
)
def _build_vector_index_worker(
task: tuple[str, list[str]],
*,
db_dir: Path,
vector_cache_dir: Path,
manifest_digest: str,
load_workers: int,
) -> dict[str, object]:
repo, revisions = task
db_path = db_dir / repo / "embeddings.db"
built = 0
skipped_empty = 0
try:
conn = sqlite3.connect(db_path, timeout=30)
try:
for revision in revisions:
entries = revision_chunk_index(conn, revision)
if not entries:
skipped_empty += 1
continue
load_revision_vector_matrix(
vector_cache_dir,
repo,
revision,
entries,
manifest_digest=manifest_digest,
workers=load_workers,
)
built += 1
finally:
conn.close()
return {"repo": repo, "built": built, "skipped_empty": skipped_empty, "error": None}
except Exception:
return {
"repo": repo,
"built": built,
"skipped_empty": skipped_empty,
"error": traceback.format_exc(),
}
def _repo_revisions_for_index(
repo: str,
repo_records: Sequence,
*,
db_dir: Path,
) -> tuple[str, list[str]]:
db_path = db_dir / repo / "embeddings.db"
if not db_path.exists():
return repo, []
conn = sqlite3.connect(db_path, timeout=30)
try:
return repo, active_revisions_for_records(conn, repo_records)
finally:
conn.close()
def _augment_chunkless_repo_entry(
repo: str,
*,
args: argparse.Namespace,
) -> dict[str, object]:
try:
return augment_chunkless_repo_worker(
repo,
db_dir=args.db_dir,
clones_dir=args.clones_dir,
seed_dir=args.seed_dir,
seed_only=args.seed_only,
revisions=None,
summary_workers=args.summary_workers,
vector_cache_dirs=args.vector_cache_dir,
model=args.model,
batch_size=args.batch_size,
max_seq_length=args.max_seq_length,
page_size=args.page_size,
dry_run=args.dry_run,
)
except Exception:
return {"repo": repo, "error": traceback.format_exc()}
def run_augment_chunkless(args: argparse.Namespace) -> int:
if args.vector_cache_dir:
helper = reconcile_helper_path()
if not helper.is_file():
raise FileNotFoundError(
f"missing reconcile helper: {helper} (set LOCALIZE_RECONCILE_HELPER to override)"
)
repos = sorted(
path.name
for path in args.db_dir.iterdir()
if path.is_dir() and (path / "embeddings.db").is_file()
)
requested = requested_repo_filter(args)
if requested is not None:
repos = [repo for repo in repos if repo in requested]
if args.limit_repos is not None:
repos = repos[: args.limit_repos]
if not repos:
print(json.dumps({"repos": 0, "chunkless_candidates": 0, "chunkless_inserted": 0}, sort_keys=True))
return 0
progress = tqdm(total=len(repos), desc="augment-chunkless", unit="repo", dynamic_ncols=True)
results: list[dict[str, object]] = []
errors = 0
with concurrent.futures.ProcessPoolExecutor(max_workers=args.repo_workers) as pool:
futures = {
pool.submit(_augment_chunkless_repo_entry, repo, args=args): repo
for repo in repos
}
for future in concurrent.futures.as_completed(futures):
repo = futures[future]
progress.set_postfix_str(repo)
result = future.result()
results.append(result)
if result.get("error"):
errors += 1
print(json.dumps(result, sort_keys=True), file=sys.stderr)
progress.update(1)
progress.close()
repo_revisions = [
(str(result.get("repo", "")), list(result.get("selected_revisions") or []))
for result in results
if result.get("repo") and not result.get("error")
]
vector_caches = []
if not args.dry_run:
vector_caches = _reconcile_augmented_vectors(
repo_revisions,
db_dir=args.db_dir,
vector_cache_dirs=args.vector_cache_dir,
model=args.model,
batch_size=args.batch_size,
max_seq_length=args.max_seq_length,
page_size=args.page_size,
)
for result in results:
result.pop("selected_revisions", None)
summary = {
"repos": len(repos),
"errors": errors,
"dry_run": args.dry_run,
"chunkless_candidates": sum(int(result.get("chunkless_candidates") or 0) for result in results),
"chunkless_inserted": sum(int(result.get("chunkless_inserted") or 0) for result in results),
"chunkless_skipped": sum(int(result.get("chunkless_skipped") or 0) for result in results),
"seeded_rows_used": sum(int(result.get("seeded_rows_used") or 0) for result in results),
"memo_hits": sum(int(result.get("memo_hits") or 0) for result in results),
"bifrost_calls": sum(int(result.get("bifrost_calls") or 0) for result in results),
"vector_caches": vector_caches,
"repos_detail": sorted(results, key=lambda row: str(row.get("repo", ""))),
}
print(json.dumps(summary, sort_keys=True))
return 1 if errors else 0
def run_build_vector_index(args: argparse.Namespace) -> int:
manifest = read_cache_manifest(args.vector_cache_dir)
if manifest is None:
raise RuntimeError(f"no vector cache manifest at {args.vector_cache_dir}")
records = [record for record in read_selection(args.selection) if record.split == args.split]
grouped = group_tasks_by_repo(records)
repos = sorted(grouped)
requested = requested_repo_filter(args)
if requested is not None:
repos = [repo for repo in repos if repo in requested]
if args.limit_repos is not None:
repos = repos[: args.limit_repos]
with concurrent.futures.ThreadPoolExecutor(max_workers=min(32, max(1, args.workers))) as pool:
revision_rows = list(
pool.map(
lambda repo: _repo_revisions_for_index(repo, grouped[repo], db_dir=args.db_dir),
repos,
)
)
tasks = [(repo, revisions) for repo, revisions in revision_rows if revisions]
progress = tqdm(total=len(tasks), desc="build-vector-index", unit="repo", dynamic_ncols=True)
errors = 0
total_built = 0
with concurrent.futures.ProcessPoolExecutor(max_workers=args.workers) as pool:
futures = {
pool.submit(
_build_vector_index_worker,
task,
db_dir=args.db_dir,
vector_cache_dir=args.vector_cache_dir,
manifest_digest=manifest.digest(),
load_workers=args.load_workers,
): task[0]
for task in tasks
}
for future in concurrent.futures.as_completed(futures):
progress.update(1)
result = future.result()
total_built += int(result.get("built") or 0)
if result.get("error"):
errors += 1
print(json.dumps(result, sort_keys=True), file=sys.stderr)
progress.close()
print(
json.dumps(
{
"repos": len(tasks),
"revisions_indexed": total_built,
"errors": errors,
"vector_cache_dir": str(args.vector_cache_dir),
"manifest_digest": manifest.digest(),
},
sort_keys=True,
)
)
return 1 if errors else 0
def run_build_embeddings(args: argparse.Namespace) -> int:
native_helper = _native_helper_path()
if not native_helper.is_file():
raise FileNotFoundError(
f"missing native helper: {native_helper} "
"(set LOCALIZE_NATIVE_HELPER to override)"
)
reconcile_helper = reconcile_helper_path()
if not reconcile_helper.is_file():
raise FileNotFoundError(
f"missing reconcile helper: {reconcile_helper} "
"(set LOCALIZE_RECONCILE_HELPER to override)"
)
manifest_digest = _build_embedding_manifest(args)
records = read_selection(args.selection)
selection_hash = selection_content_hash(records)
grouped = group_tasks_by_repo(records)
all_repos = selected_repos_from_grouped(grouped, args)
planning = tqdm(total=len(all_repos), desc="build clones", unit="repo", dynamic_ncols=True)
if getattr(args, "skip_clone", False):
available_repos, errors = list(all_repos), 0
planning.update(len(all_repos))
else:
available_repos, errors = _clone_repos_for_build(
all_repos,
clones_dir=args.clones_dir,
progress=planning,
clone_workers=args.clone_workers,
debug=args.debug,
)
planning.close()
repo_records, revision_counts = _plan_build_db_repos(
available_repos,
grouped=grouped,
args=args,
)
repos = [repo for repo in available_repos if repo_records.get(repo)]
if not repos:
print(json.dumps({"repos": 0, "revisions": 0}, sort_keys=True))
return 1 if errors else 0
# Memory packing: order so big repos are spread among the cheap small ones (the
# ProcessPool is FIFO, so order == schedule) and gate concurrent bigs so peak RSS
# stays bounded while small repos keep repo_workers busy feeding the GPUs.
big_bytes = max(0, int(getattr(args, "big_repo_mb", 150))) * 1024 * 1024
big_repos: set[str] = set()
if big_bytes > 0:
repos, big_repos = _pack_repos_by_size(
repos, clones_dir=args.clones_dir, big_bytes=big_bytes
)
print(
json.dumps(
{
"event": "repo_packing",
"repos": len(repos),
"big_repos": sorted(big_repos),
"big_repo_mb": args.big_repo_mb,
"max_big_concurrent": args.max_big_concurrent,
},
sort_keys=True,
),
file=sys.stderr,
flush=True,
)
workers = args.gpu_worker or [NativeGpuWorkerSpec("0", args.batch_size)]
runtime_workers = _native_worker_runtimes(workers)
page_size = _native_page_size(workers, args.batch_size)
reconcile_progress = tqdm(total=len(repos), desc="db reconcile", unit="repo", dynamic_ncols=True)
build_db_progress = tqdm(
total=sum(len(repo_records[repo]) for repo in repos),
desc="build db",
unit="task",
dynamic_ncols=True,
)
page_plan_progress = tqdm(
total=sum(revision_counts.get(repo, 0) for repo in repos),
desc="plan pages",
unit="rev",
dynamic_ncols=True,
)
progress = tqdm(total=0, desc="build-embeddings", unit="page", dynamic_ncols=True)
ctx = multiprocessing.get_context("spawn")
manager = multiprocessing.Manager()
progress_queue = manager.Queue()
big_repo_gate = manager.Semaphore(max(1, int(getattr(args, "max_big_concurrent", 1))))
native_workers: list[NativeGpuWorker] = []
futures: dict[concurrent.futures.Future[BuildDbStats], str] = {}
submitted_pages = 0
submitted_existing_pages = 0
completed_repos: set[str] = set()
build_db_seen_tasks: dict[str, int] = {}
next_worker = 0
pending_gpu: deque[NativePageTask] = deque()
in_flight_gpu: dict[NativeGpuWorker, NativePageTask] = {}
profile_cache_path = _gpu_profile_cache_path(args)
profile_cache_key = _gpu_profile_cache_key(args, manifest_digest)
cached_profiles = _load_gpu_profile_cache(profile_cache_path, profile_cache_key)
telemetry: dict[str, GpuTelemetry] = {
runtime.key: GpuTelemetry(
runtime.key,
runtime.spec.batch_size or args.batch_size,
autotune_candidates=(
()
if args.native_fixed_batches
else _batch_autotune_candidates(runtime.spec.batch_size or args.batch_size)
),
)
for runtime in runtime_workers
}
for gpu, cached in cached_profiles.items():
if gpu not in telemetry:
continue
profile = telemetry[gpu]
profile.pages = 3
profile.shards = 3
profile.locked_batch_size = int(cached["batch_size"])
profile.current_batch_size = int(cached["batch_size"])
profile.ewma_components_per_second = float(cached["components_per_second"])
profile.ewma_padded_tokens_per_second = float(cached.get("padded_tokens_per_second", 0.0))
profile.ewma_tokens_per_second = float(cached["tokens_per_second"])
profile.ewma_vectors_per_second = float(cached["vectors_per_second"])
profile.measured_at = time.monotonic()
cache_hit = bool(telemetry) and all(item.measured for item in telemetry.values())
if not cache_hit:
page_size = min(page_size, 256)
scheduler_stats: dict[str, object] = {
"run_started_at": time.monotonic(),
"settled_at": 0.0,
"post_settle_started_at": 0.0,
"post_settle_pages": 0.0,
"post_settle_components": 0.0,
"post_settle_vectors": 0.0,
"post_settle_composed": 0.0,
"profile_cache_key": profile_cache_key,
"profile_cache_path": profile_cache_path,
}
if cache_hit:
scheduler_stats["settled_at"] = scheduler_stats["run_started_at"]
scheduler_stats["post_settle_started_at"] = scheduler_stats["run_started_at"]
print(
json.dumps(
{
"event": "gpu_autotune_cache_hit",
"gpus": sorted(cached_profiles),
"profile_cache_path": str(profile_cache_path),
},
sort_keys=True,
),
file=sys.stderr,
flush=True,
)
try:
with tempfile.TemporaryDirectory() as temp:
temp_dir = Path(temp)
for runtime in runtime_workers:
worker = NativeGpuWorker(
helper=native_helper,
worker_key=runtime.key,
gpu=runtime.spec,
vector_cache_dir=args.vector_cache_dir,
manifest_digest=manifest_digest,
batch_size=args.batch_size,
max_seq_length=args.max_seq_length,
model=args.model,
target_padded_tokens=args.native_target_padded_tokens,
target_attention_tokens=args.native_target_attention_tokens,
encode_dtype=args.native_encode_dtype,
attn_implementation=args.native_attn_implementation,
)
worker.start(temp_dir)
native_workers.append(worker)
gpu_queue_limit = max(1, len(native_workers) * 4)
scanner_workers = max(1, min(len(repos), args.repo_workers))
with (
concurrent.futures.ThreadPoolExecutor(max_workers=scanner_workers) as scanner,
concurrent.futures.ThreadPoolExecutor(max_workers=scanner_workers) as planner,
concurrent.futures.ProcessPoolExecutor(
max_workers=args.repo_workers,
mp_context=ctx,
) as executor,
):
futures_existing = {
scanner.submit(_existing_vector_revisions, repo, grouped=grouped, args=args): repo
for repo in repos
}
page_futures: dict[concurrent.futures.Future[list[NativePageTask]], tuple[str, int]] = {}
for repo in repos:
futures[
executor.submit(
build_db_worker_entry,
repo_records[repo],
clones_dir=args.clones_dir,
db_dir=args.db_dir,
selection_hash=selection_hash,
bifrost_library=args.bifrost_library,
resume=not args.no_resume,
extract_workers=args.extract_workers,
progress_queue=progress_queue,
is_big=repo in big_repos,
big_repo_gate=big_repo_gate,
)
] = repo
while futures_existing or futures or page_futures or pending_gpu or in_flight_gpu:
made_progress = False
if futures_existing:
done_existing, _pending_existing = concurrent.futures.wait(
futures_existing,
timeout=0.0,
return_when=concurrent.futures.FIRST_COMPLETED,
)
for future in done_existing:
futures_existing.pop(future)
repo, revisions = future.result()
made_progress = True
reconcile_progress.update(1)
if revisions:
page_futures[
planner.submit(
_collect_repo_page_tasks,
repo,
revisions,
args=args,
manifest_digest=manifest_digest,
page_size=page_size,
source="existing",
)
] = (f"{_short_repo_name(repo)} existing", len(revisions))
reconcile_progress.set_postfix_str(f"{_short_repo_name(repo)} planned existing")
else:
reconcile_progress.set_postfix_str(f"{_short_repo_name(repo)} no existing")
while True:
try:
event = progress_queue.get_nowait()
except Exception:
break
made_progress = True
if isinstance(event, dict) and event.get("event") == "revision":
repo = str(event["repo"])
revision = str(event["revision"])
page_futures[
planner.submit(
_collect_repo_page_tasks,
repo,
[revision],
args=args,
manifest_digest=manifest_digest,
page_size=page_size,
source="build",
)
] = (f"{_short_repo_name(repo)} {revision[:12]}", 1)
progress.set_postfix_str(f"{_short_repo_name(repo)} queued {revision[:12]}")
elif isinstance(event, dict) and event.get("event") == "log":
repo = str(event.get("repo", ""))
message = str(event.get("message", ""))
task_progress = _extract_task_progress(message)
if task_progress is not None and repo:
current, total_tasks = task_progress
previous = build_db_seen_tasks.get(repo, 0)
if current > previous:
build_db_progress.update(current - previous)
build_db_seen_tasks[repo] = current
build_db_progress.set_postfix_str(
f"{_short_repo_name(repo)} {current}/{total_tasks}"
)
if page_futures:
done_pages, _pending_pages = concurrent.futures.wait(
page_futures,
timeout=0.0,
return_when=concurrent.futures.FIRST_COMPLETED,
)
else:
done_pages = set()
for future in done_pages:
label, planned_revisions = page_futures.pop(future)
tasks = future.result()
pending_gpu.extend(tasks)
made_progress = True
page_plan_progress.update(planned_revisions)
if tasks:
page_plan_progress.set_postfix_str(f"{label} planned {len(tasks)} shards")
progress.set_postfix_str(f"{label} planned {len(tasks)} shards")
submitted, submitted_existing, next_worker = _submit_native_pages(
native_workers,
pending_gpu,
in_flight_gpu,
next_worker,
telemetry,
)
submitted_pages += submitted
submitted_existing_pages += submitted_existing
if submitted:
made_progress = True
errors = _drain_native_worker_events(
native_workers,
pending_gpu,
in_flight_gpu,
telemetry,
scheduler_stats,
progress,
errors=errors,
)
if futures:
done, _pending = concurrent.futures.wait(
futures,
timeout=0.0,
return_when=concurrent.futures.FIRST_COMPLETED,
)
else:
done = set()
for future in done:
repo = futures.pop(future)
stats = future.result()
completed_repos.add(repo)
made_progress = True
repo_total_tasks = len(repo_records.get(repo, ()))
previous = build_db_seen_tasks.get(repo, 0)
if repo_total_tasks > previous:
build_db_progress.update(repo_total_tasks - previous)
build_db_seen_tasks[repo] = repo_total_tasks
if stats.error is not None:
errors += 1
if args.debug:
print(json.dumps({"repo": repo, "error": stats.error}, sort_keys=True), file=sys.stderr)
else:
print(f"error: {_short_repo_name(repo)} build failed: {stats.error}", file=sys.stderr)
if len(pending_gpu) + len(in_flight_gpu) >= gpu_queue_limit and in_flight_gpu:
errors = _wait_for_native_worker_event(
native_workers,
pending_gpu,
in_flight_gpu,
telemetry,
scheduler_stats,
progress,
errors=errors,
)
made_progress = True
elif not made_progress:
if in_flight_gpu:
errors = _wait_for_native_worker_event(
native_workers,
pending_gpu,
in_flight_gpu,
telemetry,
scheduler_stats,
progress,
errors=errors,
)
else:
time.sleep(0.1)
while page_futures or pending_gpu or in_flight_gpu:
if page_futures:
done_pages, _pending_pages = concurrent.futures.wait(
page_futures,
timeout=0.1,
return_when=concurrent.futures.FIRST_COMPLETED,
)
else:
done_pages = set()
for future in done_pages:
_label, planned_revisions = page_futures.pop(future)
page_plan_progress.update(planned_revisions)
pending_gpu.extend(future.result())
submitted, submitted_existing, next_worker = _submit_native_pages(
native_workers,
pending_gpu,
in_flight_gpu,
next_worker,
telemetry,
)
submitted_pages += submitted
submitted_existing_pages += submitted_existing
if in_flight_gpu:
errors = _wait_for_native_worker_event(
native_workers,
pending_gpu,
in_flight_gpu,
telemetry,
scheduler_stats,
progress,
errors=errors,
)
finally:
for worker in native_workers:
code = worker.shutdown()
if code != 0:
errors += 1
print(f"error: native gpu worker {worker.gpu.gpu} exited with code {code}", file=sys.stderr)
reconcile_progress.close()
build_db_progress.close()
page_plan_progress.close()
progress.close()
manager.shutdown()
print(
json.dumps(
{
"gpu_autotune_settle_seconds": (
scheduler_stats["settled_at"] - scheduler_stats["run_started_at"]
if scheduler_stats["settled_at"]
else None
),
"gpu_profiles": {
gpu: {
"batch_size": profile.current_batch_size,
"batch_autotune_candidates": profile.autotune_candidates,
"batch_autotune_profiles": {
str(batch_size): {
"components_per_second": batch_profile.ewma_components_per_second,
"elapsed_seconds": batch_profile.elapsed_seconds,
"padded_tokens_per_second": batch_profile.ewma_padded_tokens_per_second,
"shards": batch_profile.shards,
}
for batch_size, batch_profile in sorted(profile.batch_profiles.items())
},
"components": profile.components,
"components_written": profile.components_written,
"components_per_second": profile.ewma_components_per_second,
"component_duplicate_ratio": profile.components / max(1, profile.components_written),
"composed_written": profile.composed_written,
"actual_composed_vectors_per_second": profile.composed_written
/ max(0.001, profile.elapsed_seconds),
"encode_seconds": profile.encode_seconds,
"encode_fraction": profile.encode_seconds / max(0.001, profile.elapsed_seconds),
"elapsed_seconds": profile.elapsed_seconds,
"io_fraction": (profile.read_seconds + profile.write_seconds)
/ max(0.001, profile.elapsed_seconds),
"measured": profile.measured,
"micro_batches": profile.micro_batches,
"pages": profile.pages,
"padded_tokens": profile.padded_tokens,
"padding_waste_ratio": profile.padded_tokens / max(1, profile.tokens),
"attention_tokens": profile.attention_tokens,
"read_seconds": profile.read_seconds,
"write_seconds": profile.write_seconds,
"compose_seconds": profile.compose_seconds,
"shards": profile.shards,
"tokens": profile.tokens,
"padded_tokens_per_second": profile.ewma_padded_tokens_per_second,
"tokens_per_second": profile.ewma_tokens_per_second,
"vectors": profile.vectors,
"vectors_per_second": profile.ewma_vectors_per_second,
}
for gpu, profile in sorted(telemetry.items())
},
"post_settle_components_per_second": (
scheduler_stats["post_settle_components"]
/ max(0.001, time.monotonic() - scheduler_stats["post_settle_started_at"])
if scheduler_stats["post_settle_started_at"]
else None
),
"post_settle_pages": int(scheduler_stats["post_settle_pages"]),
"post_settle_vectors_per_second": (
scheduler_stats["post_settle_vectors"]
/ max(0.001, time.monotonic() - scheduler_stats["post_settle_started_at"])
if scheduler_stats["post_settle_started_at"]
else None
),
"post_settle_composed_vectors_per_second": (
scheduler_stats["post_settle_composed"]
/ max(0.001, time.monotonic() - scheduler_stats["post_settle_started_at"])
if scheduler_stats["post_settle_started_at"]
else None
),
"repos": len(completed_repos),
"existing_pages_submitted": submitted_existing_pages,
"page_size": page_size,
"native_shard_pages": args.native_shard_pages,
"pages_submitted": submitted_pages,
},
sort_keys=True,
)
)
return 1 if errors else 0
class _DefaultsHelpFormatter(argparse.ArgumentDefaultsHelpFormatter):
"""Show each option's default in --help, including options with no help= text.
ArgumentDefaultsHelpFormatter only appends "(default: ...)" to options that already have a help
string, and argparse hides the help column entirely when an option has none. Almost none of our
options set help=, so we give those a "(default: %(default)s)" template before formatting; the
"%(default)" token also stops the base formatter from double-appending.
"""
def _format_action(self, action: argparse.Action) -> str:
if (
not action.help
and action.option_strings
and action.default is not argparse.SUPPRESS
and action.dest != "help"
):
action.help = "(default: %(default)s)"
return super()._format_action(action)
class _DefaultsParser(argparse.ArgumentParser):
"""ArgumentParser that shows each option's default in --help.
Used for the top-level parser; argparse propagates this class to every subparser created via
add_subparsers (parser_class defaults to type(self)), so all subcommands inherit it.
"""
def __init__(self, *args: object, **kwargs: object) -> None:
kwargs.setdefault("formatter_class", _DefaultsHelpFormatter)
super().__init__(*args, **kwargs)
def make_arg_parser() -> argparse.ArgumentParser:
parser = _DefaultsParser(description="Build SFT code-localization datasets and embeddings")
parser.add_argument("--commits-root", type=Path, default=DEFAULT_COMMITS_ROOT)
parser.add_argument("--tasks-dir", type=Path, default=DEFAULT_TASKS_DIR)
parser.add_argument("--clones-dir", type=Path, default=DEFAULT_CLONES_DIR)
parser.add_argument("--embeddings-dir", type=Path, default=DEFAULT_EMBEDDINGS_DIR)
parser.add_argument("--debug", action="store_true")
subparsers = parser.add_subparsers(dest="command", required=True)
def add_repo_filters(command: argparse.ArgumentParser) -> None:
command.add_argument("--repo", action="append", dest="repos")
command.add_argument("--repo-file", type=Path)
command.add_argument("--limit-repos", type=int)
def add_debug_flag(command: argparse.ArgumentParser) -> None:
command.add_argument("--debug", action="store_true")
doctor = subparsers.add_parser("doctor", help="Check local dependencies and CUDA readiness")
add_debug_flag(doctor)
doctor.add_argument("--require-gpu", action="store_true")
select = subparsers.add_parser("select-tasks", help="Select up to 1000 primary tasks per language")
add_debug_flag(select)
select.add_argument("--language", action="append", dest="languages")
select.add_argument("--limit-per-language", type=int, default=DEFAULT_TASK_LIMIT_PER_LANGUAGE)
select.add_argument("--limit-per-repo", type=int, default=DEFAULT_TASK_LIMIT_PER_REPO)
select.add_argument("--output", type=Path, default=DEFAULT_EMBEDDINGS_DIR / "selection.jsonl")
init_db = subparsers.add_parser("init-db", help="Create empty per-repo SQLite databases for selected tasks")
add_debug_flag(init_db)
init_db.add_argument("--selection", type=Path, default=DEFAULT_EMBEDDINGS_DIR / "selection.jsonl")
build = subparsers.add_parser("build-embeddings", help="Build per-repo DBs and vectors with native GPU workers")
add_debug_flag(build)
build.add_argument("--selection", type=Path, default=DEFAULT_EMBEDDINGS_DIR / "selection.jsonl")
build.add_argument("--db-dir", type=Path, required=True)
build.add_argument("--vector-cache-dir", type=Path, required=True)
add_repo_filters(build)
build.add_argument("--max-tasks-per-repo", type=int)
build.add_argument(
"--clone-workers",
type=int,
default=4,
help="Parallel git-clone workers for recovering missing repo clones on demand",
)
build.add_argument(
"--skip-clone",
action="store_true",
help=(
"Skip clone recovery and treat every selected repo as available. Safe when the "
"DBs are already complete for the selection (vector-only builds, e.g. embedding "
"an existing corpus with a new model on a machine without clones)."
),
)
build.add_argument(
"--extract-workers",
type=int,
default=DEFAULT_EXTRACT_WORKERS,
help="Parallel Bifrost extraction clients per repo revision",
)
build.add_argument("--repo-workers", type=int, default=max(1, os.cpu_count() or 1))
build.add_argument(
"--big-repo-mb",
type=int,
default=150,
help=(
"Repos whose checked-out source (excl. .git) is >= this many MB are treated "
"as memory-heavy 'big' repos: spread apart in the schedule and gated so at "
"most --max-big-concurrent run at once (prevents the multi-giant OOM-stall)."
),
)
build.add_argument(
"--max-big-concurrent",
type=int,
default=1,
help="Max big repos extracting concurrently (Semaphore over the build-db pool).",
)
build.add_argument("--no-resume", action="store_true")
build.add_argument("--gpu-worker", action="append", type=parse_native_gpu_worker, default=[])
build.add_argument("--model", default=GRANITE_MODEL)
build.add_argument("--batch-size", type=int, default=16)
build.add_argument("--max-seq-length", type=int, default=MAX_SEQ_LENGTH)
build.add_argument("--bifrost-library", type=Path)
build.add_argument("--start-base-revision")
build.add_argument("--end-base-revision")
build.add_argument("--force-new-cache", action="store_true")
build.add_argument("--recreate-manifest", action="store_true")
build.add_argument(
"--native-shard-pages",
type=int,
default=2,
help="Logical vector-planning pages coalesced into each native GPU task",
)
build.add_argument(
"--native-fixed-batches",
action="store_true",
help="Use configured GPU worker batch sizes directly instead of autotuning",
)
build.add_argument(
"--native-long-token-threshold",
type=int,
default=0,
help="Route tasks with a component at or above this estimated token length to preferred GPUs",
)
build.add_argument(
"--native-long-page-gpu",
action="append",
default=[],
help="Physical GPU id allowed to handle long-token tasks; repeat for multiple GPUs",
)
build.add_argument(
"--native-planner-target-tokens",
type=int,
default=65_536,
help="Scheduler-side estimated-token target per native GPU task",
)
build.add_argument(
"--native-planner-max-components",
type=int,
default=256,
help="Scheduler-side max components per native GPU task bucket",
)
build.add_argument(
"--native-target-padded-tokens",
type=int,
default=65_536,
help="Native helper microbatch budget for batch_len * max_estimated_tokens",
)
build.add_argument(
"--native-target-attention-tokens",
type=int,
default=268_435_456,
help="Native helper microbatch budget for batch_len * max_estimated_tokens^2",
)
build.add_argument(
"--native-encode-dtype",
choices=("float32", "float16", "bfloat16"),
default="float32",
help="Experimental native helper inference dtype",
)
build.add_argument(
"--native-attn-implementation",
choices=("default", "eager", "sdpa", "flash_attention_2"),
default="default",
help="Experimental native helper attention implementation passed to Transformers",
)
build_index = subparsers.add_parser(
"build-vector-index",
help="Pack cached per-vector files into manifest-scoped per-revision matrices",
)
add_debug_flag(build_index)
build_index.add_argument("--selection", type=Path, default=DEFAULT_EMBEDDINGS_DIR / "selection.jsonl")
build_index.add_argument("--db-dir", type=Path, required=True)
build_index.add_argument("--vector-cache-dir", type=Path, required=True)
build_index.add_argument("--split", default="train")
add_repo_filters(build_index)
build_index.add_argument("--workers", type=int, default=max(1, min(32, os.cpu_count() or 1)))
build_index.add_argument("--load-workers", type=int, default=max(1, min(16, os.cpu_count() or 1)))
refresh = subparsers.add_parser("refresh-positives", help="Recompute task positives from existing indexed chunks")
add_debug_flag(refresh)
refresh.add_argument("--selection", type=Path, default=DEFAULT_EMBEDDINGS_DIR / "selection.jsonl")
add_repo_filters(refresh)
refresh.add_argument("--repo-workers", type=int, default=4)
refresh.add_argument("--task-workers", type=int, default=max(1, min(32, os.cpu_count() or 1)))
augment = subparsers.add_parser(
"augment-chunkless",
help="Add synthetic file-summary rows for in-scope files that produced zero function chunks",
)
add_debug_flag(augment)
add_repo_filters(augment)
augment.add_argument("--db-dir", type=Path, required=True)
augment.add_argument(
"--vector-cache-dir",
action="append",
type=Path,
default=[],
help=(
"Existing passage vector cache to reconcile once after all repo workers finish; "
"repeat for multiple caches."
),
)
augment.add_argument(
"--seed-dir",
type=Path,
help="Optional per-repo synthetic_rows.jsonl directory used to seed exact chunkless summary text.",
)
augment.add_argument(
"--seed-only",
action="store_true",
help=(
"Process only revisions covered by --seed-dir and insert only seeded texts with zero "
"Bifrost calls. This still writes augment_chunkless:<revision> done markers for those "
"revisions, so a later full pass will skip them unless you clear the metadata markers."
),
)
augment.add_argument(
"--repo-workers",
type=int,
default=8,
help="CPU repo workers for snapshot scanning and DB writes; vector reconcile runs once at the end.",
)
augment.add_argument(
"--summary-workers",
type=int,
default=DEFAULT_EXTRACT_WORKERS,
help="Parallel summary threads within each repo revision.",
)
augment.add_argument("--page-size", type=int, default=1024)
augment.add_argument("--dry-run", action="store_true")
augment.add_argument("--model", default=GRANITE_MODEL)
augment.add_argument("--batch-size", type=int, default=16)
augment.add_argument("--max-seq-length", type=int, default=MAX_SEQ_LENGTH)
prune_chunks = subparsers.add_parser("prune-orphan-chunks", help="Delete chunks not referenced by any revision")
add_debug_flag(prune_chunks)
prune_chunks.add_argument("--selection", type=Path, default=DEFAULT_EMBEDDINGS_DIR / "selection.jsonl")
add_repo_filters(prune_chunks)
evaluate = subparsers.add_parser("eval", help="Evaluate a model on the selected test split")
add_debug_flag(evaluate)
evaluate.add_argument("--selection", type=Path, required=True)
evaluate.add_argument("--db-dir", type=Path, required=True)
evaluate.add_argument("--vector-cache-dir", type=Path, required=True)
evaluate.add_argument("--split", default="test")
evaluate.add_argument("--gpu-worker", type=parse_single_gpu_worker)
evaluate.add_argument("--cuda-visible-devices", help=argparse.SUPPRESS)
evaluate.add_argument("--model", default=GRANITE_MODEL)
evaluate.add_argument("--batch-size", type=int, default=16)
evaluate.add_argument("--max-seq-length", type=int, default=MAX_SEQ_LENGTH)
evaluate.add_argument("--skip-missing-vectors", action="store_true")
evaluate.add_argument(
"--score-report-top-k",
type=int,
default=10,
help="Include file-score diagnostics for the top K files in eval reports; use 0 to disable.",
)
evaluate.add_argument("--output", type=Path, default=DEFAULT_EMBEDDINGS_DIR / "baseline-eval.json")
evaluate.add_argument("--allow-selection-mismatch", action="store_true")
compare = subparsers.add_parser(
"compare-evals", help="Paired flip / bootstrap comparison of base vs trained eval reports"
)
add_debug_flag(compare)
compare.add_argument("--base", type=Path, required=True)
compare.add_argument("--trained", type=Path, required=True)
compare.add_argument("-k", type=int, default=10)
compare.add_argument("--bootstrap-iterations", type=int, default=1000)
compare.add_argument("--seed", type=int, default=0)
compare.add_argument("--allow-selection-mismatch", action="store_true")
mine_ready = subparsers.add_parser("mine-ready-negatives", help="Mine negatives for tasks whose full candidate set is vectorized")
add_debug_flag(mine_ready)
mine_ready.add_argument("--selection", type=Path, required=True)
mine_ready.add_argument("--db-dir", type=Path, required=True)
mine_ready.add_argument("--vector-cache-dir", type=Path, required=True)
mine_ready.add_argument("--split", default="train")
mine_ready.add_argument("--output", type=Path, default=DEFAULT_EMBEDDINGS_DIR / "hard-negatives-ready.jsonl")
mine_ready.add_argument("--gpu-worker", type=parse_single_gpu_worker)
mine_ready.add_argument("--cuda-visible-devices", help=argparse.SUPPRESS)
mine_ready.add_argument("--model", default=GRANITE_MODEL)
mine_ready.add_argument("--batch-size", type=int, default=256)
mine_ready.add_argument("--max-seq-length", type=int, default=MAX_SEQ_LENGTH)
mine_ready.add_argument("--max-tasks", type=int)
mine_ready.add_argument(
"--shard-repo-workers",
type=int,
default=4,
help="Parallel repo workers within the current shard; GPU embedding stays serialized per process.",
)
mine_ready.add_argument("--scan-top-k", type=int, default=DEFAULT_SCAN_TOP_K)
mine_ready.add_argument("--hard-negatives", type=int, default=HARD_NEGATIVES)
mine_ready.add_argument(
"--existing-negative-file",
action="append",
type=Path,
default=[],
help="Additional mined-negative files whose rows should be treated as already complete.",
)
mine_ready.add_argument(
"--repo-shard",
type=parse_repo_shard,
help="Mine only repos whose stable hash maps to INDEX/COUNT.",
)
mine_ready.add_argument("--allow-selection-mismatch", action="store_true")
export_train = subparsers.add_parser("export-train", help="Export training rows with positives and mined negatives")
add_debug_flag(export_train)
export_train.add_argument("--selection", type=Path, required=True)
export_train.add_argument("--db-dir", type=Path, required=True)
export_train.add_argument("--split", default="train")
export_train.add_argument("--negative-file", action="append", type=Path, default=[])
export_train.add_argument("--output", type=Path, default=DEFAULT_EMBEDDINGS_DIR / "train-pairs.jsonl")
export_train.add_argument("--negatives-per-row", type=int, default=DEFAULT_NEGATIVES_PER_ROW)
export_train.add_argument(
"--repo-workers",
type=int,
default=1,
help="Export repos in parallel into shard files, then concatenate.",
)
export_train.add_argument(
"--max-positives-per-task",
type=int,
default=0,
help="Cap row-local positive rows per task after deterministic ordering; 0 means no cap.",
)
export_train.add_argument("--allow-selection-mismatch", action="store_true")
return parser
def main(argv: Sequence[str] | None = None) -> int:
parser = make_arg_parser()
args = parser.parse_args(argv)
if args.command == "doctor":
return print_doctor(doctor_checks(require_gpu=args.require_gpu))
if args.command == "select-tasks":
records = select_tasks(
args.commits_root,
args.tasks_dir,
languages=args.languages,
limit_per_language=args.limit_per_language,
limit_per_repo=args.limit_per_repo,
show_progress=True,
)
canonical_path, sidecar_path, sidecar = write_selection_artifacts(records, args.output)
print(
f"wrote {len(records)} task records to {canonical_path} "
f"(legacy updated at {args.output}; sidecar {sidecar_path}; selection_hash={sidecar['selection_hash']['short12']})",
file=sys.stderr,
)
return 0
if args.command == "init-db":
records = read_selection(args.selection)
selection_hash = selection_content_hash(records)
for repo in sorted({record.repo for record in records}):
conn = init_embeddings_db(args.embeddings_dir / repo / "embeddings.db")
set_selection_hash_metadata(conn, selection_hash)
conn.close()
return 0
if args.command == "build-embeddings":
if args.extract_workers < 1:
parser.error("--extract-workers must be >= 1")
if args.repo_workers < 1:
parser.error("--repo-workers must be >= 1")
if args.native_shard_pages < 1:
parser.error("--native-shard-pages must be >= 1")
if args.native_long_token_threshold < 0:
parser.error("--native-long-token-threshold must be >= 0")
if args.native_long_page_gpu and args.native_long_token_threshold == 0:
parser.error("--native-long-page-gpu requires --native-long-token-threshold")
if args.native_long_token_threshold > 0:
if not args.native_long_page_gpu:
parser.error("--native-long-token-threshold requires at least one --native-long-page-gpu")
worker_gpus = {worker.gpu for worker in (args.gpu_worker or [NativeGpuWorkerSpec("0", args.batch_size)])}
unknown_long_gpus = sorted(set(args.native_long_page_gpu) - worker_gpus)
if unknown_long_gpus:
parser.error(
"--native-long-page-gpu must refer to configured --gpu-worker physical GPUs: "
+ ", ".join(unknown_long_gpus)
)
if args.native_planner_target_tokens < 1:
parser.error("--native-planner-target-tokens must be >= 1")
if args.native_planner_max_components < 1:
parser.error("--native-planner-max-components must be >= 1")
if args.native_target_padded_tokens < 1:
parser.error("--native-target-padded-tokens must be >= 1")
if args.native_target_attention_tokens < 1:
parser.error("--native-target-attention-tokens must be >= 1")
return run_build_embeddings(args)
if args.command == "augment-chunkless":
if args.repo_workers < 1:
parser.error("--repo-workers must be >= 1")
if args.summary_workers < 1:
parser.error("--summary-workers must be >= 1")
if args.page_size < 1:
parser.error("--page-size must be >= 1")
if not args.dry_run and not args.vector_cache_dir:
parser.error("--vector-cache-dir is required unless --dry-run is set")
return run_augment_chunkless(args)
if args.command == "build-vector-index":
if args.workers < 1:
parser.error("--workers must be >= 1")
if args.load_workers < 1:
parser.error("--load-workers must be >= 1")
return run_build_vector_index(args)
if args.command == "refresh-positives":
if args.repo_workers < 1:
parser.error("--repo-workers must be >= 1")
if args.task_workers < 1:
parser.error("--task-workers must be >= 1")
records = read_selection(args.selection)
grouped = group_tasks_by_repo(records)
repos = sorted(grouped)
requested = requested_repo_filter(args)
if requested is not None:
repos = [repo for repo in repos if repo in requested]
if args.limit_repos is not None:
repos = repos[: args.limit_repos]
errors = 0
stats_rows = []
workers = min(args.repo_workers, len(repos)) if repos else 1
progress = tqdm(total=len(repos), desc="refresh-positives", unit="repo", dynamic_ncols=True)
with concurrent.futures.ProcessPoolExecutor(max_workers=workers) as pool:
futures = {
pool.submit(
refresh_repo_positives_worker,
grouped[repo],
args.clones_dir,
args.embeddings_dir,
args.task_workers,
): repo
for repo in repos
}
for future in concurrent.futures.as_completed(futures):
progress.update(1)
stats_rows.append(future.result())
progress.close()
for stats in sorted(stats_rows, key=lambda item: item.repo):
if stats.error is not None:
errors += 1
print(
json.dumps(
{
"repo": stats.repo,
"tasks": stats.tasks,
"refreshed": stats.refreshed,
"positives": stats.positives,
"skipped_missing_task": stats.skipped_missing_task,
"skipped_missing_chunks": stats.skipped_missing_chunks,
"error": stats.error,
},
sort_keys=True,
),
file=sys.stderr,
)
return 1 if errors else 0
if args.command == "prune-orphan-chunks":
records = read_selection(args.selection)
repos = sorted(group_tasks_by_repo(records))
requested = requested_repo_filter(args)
if requested is not None:
repos = [repo for repo in repos if repo in requested]
if args.limit_repos is not None:
repos = repos[: args.limit_repos]
total_deleted = 0
for repo in repos:
deleted = prune_orphan_chunks_for_repo(repo, embeddings_dir=args.embeddings_dir)
total_deleted += deleted
print(json.dumps({"repo": repo, "deleted": deleted}, sort_keys=True), file=sys.stderr)
print(json.dumps({"deleted": total_deleted}, sort_keys=True))
return 0
if args.command == "eval":
records = read_selection(args.selection)
selection_hash = verify_selection_hash_against_dbs(
records,
db_dir=args.db_dir,
allow_selection_mismatch=args.allow_selection_mismatch,
warning_printer=_warn_stderr,
)
if args.gpu_worker and args.cuda_visible_devices:
parser.error("--gpu-worker cannot be combined with --cuda-visible-devices")
batch_size = (
args.gpu_worker.batch_size
if args.gpu_worker is not None and args.gpu_worker.batch_size is not None
else args.batch_size
)
configure_cuda_visibility(
args.gpu_worker.gpu if args.gpu_worker is not None else None,
args.cuda_visible_devices,
)
embedder, query_manifest = make_embedder_with_manifest(
args.model,
device="cuda:0",
batch_size=batch_size,
max_seq_length=args.max_seq_length,
role="query",
)
assert_query_side_compatible(args.vector_cache_dir, query_manifest)
evaluations, metrics = evaluate_records(
records,
db_dir=args.db_dir,
vector_cache_dir=args.vector_cache_dir,
embed_texts=embedder,
manifest_digest=query_manifest.digest(),
split=args.split,
skip_missing_vectors=args.skip_missing_vectors,
score_report_top_k=args.score_report_top_k,
incremental_path=args.output.with_suffix(".partial.jsonl"),
)
write_eval_report(args.output, evaluations, metrics, selection_hash=selection_hash)
print(
json.dumps(
{
"selection_hash": selection_hash,
"total": metrics.total,
"all_positive_acc": metrics.all_positive_acc,
"any_positive_acc": metrics.any_positive_acc,
"mrr": metrics.mrr,
"output": str(args.output),
},
sort_keys=True,
)
)
return 0
if args.command == "compare-evals":
report = compare_eval_reports(
args.base,
args.trained,
k=args.k,
iterations=args.bootstrap_iterations,
seed=args.seed,
allow_selection_mismatch=args.allow_selection_mismatch,
)
print(json.dumps(report, indent=2, sort_keys=True))
return 0
if args.command == "mine-ready-negatives":
records = filter_records_by_repo_shard(read_selection(args.selection), args.repo_shard)
selection_hash = verify_selection_hash_against_dbs(
records,
db_dir=args.db_dir,
allow_selection_mismatch=args.allow_selection_mismatch,
warning_printer=_warn_stderr,
)
if args.shard_repo_workers < 1:
parser.error("--shard-repo-workers must be >= 1")
if args.gpu_worker and args.cuda_visible_devices:
parser.error("--gpu-worker cannot be combined with --cuda-visible-devices")
batch_size = (
args.gpu_worker.batch_size
if args.gpu_worker is not None and args.gpu_worker.batch_size is not None
else args.batch_size
)
configure_cuda_visibility(
args.gpu_worker.gpu if args.gpu_worker is not None else None,
args.cuda_visible_devices,
)
embedder, query_manifest = make_embedder_with_manifest(
args.model,
device="cuda:0",
batch_size=batch_size,
max_seq_length=args.max_seq_length,
role="query",
)
assert_query_side_compatible(args.vector_cache_dir, query_manifest)
total_tasks = sum(1 for record in records if record.split == args.split)
progress = tqdm(total=total_tasks, desc="mine-ready-negatives", unit="task", dynamic_ncols=True)
last_ready = 0
progress_lock = threading.Lock()
def on_progress(event: dict[str, object]) -> None:
nonlocal last_ready
with progress_lock:
if event.get("event") == "mine_progress":
ready = int(event.get("ready", 0))
if ready > last_ready:
progress.update(ready - last_ready)
last_ready = ready
repo = str(event.get("repo", ""))
revision = str(event.get("revision", ""))[:12]
stage = str(event.get("stage", ""))
written = int(event.get("written", 0))
if revision:
progress.set_postfix_str(f"{repo} {stage} {revision} written={written}")
else:
progress.set_postfix_str(f"{repo} {stage} written={written}")
elif event.get("event") == "mine_repo_complete":
print(
json.dumps(
{
"repo": str(event["repo"]),
"considered": int(event["considered"]),
"ready": int(event["ready"]),
"written": int(event["written"]),
"revisions_processed": int(event["revisions_processed"]),
"prompt_read_seconds": round(float(event["prompt_read_seconds"]), 2),
"query_embed_seconds": round(float(event["query_embed_seconds"]), 2),
"matrix_load_seconds": round(float(event["matrix_load_seconds"]), 2),
"gpu_score_seconds": round(float(event["gpu_score_seconds"]), 2),
"negative_write_seconds": round(float(event["negative_write_seconds"]), 2),
},
sort_keys=True,
),
file=sys.stderr,
)
elif event.get("event") == "mine_repo_error":
print(
json.dumps(
{
"repo": str(event["repo"]),
"error": str(event["error"]),
},
sort_keys=True,
),
file=sys.stderr,
)
stats = mine_ready_negatives(
records,
db_dir=args.db_dir,
vector_cache_dir=args.vector_cache_dir,
embed_texts=embedder,
manifest_digest=query_manifest.digest(),
output=args.output,
split=args.split,
max_tasks=args.max_tasks,
scan_top_k=args.scan_top_k,
hard_negative_count=args.hard_negatives,
existing_negative_files=args.existing_negative_file,
selection_hash=selection_hash,
progress=on_progress,
shard_repo_workers=args.shard_repo_workers,
)
if stats.ready > last_ready:
progress.update(stats.ready - last_ready)
progress.close()
print(
json.dumps(
{
"output": str(args.output),
"selection_hash": selection_hash,
"considered": stats.considered,
"ready": stats.ready,
"written": stats.written,
"skipped_existing": stats.skipped_existing,
"skipped_no_positive": stats.skipped_no_positive,
"skipped_incomplete_vectors": stats.skipped_incomplete_vectors,
"prompt_read_seconds": round(stats.prompt_read_seconds, 2),
"query_embed_seconds": round(stats.query_embed_seconds, 2),
"matrix_load_seconds": round(stats.matrix_load_seconds, 2),
"gpu_score_seconds": round(stats.gpu_score_seconds, 2),
"negative_write_seconds": round(stats.negative_write_seconds, 2),
"repaired_trailing_lines": stats.repaired_trailing_lines,
"errors": len(stats.repo_errors),
"repo_errors": [
{"repo": repo, "error": error}
for repo, error in stats.repo_errors
],
"unique_eligible_negative_files_p10": stats.unique_eligible_negative_files_p10,
"unique_eligible_negative_files_p50": stats.unique_eligible_negative_files_p50,
"unique_eligible_negative_files_p95": stats.unique_eligible_negative_files_p95,
"fraction_ready_with_8_plus_negative_files": stats.fraction_ready_with_8_plus_negative_files,
},
sort_keys=True,
)
)
return 1 if stats.repo_errors else 0
if args.command == "export-train":
records = read_selection(args.selection)
selection_hash = verify_selection_hash_against_dbs(
records,
db_dir=args.db_dir,
allow_selection_mismatch=args.allow_selection_mismatch,
warning_printer=_warn_stderr,
)
if args.repo_workers < 1:
parser.error("--repo-workers must be >= 1")
if args.repo_workers > 1:
grouped = group_tasks_by_repo(records)
repos = sorted(
repo for repo, repo_records in grouped.items() if any(record.split == args.split for record in repo_records)
)
shard_dir = args.output.parent / f"{args.output.name}.shards"
shard_dir.mkdir(parents=True, exist_ok=True)
workers = min(args.repo_workers, len(repos)) if repos else 1
progress = tqdm(total=len(repos), desc="export-train", unit="repo", dynamic_ncols=True)
rows: list[dict[str, object]] = []
with concurrent.futures.ProcessPoolExecutor(max_workers=workers) as pool:
futures = {
pool.submit(
export_train_repo_worker,
repo,
grouped[repo],
args.db_dir,
args.negative_file,
shard_dir / f"{repo}.jsonl",
args.split,
args.negatives_per_row,
args.max_positives_per_task,
selection_hash,
): repo
for repo in repos
}
for future in concurrent.futures.as_completed(futures):
repo = futures[future]
row = future.result()
rows.append(row)
progress.update(1)
progress.set_postfix_str(
f"{repo} rows={int(row.get('rows', 0))} tasks={int(row.get('tasks_exported', 0))}"
)
progress.close()
rows.sort(key=lambda row: str(row["repo"]))
concatenate_jsonl_shards([Path(str(row["output"])) for row in rows], args.output)
summary = aggregate_parallel_export_stats(rows, args.output)
summary["selection_hash"] = selection_hash
print(json.dumps(summary, sort_keys=True), file=sys.stderr)
return 0
stats = export_training_examples(
records,
db_dir=args.db_dir,
negative_files=args.negative_file,
output=args.output,
split=args.split,
negatives_per_row=args.negatives_per_row,
max_positives_per_task=args.max_positives_per_task,
)
print(
json.dumps(
{
"output": str(args.output),
"selection_hash": selection_hash,
"rows": stats.rows,
"tasks_exported": stats.tasks_exported,
"skipped_no_positive": stats.skipped_no_positive,
"skipped_too_few_negatives": stats.skipped_too_few_negatives,
"positives_per_task_p50": stats.positives_per_task_p50,
"positives_per_task_p95": stats.positives_per_task_p95,
"positives_per_task_max": stats.positives_per_task_max,
"num_tasks_with_0_negatives": stats.num_tasks_with_0_negatives,
"num_tasks_with_1_7_negatives": stats.num_tasks_with_1_7_negatives,
"num_tasks_with_8_plus_negatives": stats.num_tasks_with_8_plus_negatives,
"mined_negatives_per_task_p50": stats.mined_negatives_per_task_p50,
"mined_negatives_per_task_p95": stats.mined_negatives_per_task_p95,
"mined_negatives_per_task_max": stats.mined_negatives_per_task_max,
"target_files_per_task_p50": stats.target_files_per_task_p50,
"target_files_per_task_p95": stats.target_files_per_task_p95,
"target_files_per_task_max": stats.target_files_per_task_max,
"positive_chunks_per_target_file_p50": stats.positive_chunks_per_target_file_p50,
"positive_chunks_per_target_file_p95": stats.positive_chunks_per_target_file_p95,
"positive_chunks_per_target_file_max": stats.positive_chunks_per_target_file_max,
"fraction_tasks_dropped_too_few_distinct_negative_files": (
stats.fraction_tasks_dropped_too_few_distinct_negative_files
),
"true_gold_files_per_task_p50": stats.true_gold_files_per_task_p50,
"true_gold_files_per_task_p95": stats.true_gold_files_per_task_p95,
"true_gold_files_per_task_min": stats.true_gold_files_per_task_min,
"exported_gold_file_groups_per_task_p50": (
stats.exported_gold_file_groups_per_task_p50
),
"exported_gold_file_groups_per_task_p95": (
stats.exported_gold_file_groups_per_task_p95
),
"exported_gold_file_groups_per_task_max": (
stats.exported_gold_file_groups_per_task_max
),
"missing_gold_file_groups_per_task_p50": stats.missing_gold_file_groups_per_task_p50,
"missing_gold_file_groups_per_task_p95": stats.missing_gold_file_groups_per_task_p95,
"missing_gold_file_groups_per_task_max": stats.missing_gold_file_groups_per_task_max,
"task_weight_exported_sum_p50": stats.task_weight_exported_sum_p50,
"task_weight_exported_sum_p95": stats.task_weight_exported_sum_p95,
"task_weight_exported_sum_min": stats.task_weight_exported_sum_min,
"fraction_tasks_with_partial_positive_coverage": (
stats.fraction_tasks_with_partial_positive_coverage
),
"positive_slot_old_hunk": stats.positive_slot_old_hunk,
"positive_slot_class_summary_fallback": stats.positive_slot_class_summary_fallback,
"positive_slot_file_summary_fallback": stats.positive_slot_file_summary_fallback,
"valid_positive_slots_1": stats.valid_positive_slots_1,
"valid_positive_slots_2": stats.valid_positive_slots_2,
"valid_positive_slots_3": stats.valid_positive_slots_3,
"valid_positive_slots_4": stats.valid_positive_slots_4,
"valid_positive_negative_pairs": stats.valid_positive_negative_pairs,
"rows_with_3_plus_old_hunks": stats.rows_with_3_plus_old_hunks,
"rows_with_4_old_hunks": stats.rows_with_4_old_hunks,
"fallback_only_rows": stats.fallback_only_rows,
},
sort_keys=True,
),
file=sys.stderr,
)
return 0
raise AssertionError(f"unhandled command: {args.command}")
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))