hackathon-data / output /rag-dense /prepare-v2 /source-script.py
julianvolodia's picture
Super-squash branch 'main' using huggingface_hub
90264a9
Raw History Blame Contribute Delete
21.2 kB
#!/usr/bin/env python3
"""Dense-only retrieval experiment. Does not solve or grade exam answers.
Index complete cleaned heading sections. Encoder windows respect the model's
capacity; returned section text is never token-truncated. All model runs use
track.py; --prepare-only validates/extracts inputs without model inference.
"""
from __future__ import annotations
import argparse
from collections import Counter, defaultdict
from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path
import re
import sys
import time
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / "harness"))
import eval_scenarios
import matura
import track
MODEL = "OPI-PIB/PolDense-1B"
REVISION = "2a5d873862989f3a2f9344f6bb50b8371e873d4d"
DATASET_REVISION = "277db69e40dd3fb6680290e93791f53d40bbe770"
LESSONS_SHA256 = "ae0d77c41d9c0ac26508b3d57a4297e6b4075040e2c73df67dc5a9bbb4a407e5"
def sha(data):
return hashlib.sha256(data).hexdigest()
def write_json(path, value):
path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
def read_rows(path):
return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
def write_rows(path, rows):
with path.open("w", encoding="utf-8") as stream:
for row in rows:
stream.write(json.dumps(row, ensure_ascii=False) + "\n")
def extract_sections(lesson, exercises):
"""Remove exact crawler exercise bodies, then split at real headings.
Unmatched exercise markers/answers quarantine the whole affected section.
No truncation at the first exercise, which would lose following exposition.
The original lesson and each removal remain independently inspectable.
"""
text = lesson["text"]
removals = []
for exercise in sorted(exercises, key=lambda e: len(e.get("markdown", "")), reverse=True):
body = exercise.get("markdown", "").strip()
if not body:
continue
# Only remove when both the label and exact body occur as a block.
label = exercise.get("label") or ("Ćwiczenie" if exercise.get("kind") == "interactive" else "Polecenie")
pattern = re.compile(r"(?m)^\*\*" + re.escape(label) + r"\*\*\s*\n+" + re.escape(body) + r"(?=\s*\n|$)")
text, n = pattern.subn("", text)
if n:
removals.append({"kind": "exercise", "exercise_no": exercise.get("exercise_no"),
"body_sha256": sha(body.encode()), "occurrences": n})
# These are captions/descriptions, not delivered image/audio evidence.
blocks = []
for block in text.split("\n\n"):
if re.match(r"^\*(?:Ilustracja|Materiał|Film|Nagranie)(?::|\*)", block.strip()):
removals.append({"kind": "media_description", "body_sha256": sha(block.encode())})
elif re.fullmatch(r"(?:- (?:umiejętność|wiedzę|zrozumienie):\s*)+", block.strip()):
removals.append({"kind": "self_assessment_scaffold", "body_sha256": sha(block.encode())})
else:
blocks.append(block)
text = "\n\n".join(blocks)
text = re.sub(r"(?m)^\*\*(Słowniczek|Słownik)\*\*$", r"### \1", text)
sections, excluded, path, body = [], [], [], []
ordinal = 0
def flush():
nonlocal ordinal
content = "\n".join(body).strip()
if not content:
return
ordinal += 1
section_id = f"{lesson['lesson_id']}/section-{ordinal:03d}"
reason = None
if len(path) < 2 and all(line.strip() in (lesson["book_title"], f"Źródło: {lesson['url']}", "")
or line.strip().startswith(lesson["book_title"] + " ›") for line in body):
reason = "lesson_preamble"
elif re.search(r"\*\*(?:Ćwiczenie|Polecenie)|(?m:^- \[[ x]\])|Poprawna kolejność:|Błędne hasła:", content):
reason = "unresolved_exercise_or_answer_markup"
elif lesson["lesson_id"] == "epod-nowozytnosc-07" and "1888" in content:
reason = "confirmed_internal_chronology_contradiction_dias"
if reason:
excluded.append({"section_id": section_id, "heading_path": [p[1] for p in path],
"reason": reason, "text": content})
return
sections.append({"section_id": section_id, "lesson_id": lesson["lesson_id"],
"book": lesson["book"], "book_title": lesson["book_title"],
"lesson": lesson["lesson"], "heading_path": [p[1] for p in path],
"url": lesson["url"], "text": content,
"text_sha256": sha(content.encode()),
"lesson_sha256": sha(lesson["text"].encode()),
"quality_status": "source_text_not_fully_fact_checked"})
for line in text.splitlines():
match = re.match(r"^(#{1,6})\s+(.+)$", line)
if match:
flush()
level, title = len(match[1]), match[2]
path[:] = [p for p in path if p[0] < level] + [(level, title)]
body = []
else:
body.append(line)
flush()
return sections, excluded, removals
def prepare(args):
raw = args.lessons.read_bytes()
if sha(raw) != LESSONS_SHA256:
raise ValueError("Lesson snapshot changed: audit and pin a new source revision first")
lessons = read_rows(args.lessons)
by_code, supplemental_hashes = defaultdict(list), {}
for file in sorted(args.crawler_root.glob("*/exercises.jsonl")):
supplemental_hashes[str(file.relative_to(args.crawler_root))] = sha(file.read_bytes())
for row in read_rows(file):
by_code[row["lesson_code"]].append(row)
sections, excluded, cleaning = [], [], []
for lesson in lessons:
kept, dropped, removed = extract_sections(lesson, by_code[lesson["lesson_code"]])
sections.extend(kept)
excluded.extend(dropped)
cleaning.append({"lesson_id": lesson["lesson_id"], "sections": len(kept), "removals": removed})
if not sections or len({s["section_id"] for s in sections}) != len(sections):
raise ValueError("Empty corpus or duplicate section IDs")
observations = json.loads(args.observations.read_text()) if args.observations else {"images": {}}
if set(observations) != {"images"} or not isinstance(observations["images"], dict):
raise ValueError("Observations must be an object with images keyed by exact image SHA-256")
scenario = eval_scenarios.load(eval_scenarios.DEFAULT, args.exam_root)
queries = []
for row in scenario["definition"]["exams"]:
exam, _, assets = matura.load_package(args.exam_root / row["exam_id"] / "exam.json")
for item in exam["items"]:
queries.append(make_query(exam, item, assets, observations))
return sections, queries, excluded, cleaning, {
"dataset": "WMTH-100d2exam/epodreczniki-2201", "dataset_revision": DATASET_REVISION,
"lessons_sha256": sha(raw), "exercise_files_sha256": supplemental_hashes,
"scenario": scenario, "observations_sha256": sha(args.observations.read_bytes()) if args.observations else None,
}
def make_query(exam, item, assets, observations):
parts = ["Polecenie:\n" + item["question"], "Teksty źródłowe:\n" + item["source_text"]]
descriptions, missing, image_hashes = [], [], {}
for image in item["images"]:
digest = sha(assets[image["path"]])
image_hashes[image["path"]] = digest
entry = observations["images"].get(digest)
if entry is None:
missing.append(digest)
continue
if not isinstance(entry, dict) or set(entry) - {"observations", "ocr", "producer"}:
raise ValueError("Invalid image observation record")
for key in ("observations", "ocr"):
value = entry.get(key, "")
if not isinstance(value, str):
raise ValueError("Image observations/OCR must be text")
if value.strip():
descriptions.append({"image_sha256": digest, "kind": key, "text": value,
"producer": entry.get("producer")})
parts.append(f"Obraz {image['path']} — {key} (opis pomocniczy):\n{value}")
if not entry.get("observations", "").strip() and not entry.get("ocr", "").strip():
missing.append(digest)
return {"exam_id": exam["exam_id"], "item_id": item["id"],
"item_sha256": sha(matura.encode(item)), "image_sha256": image_hashes,
"query": "\n\n".join(parts), "image_observations": descriptions,
"missing_image_descriptions": missing,
"essay": "essay" in matura.task_profile(item)["routes"]}
def full_text(section):
return "\n".join([section["book_title"], " > ".join(section["heading_path"]), section["text"]])
def encoder_windows(text, tokenizer, limit, prefix=""):
"""Partition by character offsets only if intrinsic encoder capacity requires it."""
capacity = limit - tokenizer.num_special_tokens_to_add(False) - len(tokenizer.encode(prefix, add_special_tokens=False)) - 4
if capacity <= 0:
raise ValueError("Invalid encoder capacity")
encoded = tokenizer(text, add_special_tokens=False, return_offsets_mapping=True)
offsets = encoded["offset_mapping"]
if not offsets:
return [prefix + text]
windows, start = [], 0
for end_token in range(capacity, len(offsets) + capacity, capacity):
end = offsets[min(end_token, len(offsets)) - 1][1]
if end_token >= len(offsets):
end = len(text)
value = prefix + text[start:end]
if len(tokenizer.encode(value)) > limit:
raise ValueError("Encoder window exceeds model capacity; refusing truncation")
windows.append(value)
start = end
return windows
def run(args):
if args.output.exists():
raise ValueError("Use a new output directory; previous experiments are immutable")
sections, queries, excluded, cleaning, provenance = prepare(args)
args.output.mkdir(parents=True)
(args.output / "source-script.py").write_bytes(Path(__file__).read_bytes())
write_rows(args.output / "sections.jsonl", sections)
write_rows(args.output / "queries.jsonl", queries)
write_rows(args.output / "excluded-sections.jsonl", excluded)
write_rows(args.output / "cleaning.jsonl", cleaning)
manifest = {"created_utc": datetime.now(timezone.utc).isoformat(), "mode": "dense-only",
"provenance": provenance, "model": MODEL, "model_revision": REVISION,
"script_sha256": sha(Path(__file__).read_bytes()),
"sections_sha256": sha((args.output / "sections.jsonl").read_bytes()),
"queries_sha256": sha((args.output / "queries.jsonl").read_bytes()),
"short_k": args.short_k, "essay_k": args.essay_k, "retrieval_token_budget": None,
"essay_policy": "single combined query, eight sections; aspect planning deferred",
"encoder_overflow": "full coverage windows, no input discarded; max window score per section",
"query_overflow": "normalized mean of query-window vectors",
"counts": {"sections": len(sections), "queries": len(queries), "excluded_sections": len(excluded)},
"exclusion_reasons": dict(Counter(s["reason"] for s in excluded))}
write_json(args.output / "manifest.json", manifest)
print(json.dumps(manifest["counts"]), flush=True)
if args.prepare_only:
print("Preparation only: no embedding or model-quality evaluation performed", flush=True)
return
tracking = track.start("rag-dense", "retrieval PolDense-1B epodreczniki default77 k3 essay8",
params={"model": MODEL, "model_revision": REVISION,
"short_k": args.short_k, "essay_k": args.essay_k,
"sections": len(sections), "queries": len(queries),
"retrieval_token_budget": None},
tags=["dense-only", "retrieval-only", "development-set"],
auto=False, capture_repository=False)
print("ClearML run:", tracking.url, flush=True)
write_json(args.output / "tracking.json", {"url": tracking.url, "ui": "http://X.X.X.X:18080"})
started = time.monotonic()
try:
import numpy as np
import torch
from sentence_transformers import SentenceTransformer
device = args.device or ("mps" if torch.backends.mps.is_available() else "cpu")
metadata = args.model_path / ".cache/huggingface/download/model.safetensors.metadata"
revision, expected_weight_sha = metadata.read_text().splitlines()[:2]
weight_sha = sha((args.model_path / "model.safetensors").read_bytes())
if revision != REVISION or weight_sha != expected_weight_sha:
raise ValueError("Model weights do not match the pinned Hugging Face download")
model = SentenceTransformer(str(args.model_path), device=device,
model_kwargs={"torch_dtype": torch.float32 if device == "cpu" else torch.float16,
"attn_implementation": "sdpa"},
config_kwargs={"reference_compile": False},
trust_remote_code=False, local_files_only=True)
limit = min(model.max_seq_length, model[0].auto_model.config.max_position_embeddings)
if limit <= 0:
raise ValueError("Unknown embedding model capacity")
manifest.update(device=device, encoder_max_tokens=limit, pooling=model[1].get_config_dict(),
model_weights_sha256=weight_sha,
model_files_sha256={str(p.relative_to(args.model_path)): sha(p.read_bytes())
for p in args.model_path.rglob("*.json") if ".cache" not in p.parts})
write_json(args.output / "manifest.json", manifest)
texts, parents = [], []
for index, section in enumerate(sections):
windows = encoder_windows(full_text(section), model.tokenizer, limit)
texts.extend(windows)
parents.extend([index] * len(windows))
cached = {}
if args.reuse_index:
old_manifest = json.loads((args.reuse_index / "manifest.json").read_text())
if any(old_manifest.get(k) != manifest.get(k) for k in
("model", "model_revision", "model_weights_sha256", "pooling", "encoder_max_tokens")):
raise ValueError("Cannot reuse embeddings from a different model or pooling configuration")
old_vectors = np.load(args.reuse_index / "embeddings.npy", allow_pickle=False)
old_windows = json.loads((args.reuse_index / "embedding-windows.json").read_text())
if len(old_vectors) != len(old_windows) or not np.isfinite(old_vectors).all():
raise ValueError("Invalid cached index")
cached = {w["text_sha256"]: v for w, v in zip(old_windows, old_vectors)}
manifest["reused_index"] = {"path": str(args.reuse_index),
"manifest_sha256": sha((args.reuse_index / "manifest.json").read_bytes()),
"vectors_sha256": sha((args.reuse_index / "embeddings.npy").read_bytes())}
write_json(args.output / "manifest.json", manifest)
vectors = []
reused = 0
for offset in range(0, len(texts), args.batch_size):
values = texts[offset:offset + args.batch_size]
pending = [value for value in values if sha(value.encode()) not in cached]
if pending:
new = model.encode(pending, batch_size=args.batch_size, normalize_embeddings=True,
convert_to_numpy=True, show_progress_bar=False)
fresh = iter(new)
batch = np.asarray([cached[sha(value.encode())] if sha(value.encode()) in cached else next(fresh)
for value in values])
reused += sum(sha(value.encode()) in cached for value in values)
if not np.isfinite(batch).all():
raise ValueError("Non-finite embedding vectors")
vectors.extend(batch)
if offset % 50 == 0:
print(f"Embedded {min(offset + args.batch_size, len(texts))}/{len(texts)} windows", flush=True)
tracking.log("embedded_windows", min(offset + args.batch_size, len(texts)), offset)
matrix = np.asarray(vectors, dtype=np.float32)
np.save(args.output / "embeddings.npy", matrix)
write_json(args.output / "embedding-windows.json", [{"section_id": sections[p]["section_id"],
"text_sha256": sha(t.encode())} for p, t in zip(parents, texts)])
parent_array = np.asarray(parents)
retrievals = []
for query in queries:
before = time.monotonic()
windows = encoder_windows(query["query"], model.tokenizer, limit, prefix="[query]: ")
embeddings = model.encode(windows, batch_size=args.batch_size, normalize_embeddings=True,
convert_to_numpy=True, show_progress_bar=False)
q = embeddings.mean(axis=0).astype(np.float32)
norm = np.linalg.norm(q)
if not np.isfinite(q).all() or norm <= 0:
raise ValueError("Invalid query embedding")
q /= norm
scores = np.full(len(sections), -np.inf, dtype=np.float32)
np.maximum.at(scores, parent_array, matrix @ q)
k = args.essay_k if query["essay"] else args.short_k
selected = np.argsort(-scores, kind="stable")[:k]
row = {**query, "query_windows": len(windows), "seconds": time.monotonic() - before,
"sections": [{**sections[int(i)], "score": float(scores[i]), "rank": rank}
for rank, i in enumerate(selected, 1)]}
retrievals.append(row)
with (args.output / "retrieval.jsonl").open("a", encoding="utf-8") as stream:
stream.write(json.dumps(row, ensure_ascii=False) + "\n")
print(f"Retrieved {query['exam_id']}:{query['item_id']} ({k} full sections)", flush=True)
result = {"status": "complete", "queries": len(retrievals), "sections": len(sections),
"embedding_windows": len(texts), "reused_embeddings": reused, "seconds": time.monotonic() - started,
"queries_missing_image_descriptions": sum(bool(q["missing_image_descriptions"]) for q in queries),
"retrieval_relevance_adjudicated": False, "exam_answers_generated": False,
"exam_score": None, "live_default_evaluation": "not run"}
write_json(args.output / "summary.json", result)
tracking.summary(result)
tracking.table("retrieval-timings", [{"query_index": i, "seconds": r["seconds"],
"sections_returned": len(r["sections"])}
for i, r in enumerate(retrievals)])
# Source passages, questions, observations and full provenance stay local.
# This report contains only sanitized aggregate metrics.
tracking.file("summary", args.output / "summary.json")
print(json.dumps(result, indent=2), flush=True)
except BaseException as error:
write_json(args.output / "failure.json", {"type": type(error).__name__, "error": str(error),
"seconds": time.monotonic() - started})
tracking.summary({"status": "failed", "error_type": type(error).__name__})
raise
finally:
tracking.close()
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--lessons", type=Path, default=ROOT / "data/epodreczniki/dataset/lessons.jsonl")
parser.add_argument("--crawler-root", type=Path, default=ROOT / "data/epodreczniki")
parser.add_argument("--exam-root", type=Path, default=ROOT / "data/evaluation-2017-2026")
parser.add_argument("--model-path", type=Path, default=ROOT / "models/rag/PolDense-1B")
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--observations", type=Path, help="images: {sha256: {observations, ocr, producer}}")
parser.add_argument("--reuse-index", type=Path, help="Reuse exact text-window embeddings from a matching local model/index")
parser.add_argument("--short-k", type=int, default=3)
parser.add_argument("--essay-k", type=int, default=8)
parser.add_argument("--batch-size", type=int, default=1)
parser.add_argument("--device", choices=("cpu", "mps", "cuda"))
parser.add_argument("--prepare-only", action="store_true")
args = parser.parse_args()
if min(args.short_k, args.essay_k, args.batch_size) < 1:
parser.error("k and batch size must be positive")
run(args)
if __name__ == "__main__":
main()