Publish verified V8 chronological context preparation, code, and aggregate evidence
Browse filesFiles changed (7)
- README.md+2
- stages/24-v8-context-preparation/REPORT.mdAdded+25
- stages/24-v8-context-preparation/audit_v8_training_contexts.pyAdded+65
- stages/24-v8-context-preparation/ranker_v8.pyAdded+121
- stages/24-v8-context-preparation/study_historical_shortlists.pyAdded+147
- stages/24-v8-context-preparation/training_contexts_v8.pyAdded+63
- stages/24-v8-context-preparation/v8-training-context-coverage.jsonAdded+1
74 unmodified lines75767774 unmodified lines- [BugDedup V7. Короткий список кандидатов](stages/22-v7-launchpad-cpu/small-archive/REPORT.md)- [BugDedup V7. Короткие списки на исторических тикетах](stages/22-v7-launchpad-cpu/small-archive/historical/REPORT.md)74 unmodified lines757677787974 unmodified lines- [BugDedup V7. Короткий список кандидатов](stages/22-v7-launchpad-cpu/small-archive/REPORT.md)- [BugDedup V7. Короткие списки на исторических тикетах](stages/22-v7-launchpad-cpu/small-archive/historical/REPORT.md)- [BugDedup V8. Подготовка списков разных размеров](stages/24-v8-context-preparation/REPORT.md)
12345678910111213141516171819202122232425# BugDedup V8. Уверенность на списках разных размеров
На независимом Launchpad V7 находила больше размеченных целей в первой пятёрке до порога, чем по отдельности E5 и MiniLM. После порога она показывала меньше верных ссылок. При проекции исторических запросов на 1, 2, 4 и 8 кандидатов V7 воздерживалась во всех случаях. Это мотивирует изменить оценку уверенности и проверить её на другом наборе данных. [Тест Launchpad](https://huggingface.co/datasets/sup2ch/bugdedup-benchmarks/blob/e181d4088ee3a86def076d54bab5e81d6c6b3c88/stages/22-v7-launchpad-cpu/REPORT.md) · [Историческая диагностика](https://huggingface.co/datasets/sup2ch/bugdedup-benchmarks/blob/5da0ca478219917a8060bb54ab831148fb16077d/stages/22-v7-launchpad-cpu/small-archive/historical/REPORT.md)
Вариант использует тот же тип ранжировщика и порядок его кандидатов. Логистическая оценка проверяет вероятность присутствия размеченной цели в первой пятёрке. Она получает число кандидатов, прямые признаки сходства текстов и ограниченные преобразования оценок ранжировщика. Признак второго кандидата отличает единственный результат от списка с конкурирующим результатом. Хронология и группы нужны для допуска и контроля данных. Они не подаются в модель как признаки.
Для каждого исторического запроса строим исходный список кандидатов и короткие списки из 1, 2, 4, 8 и 16 более ранних записей, когда столько записей есть. Если исходный список содержит размеченную цель, в одних проекциях она присутствует. В других проекциях берём только кандидатов вне известной группы запроса. Это даёт короткие списки как с видимой целью, так и без неё. Тексты и календарные даты остаются исходными. E5 и BM25 считают признаки на каждом проецируемом архиве, включая изменение статистик BM25. При обучении ранжировщика фолда исключаем известные группы запросов проверочного фолда и связанные метки. Если в пятёрке отсутствует размеченная цель и хотя бы один статус кандидата неизвестен, не используем такую проекцию для обучения уверенности. При доступности обоих типов наблюдений полный список получает половину веса запроса, а компактные списки делят оставшуюся половину.
До обучения фиксируем независимый от разработочной выборки корпус, разбиение и даты. Выборка калибровки отделена по группам и времени. К порогам на независимом тесте не прикасаемся. Сравнение использует BM25, E5-small-v2 и MiniLM-L6-v2 на тех же запросах. Для сравнения переранжирования V8 и MiniLM имеют один список кандидатов. Основной показатель остаётся долей положительных запросов с верной предложенной ссылкой в первой пятёрке при сопоставимых ложных предложениях. Отдельно показываем Recall@5 до порога, парные интервалы, CPU p50/p95 и размер. Короткие учебные проекции не служат основанием для выпуска весов.
## Проверка подготовки на истории Core
Проверка на CPU обработала все 787 групп исторического окна обучения V7. У 244 групп в полном исходном списке была подтверждённая цель. Подготовлено 5 155 коротких проекций. Для каждого из пяти размеров получилось 244 случая с видимой целью и 787 без размеченной цели среди кандидатов. Проекции одной группы зависимы. Для оценки качества и порогов понадобятся отдельные данные. На этих наблюдениях V8 не обучали и метрики нового теста не считали. [Сводка покрытия](v8-training-context-coverage.json) · [Код подготовки](training_contexts_v8.py) · [Код оценки](ranker_v8.py)
В искусственных примерах проверены порядок по времени, исключение более поздних и одновременных тикетов, скрытие групп проверочного фолда и веса проекций. Круг сохранения и загрузки использовал ранжировщик V7 и заданные вручную коэффициенты уверенности. На CPU он воспроизвёл ожидаемый порядок для списков из нуля, одного и двух кандидатов.
## Воспроизведение
Аудит использует архив и зафиксированное разбиение V7. Исходники этого этапа размещаются в `work/iteration-08`. [Команды и архив кода V7](../22-v7-launchpad-cpu/REPORT.md) · [Код аудита](audit_v8_training_contexts.py)
~~~powershell$stage = 'Z:/llmmss/bugdedup/indexes/iteration-07'$scratch = 'Z:/llmmss/bugdedup/tmp'python -B work/iteration-08/audit_v8_training_contexts.py --first work --core work/iteration-02/ordinary --holdout (Join-Path $stage 'launchpad-holdout') --development (Join-Path $stage 'core-development') --cache (Join-Path $stage 'core-development-indexes') --run (Join-Path $stage 'launchpad-benchmark') --scratch $scratch --threads 2 --out v8-training-context-coverage.json~~~1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465"""Count V8 training observations on an already verified historical archive without fitting the model."""
from argparse import ArgumentParserfrom collections import Counterfrom pathlib import Path
import numpy as npfrom threadpoolctl import threadpool_limits
from bench_launchpad import LOCK, historical_indexfrom encoder import Encoderfrom freeze_live_mozilla import read, require, stable_rows, storefrom historical_launchpad import checked_planfrom prepare import digestfrom training_contexts_v8 import COMPACT_SIZES, build_training_contexts
def tally(counter, query): counter["observations"] += 1 has_target = bool(np.any(query.known_mask & query.labels)) all_known = bool(query.known_mask.all()) counter["visible_known_target"] += has_target counter["all_known_without_target"] += all_known and not has_target counter["has_unknown_candidate"] += not all_known
def audit(args): plan, proof = checked_plan(args.core, args.holdout, args.development) lock_path = args.run / LOCK identity = read(lock_path) archive, marker = historical_index(args, identity, plan, "train") require(identity["holdout"] == plan["holdout"] and identity["development_plan_sha256"] == proof["development_plan_sha256"], "The historical rehearsal must use the verified development plan") rows = plan["phases"]["train"]["queries"] encoder = Encoder(args.first, "e5", args.threads) full = Counter() compact = {str(size): Counter() for size in COMPACT_SIZES} seen = set() for number, group in enumerate(build_training_contexts(archive, rows, encoder, args.scratch), 1): require(group.full.group not in seen, "Two observations share a historical query group") seen.add(group.full.group) tally(full, group.full) for projection in group.compact: tally(compact[str(len(projection.labels))], projection) if number % 100 == 0: print(f"Historical V8 preparation audit {number}/{len(rows)}", flush=True) require(len(seen) == len(rows), "The rehearsal missed historical query groups") return {"role": "historical feature preparation rehearsal without fitting or test scoring", "groups": len(seen), "full": full, "compact": compact, "historical_archive_sha256": marker["identity"]["archive"], "historical_plan_sha256": proof["development_plan_sha256"], "existing_run_lock_sha256": digest(lock_path)}
if __name__ == "__main__": parser = ArgumentParser(description=__doc__) for field in ("first", "core", "holdout", "development", "cache", "run", "scratch", "out"): parser.add_argument(f"--{field}", type=Path, required=True) parser.add_argument("--threads", type=int, default=2) args = parser.parse_args() require(args.threads > 0, "CPU thread count must be positive") with threadpool_limits(limits=1, user_api="blas"), threadpool_limits(limits=1, user_api="openmp"): result = stable_rows(audit(args)) store(args.out, result) print(result.decode("utf-8").rstrip())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121"""Learn shortlist confidence from full and compact chronological training contexts."""
from dataclasses import dataclass, replace
import numpy as npfrom scipy.special import expitfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import StratifiedKFoldfrom sklearn.preprocessing import StandardScaler
from freeze_live_mozilla import read, require, stable_rows, storefrom ranker_v3 import FOLD_SEED, TOP_Kfrom ranker_v4 import DecisionQueryfrom ranker_v6 import NullRanker, OUTPUTS as RANKING_FILESfrom ranker_v7 import ShortlistRanker, candidate_logits, shortlist_evidence
GATE = "context-confidence.json"OUTPUTS = (*RANKING_FILES, GATE)FORMAT = "context-confidence-v1"FEATURES = ("log_candidate_count", "has_runner_up", "shortlist_mass", "best_vs_null", "bounded_rank_gap", "chosen_e5", "best_e5", "e5_gap", "chosen_bm25", "chosen_title_bigrams", "chosen_title_trigrams", "chosen_text_overlap", "chosen_equal_title_terms")
@dataclass(frozen=True)class TrainingContexts: full: DecisionQuery compact: tuple[DecisionQuery, ...]
def confidence_features(matrix, profile, logits): order, evidence = shortlist_evidence(matrix, profile, logits) first = matrix[order[0]] # Bound list-dependent scores so an unfamiliar shortlist length cannot # swamp the direct similarities solely through an extreme raw logit. return order, np.array([evidence[0], len(logits) > 1, expit(evidence[1]), expit(evidence[2]), np.tanh(evidence[3]), first[1], evidence[4], evidence[5], first[0], first[10], first[11], first[18], first[19]], dtype=np.float64)
def confidence_example(ranking, query): if not query.known_mask.any(): return None logits = candidate_logits(ranking, query.matrix, query.retrieval_profile) order, features = confidence_features(query.matrix, query.retrieval_profile, logits) shortlist = order[:TOP_K] known = query.known_mask[shortlist] hit = bool(np.any(known & query.labels[shortlist].astype(bool))) return (features, hit) if hit or known.all() else None
def query_examples(ranking, contexts): full = confidence_example(ranking, contexts.full) compact = [case for query in contexts.compact if (case := confidence_example(ranking, query)) is not None] full_weight = 0.5 if compact else 1.0 if full is not None: yield *full, full_weight compact_weight = (1.0 - full_weight if full is not None else 1.0) for case in compact: yield *case, compact_weight / len(compact)
class ContextConfidenceRanker(ShortlistRanker): """Reuse the ranking and estimate its acceptance with bounded and direct evidence."""
def __init__(self, ranking, weights, bias): self.ranking = ranking self.weights = np.asarray(weights, dtype=np.float64) self.bias = float(bias) require(self.weights.shape == (len(FEATURES),) and np.isfinite(self.weights).all() and np.isfinite(self.bias), "Invalid context confidence parameters")
def score(self, matrix, profile): logits = candidate_logits(self.ranking, matrix, profile) order, evidence = confidence_features(matrix, profile, logits) ranked = logits[order] confidence = self.bias + evidence @ self.weights return order, expit(confidence + (ranked - ranked[0]))
@classmethod def fit(cls, contexts): usable = [row for row in contexts if row.full.known_mask.any()] full = [row.full for row in usable] require(len(full) == len({query.group for query in full}) and all(query.group == row.full.group for row in usable for query in row.compact), "Full and compact observations must belong to the same unique query group") strata = np.asarray([np.any(query.labels[query.known_mask]) for query in full], dtype=bool) require(strata.sum() >= 9 and (~strata).sum() >= 9, "Training needs both outcomes on independent groups") folds = StratifiedKFold(n_splits=3, shuffle=True, random_state=FOLD_SEED + 8) examples = [] for train, validation in folds.split(full, strata): hidden = {full[i].group for i in validation} independent = [] for i in train: query = full[i] allowed = np.asarray([group not in hidden for group in query.candidate_groups], dtype=bool) independent.append(replace(query, known_mask=query.known_mask & allowed)) ranker = NullRanker.fit(independent) for i in validation: examples.extend(query_examples(ranker, usable[i])) require(examples, "No verified confidence observations survived cross-fitting") features, targets, weights = zip(*examples, strict=True) require(any(targets) and not all(targets), "Confidence fitting needs both verified outcomes") scaler = StandardScaler().fit(features, sample_weight=weights) model = LogisticRegression(C=1.0, random_state=FOLD_SEED + 8, max_iter=500) model.fit(scaler.transform(features), targets, sample_weight=weights) coefficients = model.coef_[0] / scaler.scale_ bias = model.intercept_[0] - scaler.mean_ @ coefficients return cls(NullRanker.fit(full), coefficients, bias)
def save(self, folder): self.ranking.save(folder) store(folder / GATE, stable_rows({"format": FORMAT, "features": FEATURES, "weights": self.weights.tolist(), "bias": self.bias}))
@classmethod def load(cls, folder): saved = read(folder / GATE) require(saved["format"] == FORMAT and tuple(saved["features"]) == FEATURES, "Unsupported context confidence format") return cls(NullRanker.load(folder), saved["weights"], saved["bias"])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147"""Stress frozen V7 and its baselines on short contexts projected from 2021 development."""
from argparse import ArgumentParserfrom collections import Counterfrom pathlib import Pathfrom tempfile import TemporaryDirectory
import numpy as npfrom threadpoolctl import threadpool_limits
from bench_launchpad import LOCK, checked_calibration, fitted_state, historical_indexfrom bugdedup import Archive, content, retrievefrom encoder import Encoderfrom freeze_live_mozilla import read, require, stable_rows, storefrom historical_launchpad import checked_planfrom ranker_v7 import ShortlistRankerfrom report_live import records
SIZES = (1, 2, 4, 8)METHODS = ("bm25", "e5", "mini", "bugdedup")PROJECT = "compact"
class FixedQueryEncoder: """Reuse the actual E5 query vector within a single simulation."""
def __init__(self, text, encoder): self.text = text self.vector = encoder.embed_query(text)
def embed_query(self, text): require(text == self.text, "A cached query vector was requested for another text") return self.vector
def select(case, prediction, historical): gold = set(case["gold"]) query = historical.docs[historical.ids[case["id"]]] source = [row["id"] for row in prediction["rrf"]] require(len(source) == len(set(source)) and all(historical.docs[historical.ids[key]]["time"] < query["time"] for key in source), "Historical source ranks contain a repeated or late candidate") visible = [key for key in source if key in gold] if gold and not visible: return None, "known_target_missing_from_original_shared_list" target = visible[0] if visible else None distractors = [key for key in source if key not in gold and historical.docs[historical.ids[key]]["group"] != query["group"]] ordered = ([target] if target else []) + distractors if len(ordered) < max(SIZES): return None, "not_enough_earlier_out_of_group_candidates" return (query, target, ordered[:max(SIZES)]), None
def projected_archive(historical, keys, scratch): indices = sorted(historical.ids[key] for key in keys) (scratch / f"{PROJECT}.json").write_bytes(stable_rows([historical.docs[index] for index in indices])) np.save(scratch / f"{PROJECT}.e5.npy", historical.vectors[indices], allow_pickle=False) return Archive(scratch, PROJECT)
def ranked_methods(archive, query, encoder, model, original): received = retrieve(archive, query, encoder) require(received["size"] == len(archive.docs) and len(received["rrf"][0]) == len(archive.docs), "A small shared list lost a historically available candidate") rank, values = model.predict(archive, query, received)
def results(rows, scores): return [(archive.docs[row]["id"], float(score)) for row, score in zip(rows, scores, strict=True)]
mini = [(entry["id"], float(entry["score"])) for entry in original["mini"] if entry["id"] in archive.ids] require({key for key, _ in mini} == set(archive.ids) and len(mini) == len(archive.ids), "The MiniLM shared scores are incomplete") return {"bm25": results(*received["bm25"]), "e5": results(*received["e5"]), "mini": mini, "bugdedup": results(rank, values)}
def evaluate(args): plan, proof = checked_plan(args.core, args.holdout, args.development) identity = read(args.run / LOCK) fitted = fitted_state(args.run, identity) calibration, checksum = checked_calibration(args.run, fitted) historical, marker = historical_index(args, identity, plan, "dev") require(plan["holdout"] == identity["holdout"] and calibration["identity"]["index"] == marker, "The previous calibration used a different historical archive") rows = plan["phases"]["dev"]["queries"] predictions = records(args.run / "dev-predictions.jsonl", rows) require(len({historical.docs[historical.ids[row["id"]]]["group"] for row in rows}) == len(rows), "The development diagnostic needs independent query groups") thresholds = calibration["matched"]["thresholds"] encoder, model = Encoder(args.first, "e5", args.threads), ShortlistRanker.load(args.run / "fitted") results = {size: {method: Counter() for method in METHODS} for size in SIZES} different = {size: {method: Counter() for method in METHODS if method != "bugdedup"} for size in SIZES} omitted, included = Counter(), Counter() with TemporaryDirectory(prefix="bugdedup-context-", dir=args.scratch) as temp: scratch = Path(temp) for number, (case, prediction) in enumerate(zip(rows, predictions, strict=True), 1): if number % 40 == 0: print(f"Historical archive projections {number - 1}/{len(rows)}", flush=True) selected, reason = select(case, prediction, historical) branch = "positive" if case["gold"] else "negative" if reason: omitted[f"{branch}:{reason}"] += 1 continue query, target, keys = selected vector = FixedQueryEncoder(content(query), encoder) included[branch] += 1 for size in SIZES: compact = projected_archive(historical, keys[:size], scratch) rankings = ranked_methods(compact, query, vector, model, prediction) outcomes = {} for method, values in rankings.items(): top = values[:5] threshold = thresholds[method] offered = {key for key, score in top if threshold is not None and score >= threshold} counts = results[size][method] if target: counts["recall5_hits"] += any(key == target for key, _ in top) counts["correct_offers"] += target in offered outcomes[method] = target in offered else: counts["false_offers"] += bool(offered) outcomes[method] = bool(offered) event = "correct_offer" if target else "false_offer" for method, counts in different[size].items(): counts[f"{event}_v7_only"] += outcomes["bugdedup"] and not outcomes[method] counts[f"{event}_baseline_only"] += outcomes[method] and not outcomes["bugdedup"] require(sum(included.values()) + sum(omitted.values()) == len(rows) and included.keys() == {"positive", "negative"}, "Projection accounting does not cover the historical development set") return {"calibration_sha256": checksum, "development_plan_sha256": proof["development_plan_sha256"], "historical_queries": len(rows), "included": included, "omitted": omitted, "selected_label_retention": "one existing earlier gold in the original shared pool when available", "roles": "diagnostic on historical calibration groups at their original locked thresholds", "counts": {str(size): results[size] for size in SIZES}, "discordant_queries": {str(size): different[size] for size in SIZES}}
if __name__ == "__main__": parser = ArgumentParser(description=__doc__) for field in ("first", "core", "holdout", "development", "cache", "run", "scratch", "out"): parser.add_argument(f"--{field}", type=Path, required=True) parser.add_argument("--threads", type=int, default=2) args = parser.parse_args() require(args.threads > 0, "CPU thread count must be positive") with threadpool_limits(limits=1, user_api="blas"), threadpool_limits(limits=1, user_api="openmp"): result = stable_rows(evaluate(args)) store(args.out, result) print(result.decode("utf-8").rstrip())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263"""Build full and compact candidate observations from historical query groups."""
from pathlib import Pathfrom tempfile import TemporaryDirectory
import numpy as np
from bugdedup import content, retrievefrom freeze_live_mozilla import requirefrom ranker import pair_matrixfrom ranker_v4 import DecisionQuery, retrieval_profilefrom ranker_v8 import TrainingContextsfrom study_historical_shortlists import FixedQueryEncoder, projected_archive
COMPACT_SIZES = (1, 2, 4, 8, 16)
def labeled_context(archive, query, retrieved, gold): shared = retrieved["rrf"][0] docs = [archive.docs[row] for row in shared] require(all(doc["time"] < query["time"] for doc in docs), "A training candidate was not available at filing") groups = tuple(doc["group"] for doc in docs) labels = np.array([doc["id"] in gold for doc in docs], dtype=bool) known = labels | np.array([group != query["group"] for group in groups], dtype=bool) return DecisionQuery(pair_matrix(archive, query, retrieved), labels, known, query["group"], groups, retrieval_profile(retrieved))
def compact_candidates(archive, query, retrieved, gold): shared = [archive.docs[row] for row in retrieved["rrf"][0]] target = next((doc["id"] for doc in shared if doc["id"] in gold), None) distractors = [doc["id"] for doc in shared if doc["group"] != query["group"] and doc["id"] not in gold] for size in COMPACT_SIZES: if target is not None and len(distractors) >= size - 1: yield [target, *distractors[:size - 1]] if len(distractors) >= size: yield distractors[:size]
def build_training_contexts(archive, rows, encoder, scratch): """Keep the original cutoff, while projecting both visible and absent targets.""" with TemporaryDirectory(prefix="bugdedup-v8-train-", dir=scratch) as temp: directory = Path(temp) seen = set() for row in rows: query = archive.docs[archive.ids[row["id"]]] gold = set(row["gold"]) require(query["group"] not in seen and all(key in archive.ids and archive.docs[archive.ids[key]]["time"] < query["time"] and archive.docs[archive.ids[key]]["group"] == query["group"] for key in gold), "Training requires distinct query groups with only earlier in-group targets") seen.add(query["group"]) query_vector = FixedQueryEncoder(content(query), encoder) received = retrieve(archive, query, query_vector) full = labeled_context(archive, query, received, gold) compact = [] for keys in compact_candidates(archive, query, received, gold): projection = projected_archive(archive, keys, directory) small = retrieve(projection, query, query_vector) require(len(small["rrf"][0]) == len(keys), "A compact training context lost one of its earlier candidates") compact.append(labeled_context(projection, query, small, gold)) yield TrainingContexts(full, tuple(compact))1{"compact":{"1":{"all_known_without_target":787,"has_unknown_candidate":0,"observations":1031,"visible_known_target":244},"16":{"all_known_without_target":787,"has_unknown_candidate":0,"observations":1031,"visible_known_target":244},"2":{"all_known_without_target":787,"has_unknown_candidate":0,"observations":1031,"visible_known_target":244},"4":{"all_known_without_target":787,"has_unknown_candidate":0,"observations":1031,"visible_known_target":244},"8":{"all_known_without_target":787,"has_unknown_candidate":0,"observations":1031,"visible_known_target":244}},"existing_run_lock_sha256":"554ffef163f5d676520ac601ffe2779395c3d552d326885d32ff89228aa5300a","full":{"all_known_without_target":529,"has_unknown_candidate":43,"observations":787,"visible_known_target":244},"groups":787,"historical_archive_sha256":"32912b27d5f83ce403ec923260ad0b56e6f736c11d9c59da5c1fd5959d55e9ef","historical_plan_sha256":"27980b9c96964178b6ccb8bd43d4cc5fd6b0de6fd5590605e11f8ad33d91e7ef","role":"historical feature preparation rehearsal without fitting or test scoring"}README.md+2
stages/24-v8-context-preparation/REPORT.mdAdded+25
stages/24-v8-context-preparation/audit_v8_training_contexts.pyAdded+65
stages/24-v8-context-preparation/ranker_v8.pyAdded+121
stages/24-v8-context-preparation/study_historical_shortlists.pyAdded+147
stages/24-v8-context-preparation/training_contexts_v8.pyAdded+63
stages/24-v8-context-preparation/v8-training-context-coverage.jsonAdded+1