| |
| """ |
| Load CVE-KGRAG chunks into Qdrant with dense (transformer) + sparse (BM25) vectors. |
| |
| Standalone — does not require the upstream CVE-KGRAG codebase. Creates four |
| collections: cve_chunks, mitre_techniques, capec_patterns, cwe_entries. |
| |
| Each point carries a named "dense" vector (640-dim by default, microsoft/harrier-oss-v1-270m) |
| and a named "sparse" vector encoded from bm25/vocab.json. |
| |
| Resumes from checkpoint at <kb-dir>/bm25/qdrant_checkpoint.json so you can re-run |
| after an interruption without re-encoding everything. |
| |
| Usage: |
| python load_qdrant.py --kb-dir ./data/knowledge_base \ |
| --qdrant-url http://localhost:6333 \ |
| --model microsoft/harrier-oss-v1-270m |
| """ |
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import logging |
| import math |
| import re |
| import sys |
| import uuid |
| from collections import Counter |
| from pathlib import Path |
| from typing import Any, Dict, Iterable, List, Tuple |
|
|
| from qdrant_client import QdrantClient |
| from qdrant_client.models import ( |
| Distance, PointStruct, SparseIndexParams, SparseVector, |
| SparseVectorParams, VectorParams, |
| ) |
| from sentence_transformers import SentenceTransformer |
| from tqdm import tqdm |
|
|
| logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s") |
| log = logging.getLogger("load_qdrant") |
|
|
| COLLECTIONS = { |
| "cve": "cve_chunks", |
| "mitre": "mitre_techniques", |
| "capec": "capec_patterns", |
| "cwe": "cwe_entries", |
| } |
| CHUNK_FILES = { |
| "cve": "rag_exports/cve_chunks.json", |
| "mitre": "rag_exports/mitre_chunks.json", |
| "capec": "rag_exports/capec_chunks.json", |
| "cwe": "rag_exports/cwe_chunks.json", |
| } |
| DENSE = "dense" |
| SPARSE = "sparse" |
| TOKEN_RE = re.compile(r"[a-z0-9][a-z0-9_-]*", re.IGNORECASE) |
| K1 = 1.5 |
| B = 0.75 |
|
|
|
|
| def tokenize(text: str) -> List[str]: |
| return [t.lower() for t in TOKEN_RE.findall(text or "")] |
|
|
|
|
| def point_uuid(chunk_id: str) -> str: |
| return str(uuid.uuid5(uuid.NAMESPACE_URL, chunk_id)) |
|
|
|
|
| class SparseEncoder: |
| """BM25-weighted sparse vectors using the prebuilt vocab.json.""" |
|
|
| def __init__(self, vocab_path: Path, avgdl: float = 200.0) -> None: |
| with vocab_path.open("r", encoding="utf-8") as f: |
| raw = json.load(f) |
| self.token_to_id = {t: int(v["id"]) for t, v in raw.items()} |
| self.idf = {int(v["id"]): float(v["idf"]) for v in raw.values()} |
| self.avgdl = avgdl |
|
|
| def encode(self, text: str) -> SparseVector: |
| tokens = tokenize(text) |
| dl = len(tokens) or 1 |
| tf = Counter(tokens) |
| indices: List[int] = [] |
| values: List[float] = [] |
| for tok, count in tf.items(): |
| tid = self.token_to_id.get(tok) |
| if tid is None: |
| continue |
| num = count * (K1 + 1) |
| den = count + K1 * (1 - B + B * dl / self.avgdl) |
| indices.append(tid) |
| values.append(self.idf[tid] * num / den) |
| return SparseVector(indices=indices, values=values) |
|
|
|
|
| def ensure_collections(client: QdrantClient, dense_dim: int) -> None: |
| existing = {c.name for c in client.get_collections().collections} |
| for name in COLLECTIONS.values(): |
| if name in existing: |
| log.info(f" {name} already exists") |
| continue |
| client.create_collection( |
| collection_name=name, |
| vectors_config={DENSE: VectorParams(size=dense_dim, distance=Distance.COSINE)}, |
| sparse_vectors_config={SPARSE: SparseVectorParams(index=SparseIndexParams())}, |
| ) |
| log.info(f" created {name}") |
|
|
|
|
| def sanitize_payload(p: Dict[str, Any]) -> Dict[str, Any]: |
| """Qdrant indexes scalars and flat lists fine; nested dicts become JSON strings.""" |
| out: Dict[str, Any] = {} |
| for k, v in p.items(): |
| if isinstance(v, (str, int, float, bool)) or v is None: |
| out[k] = v |
| elif isinstance(v, list) and all(isinstance(x, (str, int, float, bool)) for x in v): |
| out[k] = v |
| else: |
| out[k] = json.dumps(v, ensure_ascii=False) |
| return out |
|
|
|
|
| def upsert_collection( |
| client: QdrantClient, |
| collection: str, |
| chunks: List[Dict[str, Any]], |
| dense_model: SentenceTransformer, |
| sparse: SparseEncoder, |
| *, |
| batch: int = 2000, |
| resume_from: int = 0, |
| ) -> int: |
| total = len(chunks) |
| log.info(f" → {collection}: {total - resume_from:,} / {total:,} chunks to encode") |
| for start in tqdm(range(resume_from, total, batch), desc=collection): |
| end = min(start + batch, total) |
| slab = chunks[start:end] |
| texts = [c["text"] for c in slab] |
| dense = dense_model.encode(texts, batch_size=128, show_progress_bar=False, |
| convert_to_numpy=True, normalize_embeddings=True) |
| points = [] |
| for c, d in zip(slab, dense): |
| points.append(PointStruct( |
| id=point_uuid(c["id"]), |
| vector={ |
| DENSE: d.tolist(), |
| SPARSE: sparse.encode(c["text"]), |
| }, |
| payload={**sanitize_payload(c.get("payload") or {}), "chunk_id": c["id"]}, |
| )) |
| client.upsert(collection_name=collection, points=points) |
| yield end |
|
|
|
|
| def load_chunks(path: Path) -> List[Dict[str, Any]]: |
| with path.open("r", encoding="utf-8") as f: |
| return json.load(f) |
|
|
|
|
| def main() -> int: |
| p = argparse.ArgumentParser(description=__doc__) |
| p.add_argument("--kb-dir", required=True, type=Path, |
| help="Knowledge-base root (containing rag_exports/ and bm25/)") |
| p.add_argument("--qdrant-url", default="http://localhost:6333") |
| p.add_argument("--qdrant-api-key", default=None) |
| p.add_argument("--model", default="microsoft/harrier-oss-v1-270m", |
| help="HF sentence-transformers model for dense vectors") |
| p.add_argument("--device", default=None, help="cuda|cpu (auto if omitted)") |
| p.add_argument("--batch", type=int, default=2000) |
| p.add_argument("--recreate", action="store_true", |
| help="Drop and recreate collections before loading") |
| args = p.parse_args() |
|
|
| if not (args.kb_dir / "rag_exports").is_dir(): |
| log.error(f"--kb-dir missing rag_exports/: {args.kb_dir}") |
| return 2 |
|
|
| log.info(f"Loading dense model: {args.model}") |
| dense_model = SentenceTransformer(args.model, device=args.device) |
| dense_dim = dense_model.get_sentence_embedding_dimension() |
| log.info(f" dim={dense_dim}") |
|
|
| log.info("Loading sparse encoder") |
| sparse = SparseEncoder(args.kb_dir / "bm25" / "vocab.json") |
|
|
| client = QdrantClient(url=args.qdrant_url, api_key=args.qdrant_api_key, timeout=60) |
|
|
| if args.recreate: |
| log.info("Recreating collections") |
| for name in COLLECTIONS.values(): |
| try: |
| client.delete_collection(name) |
| except Exception: |
| pass |
| ensure_collections(client, dense_dim) |
|
|
| ckpt_path = args.kb_dir / "bm25" / "qdrant_checkpoint.json" |
| ckpt: Dict[str, int] = {} |
| if ckpt_path.exists(): |
| ckpt = json.loads(ckpt_path.read_text()) |
| log.info(f"Resuming from checkpoint: {ckpt}") |
|
|
| for key, rel in CHUNK_FILES.items(): |
| path = args.kb_dir / rel |
| if not path.exists(): |
| log.warning(f" {path} missing, skipping {key}") |
| continue |
| chunks = load_chunks(path) |
| col = COLLECTIONS[key] |
| resume = ckpt.get(col, 0) if not args.recreate else 0 |
| if resume >= len(chunks): |
| log.info(f" {col}: already complete ({resume:,}/{len(chunks):,})") |
| continue |
| for done in upsert_collection( |
| client, col, chunks, dense_model, sparse, |
| batch=args.batch, resume_from=resume, |
| ): |
| ckpt[col] = done |
| ckpt_path.write_text(json.dumps(ckpt)) |
| log.info(f" {col}: complete") |
|
|
| log.info("Done. Counts:") |
| for name in COLLECTIONS.values(): |
| info = client.get_collection(name) |
| log.info(f" {name}: {info.points_count:,} points") |
| return 0 |
|
|
|
|
| if __name__ == "__main__": |
| sys.exit(main()) |
|
|