Publish verified LibreOffice character retrieval transfer
Browse filesFiles changed (7)
- README.md+2
- stages/12-v5-mail-cpu/title-character-transfer/REPORT.mdAdded+23
- stages/12-v5-mail-cpu/title-character-transfer/results.jsonAdded+1
- stages/12-v5-mail-cpu/title-character-transfer/study_historical_fusion.pyAdded+149
- stages/12-v5-mail-cpu/title-character-transfer/study_title_char_retrieval.pyAdded+173
- stages/12-v5-mail-cpu/title-character-transfer/study_title_char_transfer.pyAdded+108
- stages/12-v5-mail-cpu/title-character-transfer/verify_webkit_statistics.pyAdded+122
44 unmodified lines45464744 unmodified lines- [Mozilla Core. Резерв мест в списке кандидатов](stages/12-v5-mail-cpu/fusion-probe/REPORT.md)- [Mozilla Core. Поиск по символьным фрагментам заголовка](stages/12-v5-mail-cpu/title-character-probe/REPORT.md)44 unmodified lines454647484944 unmodified lines- [Mozilla Core. Резерв мест в списке кандидатов](stages/12-v5-mail-cpu/fusion-probe/REPORT.md)- [Mozilla Core. Поиск по символьным фрагментам заголовка](stages/12-v5-mail-cpu/title-character-probe/REPORT.md)- [LibreOffice. Перенос символьного поиска](stages/12-v5-mail-cpu/title-character-transfer/REPORT.md)
1234567891011121314151617181920212223# Перенос символьного поиска на LibreOffice
Сравнили обычный RRF с добавлением поиска по символьным фрагментам заголовка на замороженной выборке LibreOffice. Применили настройки из Mozilla Core. Символьный поиск использует фрагменты длиной от трёх до пяти и до 40 более ранних результатов с весом 0,5. BM25 и E5 сохраняют вес 1. Общий список содержит до 24 кандидатов. [Эксперимент Mozilla Core](../title-character-probe/REPORT.md)
| Положительные группы | Обычный RRF | С символьным поиском | Парная разница | Выигрыши / потери ||---|---:|---:|---:|---:|| Все, 326 | 68,4% | 69,9% | 1,5 п.п. (95% ДИ [0,0, 3,4]) | 7 / 2 || Ранняя половина, 163 | 65,0% | 67,5% | 2,5 п.п. (95% ДИ [0,6, 4,9]) | 4 / 0 || Поздняя половина, 163 | 71,8% | 72,4% | 0,6 п.п. (95% ДИ [-1,8, 3,7]) | 3 / 2 |
Символьный поиск нашёл дубль за пределами обоих исходных списков в 13 группах. После слияния такие дубли остались в 0 группах.
При загруженном индексе и готовых исходных списках дополнительный поиск и слияние заняли 4,29 / 7,18 мс p50 / p95 на AMD Ryzen 5 1600 Six-Core Processor в одном потоке. На всех 895 запросах списки совпали с прямым расчётом. Замер охватывает попадание дубля в список до переранжирования. Выборка повторно использует уже известный тест V4. [CPU-бенчмарк V4](../../10-v4-cpu/REPORT.md)
## Воспроизведение
Поместите четыре Python-файла дополнения рядом. Используйте архив LibreOffice и сохранённые результаты V4. Скрипт сверяет замороженное разбиение, порядок кандидатов и оценки повторной выборки. [Воспроизведение V4](../../10-v4-cpu/REPRODUCE.md)
~~~powershellpython -B study_title_char_transfer.py --holdout $transfer --run $run --out ./title-character-transfer~~~
[Агрегированные результаты](results.json)1{"all":{"character_hits":228,"exact_ci95":[-0.003067484662576687,0.03374233128834356],"ordinary_hits":223,"paired":{"ci95":[0.0,0.03374233128834356],"delta":0.015337423312883436,"losses":2,"ties":317,"wins":7},"positive_groups":326},"archive_documents":17257,"candidate_limit":24,"character_depth":40,"character_index_bytes":17748876,"character_ngram_range":[3,5],"character_rrf_weight":0.5,"cpu":"AMD Ryzen 5 1600 Six-Core Processor","cpu_ms_p50_p95":[4.285,7.184979999999998],"early":{"character_hits":110,"exact_ci95":[0.006134969325153374,0.049079754601226995],"ordinary_hits":106,"paired":{"ci95":[0.006134969325153374,0.049079754601226995],"delta":0.024539877300613498,"losses":0,"ties":159,"wins":4},"positive_groups":163},"exclusive_gold_retained_in_fusion":0,"hash_width":262144,"identical_rankings_verified":895,"labelled_gold_exclusive_to_character_list":13,"late":{"character_hits":118,"exact_ci95":[-0.018404907975460124,0.03067484662576687],"ordinary_hits":117,"paired":{"ci95":[-0.018404907975460124,0.03680981595092025],"delta":0.006134969325153374,"losses":2,"ties":158,"wins":3},"positive_groups":163},"project":"LibreOffice","purpose":"fixed candidate coverage transfer before reranking","queries":895,"query_counts":{"hard":269,"ordinary":300,"positive":326},"reference_cpu_ms_p50_p95":[22.6403,31.13652],"source_hashes":{"archive_sha256":"84a1d21377b5fec9f5815d78a4aa25727d5c2199db6570e1a03cc3bc70fb9690","calibration_sha256":"08fd7335c9ee124e1a3c8088571cb5be6f0b72287cf45dab4deca08e3fc6ed98","metrics_sha256":"c84cc6524b2ad874589d2b71fc1b80ca1ac0368034293e9cef4fa66648e07b8c","predictions_sha256":"e12d003d94013c8ffa9986439074118edc27e058aeec266506f25922bea43a26","proof_sha256":"168f8f83b762c83244bda3e3413386c458e2639531cdab01bf3038b9c6d38445","split_sha256":"7b19c5de09be0ee2d8ce6ea3c0898f6b978d084067aec334ee51224a4b3dd123"}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149"""Compare a fixed 24-slot candidate list with six reserved places per retriever."""
from argparse import ArgumentParserfrom collections import defaultdictfrom pathlib import Path
from freeze_live_mozilla import read, require, stable_rowsfrom prepare import digestfrom report_apache import publishfrom report_live import recordsfrom results_core import delta, pctfrom verify_webkit_statistics import paired_summary
STAGE = "stages/12-v5-mail-cpu/fusion-probe"SIZE, RESERVED, RRF_CONSTANT = 24, 6, 20
def rank_by_rrf(sources, position): scores = defaultdict(float) for source, weight in sources: for rank, key in enumerate(source, 1): scores[key] += weight / (RRF_CONSTANT + rank) return sorted(scores, key=lambda key: (-scores[key], position[key]))
def fusion(bm25, e5, position): ordered = rank_by_rrf(((bm25, 1), (e5, 1)), position) reserved = set(bm25[:RESERVED]) | set(e5[:RESERVED]) for key in ordered: if len(reserved) == SIZE: break reserved.add(key) return ordered[:SIZE], [key for key in ordered if key in reserved]
def evaluate(pairs): standard, reserved = zip(*pairs, strict=True) comparison, exact = paired_summary(reserved, standard) return {"positive_groups": len(pairs), "rrf_hits": sum(standard), "reserved_hits": sum(reserved), "paired": comparison, "exact_ci95": exact}
def historical_development(run, plan, index): archive = index / "core.json" marker = read(index / "core.vector-identity.json") prediction_path = run / "dev-predictions.jsonl" calibration = run / "calibration.json" diagnostic = read(run / "dev-diagnostic.json") identity = read(run / "dev-predictions-identity.json") hashes = {"predictions_sha256": digest(prediction_path), "archive_sha256": digest(archive), "plan_sha256": digest(plan), "calibration_sha256": digest(calibration)} require(hashes["archive_sha256"] == marker["identity"]["archive"] and identity["index"] == marker and read(calibration)["identity"] == identity and diagnostic["role"] == "historical development only" and hashes["predictions_sha256"] == diagnostic["prediction_sha256"] and hashes["calibration_sha256"] == diagnostic["calibration_sha256"] and hashes["plan_sha256"] == read(run / "benchmark-lock.json")["historical_isolation_sha256"], "The verified historical development artifacts changed") archive_docs, rows = read(archive), read(plan)["splits"]["dev"] groups = {doc["id"]: doc["group"] for doc in archive_docs} require(len({groups[row["id"]] for row in rows}) == len(rows), "Expected one query per historical group") return archive_docs, rows, prediction_path, hashes
def verified_rankings(archive_docs, rows, prediction_path): times = {doc["id"]: doc["time"] for doc in archive_docs} require(len(times) == len(archive_docs) and len({row["id"] for row in rows}) == len(rows), "Expected distinct archive records and queries") predictions = records(prediction_path, rows) for row, pred in zip(rows, predictions, strict=True): issue, gold = row["id"], set(row["gold"]) bm25, e5 = ([entry["id"] for entry in pred[method]] for method in ("bm25", "e5")) require(all(len(source) <= 40 and len(source) == len(set(source)) for source in (bm25, e5)) and all(times[key] < times[issue] for key in {*bm25, *e5, *gold}), "A source list violates chronology or size") yield issue, gold, bm25, e5, [entry["id"] for entry in pred["rrf"]]
def run_study(run, plan, index): archive, rows, predictions, hashes = historical_development(run, plan, index) position = {doc["id"]: i for i, doc in enumerate(archive)} positive = [] changed_queries = changed_positive = 0 for issue, gold, bm25, e5, recorded in verified_rankings(archive, rows, predictions): baseline, variant = fusion(bm25, e5, position) require(baseline == recorded and len(variant) == len(baseline), "Standard RRF or the fixed candidate budget did not reproduce") changed = variant != baseline changed_queries += changed if gold: changed_positive += changed positive.append((archive[position[issue]]["time"], issue, bool(gold.intersection(baseline)), bool(gold.intersection(variant)))) outcomes = [(baseline, variant) for _, _, baseline, variant in sorted(positive)] middle = len(outcomes) // 2 require(middle > 0, "The development sample is too small to split chronologically") return {"purpose": "historical candidate coverage before reranking", "candidate_limit": SIZE, "reserved_per_source": RESERVED, "rrf_constant": RRF_CONSTANT, "historical_queries": len(rows), "changed_candidate_lists": changed_queries, "changed_positive_candidate_lists": changed_positive, "source_hashes": hashes, "all": evaluate(outcomes), "early": evaluate(outcomes[:middle]), "late": evaluate(outcomes[middle:])}
def render(result): lines = ["# Резерв мест в общем списке кандидатов", "", "На сохранённой калибровке Mozilla Core сравнили два способа отобрать до 24 кандидатов. " "Обычный RRF объединяет позиции BM25 и E5. В варианте с резервом первые шесть результатов " "каждого метода получают место в списке, а оставшиеся места заполняются по RRF. " "Совпадающие кандидаты занимают одно место.", "", "| Положительные группы | Обычный RRF | RRF с резервом | Парная разница | Только резерв / только обычный RRF |", "|---|---:|---:|---:|---:|"] for key, title in (("all", "Все"), ("early", "Ранняя половина"), ("late", "Поздняя половина")): row = result[key] n, comparison = row["positive_groups"], row["paired"] lines.append(f"| {title}, {n} | {pct(row['rrf_hits']/n)} | {pct(row['reserved_hits']/n)} | " f"{delta(comparison)} | {comparison['wins']} / {comparison['losses']} |") lines.extend(["", f"Состав списка изменился для {result['changed_candidate_lists']} из {result['historical_queries']} " f"запросов, включая {result['changed_positive_candidate_lists']} положительных групп. " "Нулевой интервал при отсутствии расхождений отражает этот прогон. Для другой выборки результат может отличаться.", "", "Показатель считает группы, в которых среди кандидатов есть размеченный дубль. " "Раннюю и позднюю половины выделили по времени создания запроса. " "Замер охватывает попадание в список кандидатов до переранжирования. Настройки теста V6 зафиксированы отдельно.", "", "## Воспроизведение", "", "Подготовьте сохранённые ранжирования калибровки V5 и исторический индекс. " "Положите оба Python-файла этого дополнения рядом. " "Скрипт сверяет их контрольные суммы, воспроизводит обычный RRF для каждого запроса " "и считает парные интервалы. [Воспроизведение V5](../REPRODUCE.md)", "", "~~~powershell", "$plan = 'work/iteration-05/mail-verification/historical-isolation.private.json'", "python -B study_historical_fusion.py --run $run --plan $plan --index (Join-Path $cache 'dev-index') --out ./fusion-probe", "~~~", "", "[Агрегированные результаты](results.json)", ""]) return "\n".join(lines)
if __name__ == "__main__": cli = ArgumentParser(description=__doc__) for name in ("run", "plan", "index", "out"): cli.add_argument(f"--{name}", required=True, type=Path) cli.add_argument("--publish", action="store_true") args = cli.parse_args() result = run_study(args.run, args.plan, args.index) report, metrics = args.out / "REPORT.md", args.out / "results.json" args.out.mkdir(parents=True, exist_ok=True) report.write_bytes(render(result).encode()) metrics.write_bytes(stable_rows(result)) if args.publish: script = Path(__file__).resolve() publish({"REPORT.md": report, "results.json": metrics, script.name: script, "verify_webkit_statistics.py": script.with_name("verify_webkit_statistics.py")}, stage=STAGE, title="Mozilla Core. Резерв мест в списке кандидатов", message="Publish the verified historical candidate fusion probe")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173"""Evaluate a fixed character retrieval channel on historical Core rankings."""
from argparse import ArgumentParserfrom pathlib import Pathfrom time import perf_counter_ns
import numpy as npfrom sklearn.feature_extraction.text import HashingVectorizerfrom threadpoolctl import threadpool_limits
from bench_core import measurement_environmentfrom bugdedup import topfrom freeze_live_mozilla import require, stable_rowsfrom prepare import wordsfrom report_apache import publishfrom results_core import delta, pctfrom study_historical_fusion import SIZE, historical_development, rank_by_rrf, verified_rankingsfrom verify_webkit_statistics import paired_summary
STAGE = "stages/12-v5-mail-cpu/title-character-probe"CHAR_WEIGHT, CHAR_LIMIT, HASH_WIDTH = .5, 40, 2 ** 18
def title_terms(title): return " ".join(words(title))
def character_reference(index, times, query, query_time): eligible = int(np.searchsorted(times, query_time, side="left")) scores = (index[:eligible] @ query.T).toarray().ravel() ordered = top(scores, CHAR_LIMIT) return ordered[scores[ordered] > 0]
def character_ranking(postings, times, query, query_time): eligible = int(np.searchsorted(times, query_time, side="left")) scores = np.zeros(eligible, dtype=np.float32) for feature, weight in zip(query.indices, query.data, strict=True): lower, upper = postings.indptr[feature:feature + 2] rows = postings.indices[lower:upper] count = int(np.searchsorted(rows, eligible, side="left")) scores[rows[:count]] += postings.data[lower:lower + count] * weight ordered = top(scores, CHAR_LIMIT) return ordered[scores[ordered] > 0]
def compare(outcomes): baseline, with_characters = zip(*outcomes, strict=True) paired, exact = paired_summary(with_characters, baseline) return {"positive_groups": len(outcomes), "ordinary_hits": sum(baseline), "character_hits": sum(with_characters), "paired": paired, "exact_ci95": exact}
def study(run, plan, cache): return study_rankings(*historical_development(run, plan, cache))
def study_rankings(archive, rows, predictions, hashes): position = {doc["id"]: i for i, doc in enumerate(archive)} times = np.asarray([doc["time"] for doc in archive], dtype=np.int64) require(np.all(times[1:] >= times[:-1]), "The historical index is not chronological") vectorizer = HashingVectorizer(analyzer="char_wb", ngram_range=(3, 5), n_features=HASH_WIDTH, lowercase=False, norm="l2", dtype=np.float32) index = vectorizer.transform(title_terms(doc["title"]) for doc in archive) postings = index.transpose().tocsr() postings.sort_indices()
def characters(issue, document_index, rank): ix = position[issue] query = vectorizer.transform([title_terms(archive[ix]["title"])]) positions = rank(document_index, times, query, times[ix]) require(np.all(times[positions] < times[ix]), "Character retrieval included a ticket from the future") return [archive[i]["id"] for i in positions]
rankings = list(verified_rankings(archive, rows, predictions)) for row in rows[:8]: characters(row["id"], postings, character_ranking) elapsed, positive = [], [] cached_character_lists = {} beyond_sources = available_after_fusion = 0 for issue, gold, bm25, e5, recorded in rankings: sources = ((bm25, 1), (e5, 1)) require(recorded == rank_by_rrf(sources, position)[:SIZE], "The original RRF list did not reproduce") start = perf_counter_ns() char = characters(issue, postings, character_ranking) fused = rank_by_rrf((*sources, (char, CHAR_WEIGHT)), position)[:SIZE] elapsed.append((perf_counter_ns() - start) / 1e6) cached_character_lists[issue] = (char, fused) if not gold: continue if not gold.intersection(bm25 + e5) and gold.intersection(char): beyond_sources += 1 available_after_fusion += bool(gold.intersection(fused)) positive.append((times[position[issue]], issue, bool(gold.intersection(recorded)), bool(gold.intersection(fused)))) reference_latency = [] for row in rows[:8]: characters(row["id"], index, character_reference) for issue, _, bm25, e5, _ in rankings: start = perf_counter_ns() char = characters(issue, index, character_reference) fused = rank_by_rrf(((bm25, 1), (e5, 1), (char, CHAR_WEIGHT)), position)[:SIZE] reference_latency.append((perf_counter_ns() - start) / 1e6) require((char, fused) == cached_character_lists[issue], "The inverted index changed the search ranking") outcomes = [(base, char) for _, _, base, char in sorted(positive)] middle = len(outcomes) // 2 require(middle > 0, "The development sample is too small to split chronologically") return {"purpose": "historical candidate coverage before reranking", "source_hashes": hashes, "archive_documents": len(archive), "queries": len(rows), "candidate_limit": SIZE, "character_depth": CHAR_LIMIT, "character_rrf_weight": CHAR_WEIGHT, "character_ngram_range": [3, 5], "hash_width": HASH_WIDTH, "labelled_gold_exclusive_to_character_list": beyond_sources, "exclusive_gold_retained_in_fusion": available_after_fusion, "cpu_ms_p50_p95": np.percentile(elapsed, (50, 95)).tolist(), "reference_cpu_ms_p50_p95": np.percentile(reference_latency, (50, 95)).tolist(), "identical_rankings_verified": len(cached_character_lists), "character_index_bytes": postings.data.nbytes + postings.indices.nbytes + postings.indptr.nbytes, "cpu": measurement_environment(1)["cpu"], "all": compare(outcomes), "early": compare(outcomes[:middle]), "late": compare(outcomes[middle:])}
def render(result): lines = ["# Поиск по символьным фрагментам заголовка", "", "В исторической калибровке Mozilla Core к BM25 и E5 добавили поиск по символьным фрагментам " "длиной от трёх до пяти. Он сравнивает нормализованные заголовки и возвращает до 40 более ранних " "тикетов. Вклад этой выдачи в RRF вдвое меньше вклада BM25 или E5. Размер общего списка остался 24.", "", "| Положительные группы | Обычный RRF | RRF с символьным поиском | Парная разница | Выигрыши / потери |", "|---|---:|---:|---:|---:|"] for key, label in (("all", "Все"), ("early", "Ранняя половина"), ("late", "Поздняя половина")): row = result[key] n, paired = row["positive_groups"], row["paired"] lines.append(f"| {label}, {n} | {pct(row['ordinary_hits']/n)} | {pct(row['character_hits']/n)} | " f"{delta(paired)} | {paired['wins']} / {paired['losses']} |") p50, p95 = (f"{val:.2f}".replace(".", ",") for val in result["cpu_ms_p50_p95"]) ref_p50, ref_p95 = (f"{val:.2f}".replace(".", ",") for val in result["reference_cpu_ms_p50_p95"]) index_mb = f"{result['character_index_bytes'] / 1e6:.1f}".replace(".", ",") documents = f"{result['archive_documents']:,}".replace(",", " ") lines.extend(["", f"В {result['labelled_gold_exclusive_to_character_list']} группах символьный поиск нашёл дубль " "за пределами обоих списков BM25 и E5. После слияния такой дубль остался в " f"{result['exclusive_gold_retained_in_fusion']} группах.", "", f"На {result['cpu']} при одном потоке и {documents} тикетов дополнительный поиск и слияние заняли " f"{ref_p50} / {ref_p95} мс p50 / p95 при прямом вычислении и {p50} / {p95} мс с инвертированным индексом. " f"Оба варианта выдали одинаковые списки на всех {result['identical_rankings_verified']} запросах. " f"Массивы инвертированного индекса заняли {index_mb} МБ. " "Замер начинается с загруженного индекса и готовых исходных списков BM25 и E5. " "Опыт измеряет наличие дубля в списке до переранжирования. " "Для оценки предложений и ложных совпадений нужен отдельный сквозной тест.", "", "## Воспроизведение", "", "Поместите три Python-файла рядом. Используйте сохранённые ранжирования и исторический индекс " "калибровки. [Воспроизведение V5](../REPRODUCE.md)", "", "~~~powershell", "$plan = 'work/iteration-05/mail-verification/historical-isolation.private.json'", "python -B study_title_char_retrieval.py --run $run --plan $plan --index (Join-Path $cache 'dev-index') --out ./title-character-probe", "~~~", "", "[Агрегированные результаты](results.json)", ""]) return "\n".join(lines)
if __name__ == "__main__": cli = ArgumentParser(description=__doc__) for name in ("run", "plan", "index", "out"): cli.add_argument(f"--{name}", required=True, type=Path) cli.add_argument("--publish", action="store_true") args = cli.parse_args() with threadpool_limits(limits=1): result = study(args.run, args.plan, args.index) report, metrics = args.out / "REPORT.md", args.out / "results.json" args.out.mkdir(parents=True, exist_ok=True) report.write_bytes(render(result).encode()) metrics.write_bytes(stable_rows(result)) if args.publish: script = Path(__file__).resolve() files = (script, script.with_name("study_historical_fusion.py"), script.with_name("verify_webkit_statistics.py")) publish({"REPORT.md": report, "results.json": metrics, **{p.name: p for p in files}}, stage=STAGE, title="Mozilla Core. Поиск по символьным фрагментам заголовка", message="Publish verified historical character retrieval probe")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108"""Apply the fixed Mozilla Core character probe to the frozen LibreOffice archive."""
from argparse import ArgumentParserfrom collections import Counterfrom pathlib import Path
from threadpoolctl import threadpool_limits
from freeze_live_mozilla import read, require, stable_rowsfrom prepare import digestfrom report_apache import publishfrom results_core import delta, pctfrom study_title_char_retrieval import study_rankingsfrom verify_results import verify as verify_predictions
STAGE = "stages/12-v5-mail-cpu/title-character-transfer"
def transfer(holdout, run): manifest_path = holdout / "split-libreoffice.json" proof_path = holdout / "holdout-verification.json" archive_path = holdout / "libreoffice.json" index = read(holdout / "libreoffice.vector-identity.json") lock = read(run / "benchmark-lock.json") manifest, proof = read(manifest_path), read(proof_path) rows = manifest["queries"] observed_counts = Counter("positive" if row["gold"] else "hard" if "witness" in row else "ordinary" for row in rows) require(digest(manifest_path) == proof["split_sha256"] == lock["libreoffice_sha256"] and digest(proof_path) == lock["libreoffice_verification_sha256"] and digest(archive_path) == index["archive_sha256"] == manifest["archive_sha256"] and index["rows"] == proof["archive_rows"] == manifest["archive_rows"] and proof["duplicate_groups_shared"] == 0 and observed_counts == proof["query_counts"], "The independently checked V4 LibreOffice archive or duplicate groups changed")
calibration_path = run / "calibration.json" fitted = read(run / "fitted/identity.json") prediction_path = run / "libreoffice-predictions.jsonl" identity = run / "libreoffice-predictions-identity.json" saved_path = run / "libreoffice-metrics.json" saved = read(saved_path) calibration = read(calibration_path) binding = {"calibration_sha256": digest(calibration_path), "fitted": fitted, "index": index} require(binding == read(identity) == saved["evidence"] and identity.stat().st_mtime_ns >= calibration_path.stat().st_mtime_ns and saved["environment"]["provider"] == "CPUExecutionProvider", "The saved CPU rankings have different provenance") verify_predictions(run, {"splits": {"libreoffice": rows}, "projects": {"libreoffice": "libreoffice"}}, "libreoffice", calibration, archive_root=holdout) hashes = {"split_sha256": proof["split_sha256"], "archive_sha256": manifest["archive_sha256"], "proof_sha256": digest(proof_path), "calibration_sha256": binding["calibration_sha256"], "predictions_sha256": digest(prediction_path), "metrics_sha256": digest(saved_path)} result = study_rankings(read(archive_path), rows, prediction_path, hashes) require(result["all"]["ordinary_hits"] == saved["systems"]["rrf"]["positive_in_shared_pool"], "Shared RRF coverage disagrees with the saved report") return {**result, "purpose": "fixed candidate coverage transfer before reranking", "project": "LibreOffice", "query_counts": dict(observed_counts)}
def render(result): lines = ["# Перенос символьного поиска на LibreOffice", "", "Сравнили обычный RRF с добавлением поиска по символьным фрагментам заголовка на замороженной выборке LibreOffice. " "Применили настройки из Mozilla Core. Символьный поиск использует фрагменты длиной от трёх до пяти и до 40 " "более ранних результатов с весом 0,5. BM25 и E5 сохраняют вес 1. Общий список содержит до 24 кандидатов. " "[Эксперимент Mozilla Core](../title-character-probe/REPORT.md)", "", "| Положительные группы | Обычный RRF | С символьным поиском | Парная разница | Выигрыши / потери |", "|---|---:|---:|---:|---:|"] for key, label in (("all", "Все"), ("early", "Ранняя половина"), ("late", "Поздняя половина")): row = result[key] n, paired = row["positive_groups"], row["paired"] lines.append(f"| {label}, {n} | {pct(row['ordinary_hits']/n)} | {pct(row['character_hits']/n)} | " f"{delta(paired)} | {paired['wins']} / {paired['losses']} |") p50, p95 = (f"{item:.2f}".replace(".", ",") for item in result["cpu_ms_p50_p95"]) lines.extend(["", f"Символьный поиск нашёл дубль за пределами обоих исходных списков в " f"{result['labelled_gold_exclusive_to_character_list']} группах. После слияния такие дубли остались в " f"{result['exclusive_gold_retained_in_fusion']} группах.", "", f"При загруженном индексе и готовых исходных списках дополнительный поиск и слияние заняли " f"{p50} / {p95} мс p50 / p95 на {result['cpu']} в одном потоке. " f"На всех {result['identical_rankings_verified']} запросах списки совпали с прямым расчётом. " "Замер охватывает попадание дубля в список до переранжирования. Выборка повторно использует уже " "известный тест V4. [CPU-бенчмарк V4](../../10-v4-cpu/REPORT.md)", "", "## Воспроизведение", "", "Поместите четыре Python-файла дополнения рядом. Используйте архив LibreOffice и сохранённые результаты V4. " "Скрипт сверяет замороженное разбиение, порядок кандидатов и оценки повторной выборки. " "[Воспроизведение V4](../../10-v4-cpu/REPRODUCE.md)", "", "~~~powershell", "python -B study_title_char_transfer.py --holdout $transfer --run $run --out ./title-character-transfer", "~~~", "", "[Агрегированные результаты](results.json)", ""]) return "\n".join(lines)
if __name__ == "__main__": cli = ArgumentParser(description=__doc__) for name in ("holdout", "run", "out"): cli.add_argument(f"--{name}", required=True, type=Path) cli.add_argument("--publish", action="store_true") args = cli.parse_args() with threadpool_limits(limits=1): result = transfer(args.holdout, args.run) args.out.mkdir(parents=True, exist_ok=True) report, metrics = args.out / "REPORT.md", args.out / "results.json" report.write_bytes(render(result).encode()) metrics.write_bytes(stable_rows(result)) if args.publish: script = Path(__file__).resolve() helpers = ("study_title_char_retrieval.py", "study_historical_fusion.py", "verify_webkit_statistics.py") sources = {filename: script.with_name(filename) for filename in (script.name, *helpers)} publish({"REPORT.md": report, "results.json": metrics, **sources}, stage=STAGE, title="LibreOffice. Перенос символьного поиска", message="Publish verified LibreOffice character retrieval transfer")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122"""Check the release statistics from frozen labels and per-query rankings."""
from math import isclose, isfinitefrom statistics import fmean, median, quantiles
import numpy as np
from bugdedup import SYSTEMS
PAIRED_BOOTSTRAP_SEED = 73011
def latency(times): if len(times) < 2 or any(not isfinite(value) or value < 0 for value in times): raise ValueError("The CPU timing samples are incomplete or invalid") return [median(times), quantiles(times, n=20, method="inclusive")[-1]]
def paired_summary(model, baseline): differences = np.fromiter((int(left) - int(right) for left, right in zip(model, baseline, strict=True)), dtype=np.int8) total = len(differences) if total == 0: raise ValueError("The paired test requires both positive and negative groups") wins = int(np.count_nonzero(differences == 1)) losses = int(np.count_nonzero(differences == -1)) ties = total - wins - losses
rng = np.random.default_rng(PAIRED_BOOTSTRAP_SEED) resampled = np.empty(10_000) for batch in resampled.reshape(100, 100): paired_draws = rng.integers(total, size=(len(batch), total)) batch[:] = differences[paired_draws].sum(axis=1) / total interval = quantiles(resampled.tolist(), n=40, method="inclusive")
# Convolve the empirical three-point distribution once per group to remove Monte Carlo error. probabilities = (losses / total, ties / total, wins / total) mass = np.array([1.0]) for _ in range(total): mass = np.convolve(mass, probabilities) cumulative = np.cumsum(mass) / mass.sum() exact = [(int(i) - total) / total for i in cumulative.searchsorted([0.025, 0.975])] return {"delta": (wins - losses) / total, "ci95": [interval[0], interval[-1]], "wins": wins, "losses": losses, "ties": ties}, exact
def check(label, actual, expected): if isinstance(actual, (list, tuple)) and isinstance(expected, (list, tuple)) and len(actual) == len(expected): for index, (left, right) in enumerate(zip(actual, expected, strict=True)): check(f"{label}[{index}]", left, right) elif isinstance(actual, float) and isinstance(expected, (int, float)): if not isclose(actual, expected, rel_tol=0, abs_tol=1e-12): raise ValueError(f"Independent audit disagrees with {label}") elif actual != expected: raise ValueError(f"Independent audit disagrees with {label}")
def candidate_coverage(positive): shared_gold, missed_fusion, missed_retrieval = [], 0, 0 for record, gold in positive: pool = {entry["id"] for entry in record["rrf"]} source = {entry["id"] for method in ("bm25", "e5") for entry in record[method]} if not pool <= source: raise ValueError("A shared candidate has no source ranking") from_pool, from_source = gold & pool, gold & source shared_gold.append(from_pool) missed_fusion += bool(from_source) and not from_pool missed_retrieval += not from_source return {"in_shared_pool": sum(map(bool, shared_gold)), "lost_at_fusion": missed_fusion, "outside_both_source_lists": missed_retrieval}, shared_gold
def verify(rows, predictions, thresholds, champion, saved): by_id = {record["id"]: record for record in predictions} if len(by_id) != len(predictions) or len(rows) != len(by_id) or {row["id"] for row in rows} != by_id.keys(): raise ValueError("The paired audit requires exactly one ranking for each frozen query") positive = [(by_id[row["id"]], set(row["gold"])) for row in rows if row["gold"]] negative = [by_id[row["id"]] for row in rows if not row["gold"]] if not positive or not negative: raise ValueError("The paired test requires both positive and negative groups") check("champion", champion, saved["champion"])
coverage, shared_gold = candidate_coverage(positive) accepted, counts, ranking_losses = {}, {}, {} for system in SYSTEMS: threshold = thresholds[system] offers = {issue: {entry["id"] for entry in record[system][:5] if threshold is not None and entry["score"] >= threshold} for issue, record in by_id.items()} correct = [bool(offers[record["id"]] & gold) for record, gold in positive] false = [bool(offers[record["id"]]) for record in negative] hits5 = [{entry["id"] for entry in record[system][:5]} & gold for record, gold in positive] conditional = [len(hit & shared) / len(shared) for hit, shared in zip(hits5, shared_gold, strict=True) if shared] found_in_list = sum(any(entry["id"] in gold for entry in record[system]) for record, gold in positive) reached_top5, correct_total = sum(map(bool, hits5)), sum(correct) times = [record["ms"][system] for record in by_id.values()] accepted[system] = {"gated_hit5": correct, "fpr": false} counts[system] = {"correct_positive_groups": correct_total, "negative_groups_with_offer": sum(false)} ranking_losses[system] = {"absent_from_ranked_list": len(positive) - found_in_list, "ranked_below_five": found_in_list - reached_top5, "stopped_at_threshold": reached_top5 - correct_total} observed = {"positives": len(correct), "negative_queries": len(false), "gated_hit5": correct_total / len(correct), "hit5": reached_top5 / len(positive), "positive_in_shared_pool": coverage["in_shared_pool"], "recall5": fmean(len(hit) / len(gold) for hit, (_, gold) in zip(hits5, positive, strict=True)), "conditional_recall5_in_pool": fmean(conditional) if conditional else None, "fpr": sum(false) / len(false), "ms_p50_p95": latency(times)} for metric, value in observed.items(): check(f"{system}/{metric}", value, saved["systems"][system][metric])
exact_intervals = {} for system in (name for name in SYSTEMS if name != "bugdedup"): exact_intervals[system] = {} for metric, model in accepted["bugdedup"].items(): comparison, exact = paired_summary(model, accepted[system][metric]) stored = saved["paired_against_each"][system][metric] exact_intervals[system][metric] = exact for key, value in comparison.items(): check(f"{system}/{metric}/{key}", value, stored[key]) if system == champion: check(f"champion/{metric}/{key}", value, saved[f"paired_{metric}"][key]) return {"counts": counts, "exact_percentile_ci95": exact_intervals, "candidate_coverage": coverage, "positive_group_losses": ranking_losses}README.md+2
stages/12-v5-mail-cpu/title-character-transfer/REPORT.mdAdded+23
stages/12-v5-mail-cpu/title-character-transfer/results.jsonAdded+1
stages/12-v5-mail-cpu/title-character-transfer/study_historical_fusion.pyAdded+149
stages/12-v5-mail-cpu/title-character-transfer/study_title_char_retrieval.pyAdded+173
stages/12-v5-mail-cpu/title-character-transfer/study_title_char_transfer.pyAdded+108
stages/12-v5-mail-cpu/title-character-transfer/verify_webkit_statistics.pyAdded+122