#!/bin/zsh set -eu set -o pipefail : "${LAB:?}" "${HOME:?}" "${RESULTS:?}" "${LAB_PYTHON:?}" mkdir -p "$LAB/logs" "$LAB/cache/hf" "$RESULTS" cd "$LAB" export HF_HOME="$LAB/cache/hf" export HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_HUB_DISABLE_TELEMETRY=1 export HF_HUB_DISABLE_XET=1 TOKENIZERS_PARALLELISM=false export OMP_NUM_THREADS=8 OPENBLAS_NUM_THREADS=8 MKL_NUM_THREADS=8 VECLIB_MAXIMUM_THREADS=8 export PIP_DISABLE_PIP_VERSION_CHECK=1 # Install only in the runner's network-denied stage. Rebuild with the supplied # Python so retries never start a partially installed application environment. setup_stage=venv setup_started=$SECONDS TRAPEXIT() { local run_rc=$? "$LAB_PYTHON" -I - "$run_rc" "$setup_stage" "$(( SECONDS - setup_started ))" <<'PY' import json import os from pathlib import Path import re import sys lab, out = Path(os.environ['LAB']), Path(os.environ['RESULTS']) rc, stage, seconds = int(sys.argv[1]), sys.argv[2], int(sys.argv[3]) (out / 'run-status.json').write_text(json.dumps({ 'status': 'complete' if rc == 0 else 'failed', 'exit_code': rc, 'stage': stage, 'elapsed_seconds_integer': seconds}) + '\n') parts = [] for name in ('venv.txt', 'pip-install.txt', 'pip-check.txt'): path = lab / 'logs' / name if path.exists(): with path.open('rb') as stream: stream.seek(max(0, path.stat().st_size - 16000)) parts.append(name + '\n' + stream.read().decode('utf-8', errors='replace')) text = '\n\n'.join(parts) for key, replacement in [('RESULTS', '[RESULTS]'), ('HOME', '[HOME]'), ('LAB', '[LAB]')]: text = text.replace(os.environ[key], replacement) text = re.sub(r'/Users/[^/\s]+', '[USER]', text) (out / 'setup-log.txt').write_text(text) if rc and stage != 'measurement': (out / 'outcome.json').write_text(json.dumps({ 'status': 'failed', 'reason': 'offline dependency setup failed', 'stage': stage}) + '\n') PY return "$run_rc" } for setup_log in venv pip-install pip-check; do : > "$LAB/logs/$setup_log.txt" done /usr/bin/time -l "$LAB_PYTHON" -I -m venv --clear "$LAB/venv" \ > "$LAB/logs/venv.txt" 2>&1 setup_stage=pip-install /usr/bin/time -l "$LAB/venv/bin/python" -I -m pip install \ --no-index --find-links "$LAB/wheels" --only-binary=:all: --no-deps \ --require-hashes --no-compile -r "$LAB/requirements.lock" \ > "$LAB/logs/pip-install.txt" 2>&1 setup_stage=pip-check /usr/bin/time -l "$LAB/venv/bin/python" -I -m pip check \ > "$LAB/logs/pip-check.txt" 2>&1 setup_stage=measurement cat > "$LAB/measure.py" <<'PY' import csv import hashlib import importlib.metadata import io import json import math import os from pathlib import Path import re import sys import time import traceback import unicodedata LAB = Path(os.environ['LAB']) RESULTS = Path(os.environ['RESULTS']) MODEL_REV = '97b0c614be4d77ee51c0cef4e5f07c00f9eb65b3' MDN_REV = '40dcd50c6a9bea4f47a30c203af4b4fa3579bb26' INSTRUCTION = 'Instruct: Given a web search query, retrieve relevant passages that answer the query\nQuery: ' GROUPS = ('identifier', 'symptom', 'history') ARMS = ('bm25', 'dense', 'hybrid') RUN_ID = time.strftime('%Y%m%dT%H%M%SZ', time.gmtime()) STAGES = {} # Written before inference; no query generation or selection based on rankings. # Each row is a distinct status-code definition, checked against pinned MDN. ITEMS = [ ('401', 'アクセス先で有効なログイン情報を送れておらず、認証情報を付けて送り直すよう求められます'), ('403', 'サーバーは要求を理解していますが、その利用者には操作する権限がなく、認証し直しても拒否されます'), ('404', '指定した場所のページが見つからず、一時的なのか今後も戻らないのかは分かりません'), ('405', 'その操作方法をサーバーは知っていますが、このページではその方法での要求を受け付けません'), ('406', '利用者が受け入れる形式や言語を指定したところ、サーバーに対応する表現が一つもありません'), ('407', 'アクセス先ではなく途中のプロキシが利用者の認証情報を求めており、それを付けて送り直す必要があります'), ('408', '通信を受けるサーバー側で待機時間が過ぎ、利用者からの要求が完了しないまま接続を閉じられました'), ('409', 'アップロードしようとしたファイルがサーバー上の現在の版と食い違い、そのままでは更新を適用できません'), ('410', '以前あったページが恒久的に削除され、同じ場所でまた使える見込みはありません'), ('411', '要求本文の長さを示す項目が送られていないため、サーバーがその長さを明示するよう求めています'), ('412', '更新する前に満たすべき条件をヘッダーで指定しましたが、現在の資料はその条件と一致しません'), ('413', 'アップロードする本文がサーバーの受け入れ上限より大きく、要求を処理してもらえません'), ('414', '検索条件をたくさん付けた結果、送信先のアドレス自体が長すぎてサーバーに拒否されました'), ('415', '送信した本文のデータ形式にサーバーが対応しておらず、その形式のままでは処理できません'), ('416', 'ファイルの一部を取り寄せようとして、実際のファイルの末尾より先の位置を要求してしまいました'), ('417', '要求の期待値を指定するヘッダーにサーバーが応じられず、その指定を外して再送する必要があります'), ('422', '送信したデータは形式も構文も正しいのに、そこに書かれた指示の意味をサーバーが処理できません'), ('428', '同時更新による上書きを防ぐため、サーバーから条件付きの要求を送るよう求められましたが、条件を付けていませんでした'), ('429', '一人の利用者が短時間に何度もアクセスしたため、その利用者の要求回数の制限に達しました'), ('431', '本文や送信先アドレスではなく、Cookieなど要求ヘッダーの一部または全体が大きすぎて拒否されました'), ('500', 'サーバー内部で予期しない例外が起きて要求を処理できず、より具体的な原因の種類も示されていません'), ('502', '中継サーバーが上流から返答を受け取りましたが、その返答が不正で利用者へ正常に渡せません'), ('503', 'サービス全体が保守中または過負荷で一時的に利用できず、準備が整うまで待つ必要があります'), ('504', '中継サーバーが上流の返答を待ち続けましたが、制限時間までに返答が届きませんでした'), ] def scrub(value): for original, replacement in sorted(((str(LAB), '[LAB]'), (str(RESULTS), '[RESULTS]'), (os.environ['HOME'], '[HOME]')), key=lambda x: -len(x[0])): value = value.replace(original, replacement) return re.sub(r'/Users/[^/\s]+', '[USER]', value) def emit(name, value, plain=False): text = value if plain else json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) text = scrub(text) + '\n' if len(text.encode('utf-8')) > 512 * 1024: raise RuntimeError('Result file exceeds 512 KiB: ' + name) (RESULTS / name).write_text(text, encoding='utf-8') def elapsed(start): return round(time.perf_counter() - start, 6) def percentile(values, p): ordered = sorted(values) return ordered[max(0, math.ceil(len(ordered) * p) - 1)] def verify_inputs(): manifest = json.loads((LAB / 'inputs.json').read_text()) if manifest['model_revision'] != MODEL_REV or manifest['mdn_revision'] != MDN_REV: raise RuntimeError('Unexpected input revision') for row in manifest['files']: path = LAB / 'model' / row['file'] if path.is_symlink() or path.stat().st_size != row['bytes']: raise RuntimeError('Model size mismatch') h = hashlib.sha256() if row['hash_kind'] == 'sha256' else hashlib.sha1() if row['hash_kind'] == 'git': h.update(f"blob {row['bytes']}\0".encode()) with path.open('rb') as f: for block in iter(lambda: f.read(1024 * 1024), b''): h.update(block) if h.hexdigest() != row['hash']: raise RuntimeError('Model content mismatch: ' + row['file']) if hashlib.sha256((LAB / 'requirements.lock').read_bytes()).hexdigest() != manifest['requirements_sha256']: raise RuntimeError('Dependency lock changed') if len(manifest['documents']) != 76: raise RuntimeError('Expected all 60 statuses plus 16 predefined headers') return manifest def documents(manifest): docs = [] for row in manifest['documents']: path = LAB / 'mdn' / row['file'] if path.is_symlink() or not path.resolve().is_relative_to(LAB / 'mdn'): raise RuntimeError('Unexpected data path') raw = path.read_bytes() if hashlib.sha256(raw).hexdigest() != row['sha256']: raise RuntimeError('MDN content mismatch') text = raw.decode('utf-8') match = re.match(r'\A---\s*\n(.*?)\n---\s*\n(.*)', text, flags=re.S) if not match: raise RuntimeError('MDN front matter missing') front, body = match.groups() title = re.search(r'^title:\s*(.+)$', front, re.M) slug = re.search(r'^slug:\s*(.+)$', front, re.M) if not title or not slug: raise RuntimeError('MDN title or slug missing') title = title.group(1).strip().strip('"\'') slug = slug.group(1).strip().strip('"\'') # Treat all MDN macros/HTML/code as text, never render or execute them. body = re.sub(r'', ' ', body, flags=re.S) body = re.sub(r'\{\{(.*?)\}\}', lambda m: ' '.join(re.findall(r'["\']([^"\']+)["\']', m.group(1))), body, flags=re.S) body = re.sub(r'\[([^\]]+)\]\([^)]*\)', r'\1', body) body = re.sub(r'<[^>]+>', ' ', body) body = re.sub(r'\s+', ' ', body).strip() doc_id = '/'.join(path.parts[-3:-1]) docs.append({'id': doc_id, 'title': title, 'text': body, 'url': 'https://developer.mozilla.org/ja/docs/' + slug, 'source': f'https://github.com/mdn/translated-content/blob/{MDN_REV}/' + row['file'], 'sha256': row['sha256']}) return sorted(docs, key=lambda x: x['id']) def cases(): output = [] for index, (code, symptom) in enumerate(ITEMS): wrong = ITEMS[(index + 7) % len(ITEMS)][0] queries = { 'identifier': f'HTTP {code} の意味と対応を説明する個別の資料を探したい。', 'symptom': symptom + '。この症状に対応するHTTPエラーの個別説明を探してください。', 'history': f'以前の別件はHTTP {wrong}でした。今回は{symptom}。今回の症状に対応するHTTPエラーの個別説明を探してください。', } for group in GROUPS: output.append({'id': code + '-' + group, 'family': code, 'group': group, 'query': queries[group], 'gold': 'status/' + code, 'distractor': wrong if group == 'history' else None}) return output def run(): started_all = time.perf_counter() emit('outcome.json', {'run_id': RUN_ID, 'status': 'running'}) emit('errors.json', {'run_id': RUN_ID, 'errors': []}) t = time.perf_counter() manifest = verify_inputs() docs = documents(manifest) tests = cases() if len({d['id'] for d in docs}) != 76 or any(q['gold'] not in {d['id'] for d in docs} for q in tests): raise RuntimeError('Corpus or gold document missing') case_hash = hashlib.sha256(json.dumps(tests, ensure_ascii=False, sort_keys=True).encode()).hexdigest() emit('cases.json', {'run_id': RUN_ID, 'sha256': case_hash, 'cases': tests}) emit('corpus.json', {'run_id': RUN_ID, 'revision': MDN_REV, 'documents': [{k: v for k, v in d.items() if k != 'text'} for d in docs], 'license': 'Mozilla Contributors (MDN Web Docs), CC BY-SA 2.5 or later; transformed into text chunks', 'content_license_url': 'https://creativecommons.org/licenses/by-sa/2.5/', 'license_url': 'https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Attrib_copyright_license'}) STAGES['verify_and_read_seconds'] = elapsed(t) # Application code is imported only in the offline run stage. t = time.perf_counter() import numpy as np import torch from transformers import AutoModel, AutoTokenizer from rank_bm25 import BM25Okapi from janome.tokenizer import Tokenizer torch.set_num_threads(8) torch.set_num_interop_threads(1) torch.manual_seed(0) np.random.seed(0) STAGES['library_import_seconds'] = elapsed(t) t = time.perf_counter() tokenizer = AutoTokenizer.from_pretrained(str(LAB / 'model'), local_files_only=True, trust_remote_code=False, padding_side='left') chunks = [] for doc in docs: prefix = doc['title'] + '\n' budget = 384 - len(tokenizer.encode(prefix, add_special_tokens=False)) if budget < 128: raise RuntimeError('Unexpected long document title') tokens = tokenizer(doc['text'], add_special_tokens=False, return_offsets_mapping=True) offsets = tokens['offset_mapping'] for begin in range(0, len(offsets), budget - 64): end = min(begin + budget, len(offsets)) # Unicode character offsets avoid cutting a Japanese character in half. text = prefix + doc['text'][offsets[begin][0]:offsets[end - 1][1]] length = len(tokenizer.encode(text, add_special_tokens=False)) if length > 480: raise RuntimeError('Chunk exceeds the preregistered token ceiling') chunks.append({'doc': doc['id'], 'text': text, 'tokens': length}) if end == len(offsets): break if not (76 <= len(chunks) <= 900): raise RuntimeError('Chunk count outside the preregistered workload bound') for q in tests: if len(tokenizer.encode(INSTRUCTION + q['query'], add_special_tokens=False)) > 512: raise RuntimeError('Query would be truncated') STAGES['common_chunking_seconds'] = elapsed(t) chunk_hash = hashlib.sha256(json.dumps(chunks, ensure_ascii=False, sort_keys=True).encode()).hexdigest() t = time.perf_counter() janome = Tokenizer() def lexical(text): text = unicodedata.normalize('NFKC', text).lower() return [s for s in janome.tokenize(text, wakati=True) if any(c.isalnum() for c in s)] lexical_corpus = [lexical(c['text']) for c in chunks] # Pre-tokenize to avoid rank_bm25's optional multiprocessing tokenizer pool. bm25 = BM25Okapi(lexical_corpus, k1=1.5, b=0.75, epsilon=0.25) STAGES['bm25_build_seconds'] = elapsed(t) t = time.perf_counter() model = AutoModel.from_pretrained(str(LAB / 'model'), local_files_only=True, trust_remote_code=False, use_safetensors=True, dtype=torch.float32, attn_implementation='sdpa') model.to('cpu').eval() STAGES['dense_model_load_seconds'] = elapsed(t) def embed(texts): encoded = tokenizer(texts, padding=True, truncation=False, return_tensors='pt') if encoded['input_ids'].shape[1] > 512: raise RuntimeError('Embedding input exceeds 512 tokens') with torch.inference_mode(): hidden = model(**encoded, use_cache=False).last_hidden_state # All batches are left padded, per the official Qwen example. vectors = torch.nn.functional.normalize(hidden[:, -1, :], p=2, dim=1) values = vectors.float().numpy().copy() if not np.isfinite(values).all(): raise RuntimeError('Non-finite embedding') return values t = time.perf_counter() arrays = [] for start in range(0, len(chunks), 4): arrays.append(embed([c['text'] for c in chunks[start:start + 4]])) vectors = np.concatenate(arrays, axis=0) STAGES['dense_document_embedding_seconds'] = elapsed(t) np.save(LAB / 'document-vectors.npy', vectors, allow_pickle=False) STAGES['dense_vector_index_bytes'] = (LAB / 'document-vectors.npy').stat().st_size def rank_documents(scores, positive_only=False): best = {} best_chunk = {} for idx, score in enumerate(scores): score = float(score) if not math.isfinite(score): raise RuntimeError('Non-finite retrieval score') if positive_only and score <= 0: continue doc = chunks[idx]['doc'] if doc not in best or score > best[doc]: best[doc] = score best_chunk[doc] = idx ranked = sorted(best, key=lambda d: (-best[d], d))[:20] return ranked, best, best_chunk def fuse(dense, sparse): values = {} for ranking in (dense, sparse): for rank, doc in enumerate(ranking, 1): values[doc] = values.get(doc, 0.0) + 1.0 / (60 + rank) return sorted(values, key=lambda d: (-values[d], d))[:20], values # One fixed warm-up is excluded from query latency, never from index time. embed([INSTRUCTION + 'HTTPの資料を検索する']) bm25.get_scores(lexical('HTTPの資料を検索する')) timings = [] first = {} unstable = [] t_queries = time.perf_counter() # Each query measured three times, rotating order without fitting parameters. for round_no in range(3): order = tests[round_no * 24:] + tests[:round_no * 24] for q in order: t = time.perf_counter() sparse, sparse_scores, sparse_chunk = rank_documents(bm25.get_scores(lexical(q['query'])), True) sparse_ms = elapsed(t) * 1000 t = time.perf_counter() query_vector = embed([INSTRUCTION + q['query']])[0] dense, dense_scores, dense_chunk = rank_documents(vectors @ query_vector) dense_ms = elapsed(t) * 1000 t = time.perf_counter() hybrid, hybrid_scores = fuse(dense, sparse) fusion_ms = elapsed(t) * 1000 rankings = {'bm25': sparse, 'dense': dense, 'hybrid': hybrid} for arm, ms in (('bm25', sparse_ms), ('dense', dense_ms), ('hybrid', sparse_ms + dense_ms + fusion_ms)): timings.append({'round': round_no + 1, 'case': q['id'], 'group': q['group'], 'arm': arm, 'milliseconds': round(ms, 4)}) if round_no == 0: first[q['id']] = {'query': q, 'rankings': rankings, 'scores': {'bm25': sparse_scores, 'dense': dense_scores, 'hybrid': hybrid_scores}, 'chunks': {'bm25': sparse_chunk, 'dense': dense_chunk}} elif rankings != first[q['id']]['rankings']: unstable.append({'case': q['id'], 'round': round_no + 1}) STAGES['all_query_rounds_seconds'] = elapsed(t_queries) counts = {} for group in (*GROUPS, 'all'): subset = [q for q in tests if group == 'all' or q['group'] == group] counts[group] = {} for arm in ARMS: ranks = [] for q in subset: ranking = first[q['id']]['rankings'][arm] ranks.append(ranking.index(q['gold']) + 1 if q['gold'] in ranking else None) lat = [x['milliseconds'] for x in timings if x['arm'] == arm and (group == 'all' or x['group'] == group)] counts[group][arm] = {'n': len(ranks), 'hit1': sum(r == 1 for r in ranks), 'hit3': sum(r is not None and r <= 3 for r in ranks), 'mrr20': round(sum(1 / r if r else 0 for r in ranks) / len(ranks), 6), 'latency_p50_ms': round(percentile(lat, .50), 4), 'latency_p95_ms': round(percentile(lat, .95), 4)} def paired_changes(before_arm, after_arm): output = {} for group in GROUPS: changes = {'new_hit1': [], 'lost_hit1': [], 'new_hit3': [], 'lost_hit3': []} for q in (q for q in tests if q['group'] == group): ranks = first[q['id']]['rankings'] for k in (1, 3): before, after = q['gold'] in ranks[before_arm][:k], q['gold'] in ranks[after_arm][:k] if after and not before: changes[f'new_hit{k}'].append(q['id']) if before and not after: changes[f'lost_hit{k}'].append(q['id']) output[group] = changes return output differences = paired_changes('dense', 'hybrid') bm25_changes = {reference: paired_changes(reference, 'bm25') for reference in ('dense', 'hybrid')} # Count each question lost by choosing BM25 once, even if both references got it right. bm25_lost_union = {g: sorted(set(bm25_changes['dense'][g]['lost_hit1']) | set(bm25_changes['hybrid'][g]['lost_hit1'])) for g in GROUPS} gains = {g: counts[g]['hybrid']['hit1'] - counts[g]['dense']['hit1'] for g in GROUPS} success_tests = { 'identifier_net_gain_at_least_3_of_24': gains['identifier'] >= 3, 'symptom_new_failures_at_most_1_of_24': len(differences['symptom']['lost_hit1']) <= 1, 'history_new_failures_at_most_1_of_24': len(differences['history']['lost_hit1']) <= 1, 'all_net_gain_at_least_3_of_72': counts['all']['hybrid']['hit1'] - counts['all']['dense']['hit1'] >= 3, 'p95_added_latency_at_most_100_ms': counts['all']['hybrid']['latency_p95_ms'] - counts['all']['dense']['latency_p95_ms'] <= 100, 'stable_rankings': not unstable, } bm25_saved_ms = {reference: counts['all'][reference]['latency_p95_ms'] - counts['all']['bm25']['latency_p95_ms'] for reference in ('dense', 'hybrid')} bm25_tests = { 'each_group_hit1_deficit_at_most_1_vs_dense_and_hybrid': all( counts[g]['bm25']['hit1'] >= counts[g][reference]['hit1'] - 1 for g in GROUPS for reference in ('dense', 'hybrid')), 'each_group_new_failures_union_at_most_1': all(len(bm25_lost_union[g]) <= 1 for g in GROUPS), 'all_new_failures_union_at_most_2': sum(len(bm25_lost_union[g]) for g in GROUPS) <= 2, 'p95_at_most_half_of_dense_and_hybrid': all( counts['all']['bm25']['latency_p95_ms'] <= counts['all'][reference]['latency_p95_ms'] / 2 for reference in ('dense', 'hybrid')), 'p95_saving_at_least_50_ms_vs_dense_and_hybrid': all(ms >= 50 for ms in bm25_saved_ms.values()), 'stable_rankings': not unstable, } bm25_option = all(bm25_tests.values()) # H1 concerns identifier gains. Configuration choice also accounts for gains elsewhere. hybrid_general_tests = { 'all_net_gain_at_least_3_of_72': success_tests['all_net_gain_at_least_3_of_72'], 'each_group_new_failures_at_most_1_of_24': all(len(differences[g]['lost_hit1']) <= 1 for g in GROUPS), 'p95_added_latency_at_most_100_ms': success_tests['p95_added_latency_at_most_100_ms'], 'stable_rankings': not unstable, } hybrid_option = all(success_tests.values()) or all(hybrid_general_tests.values()) dense_keep_tests = { 'each_alternative_group_net_gain_below_3': all( counts[g][arm]['hit1'] - counts[g]['dense']['hit1'] < 3 for g in GROUPS for arm in ('bm25', 'hybrid')), 'each_alternative_all_net_gain_below_3': all( counts['all'][arm]['hit1'] - counts['all']['dense']['hit1'] < 3 for arm in ('bm25', 'hybrid')), } ceiling = all(counts[g][a]['hit1'] >= 23 for g in GROUPS for a in ARMS) # First matching branch wins; candidate flags alone are not recommendations. if unstable: choice, reason = 'hold_unstable', 'rankings_changed_between_rounds' elif ceiling: choice, reason = 'hold_ceiling', 'all_arms_and_groups_at_least_23_of_24' elif bm25_option: choice, reason = 'bm25', 'bounded_losses_vs_both_references_and_material_latency_saving' elif hybrid_option: choice = 'hybrid' reason = 'h1_supported' if all(success_tests.values()) else 'overall_gain_with_bounded_losses_despite_h1_not_supported' elif all(dense_keep_tests.values()): choice, reason = 'dense', 'neither_alternative_reaches_3_net_gains_and_bm25_cost_rule_fails' else: choice, reason = 'review_tradeoff', 'material_gain_exists_but_loss_or_latency_limits_prevent_selection' decision = {'choice': choice, 'reason': reason, 'priority': ['hold_unstable', 'hold_ceiling', 'bm25', 'hybrid', 'dense', 'review_tradeoff']} result = {'run_id': RUN_ID, 'status': 'measured', 'metrics': counts, 'hybrid_minus_dense_hit1': gains, 'paired_changes': differences, 'bm25_paired_changes': bm25_changes, 'bm25_new_failures_union': bm25_lost_union, 'bm25_p95_saved_ms': bm25_saved_ms, 'hypothesis_tests': success_tests, 'hypothesis_supported': all(success_tests.values()), 'configuration_tests': {'bm25': bm25_tests, 'hybrid_general': hybrid_general_tests, 'dense_keep': dense_keep_tests}, 'bm25_lower_cost_candidate': bm25_option, 'hybrid_candidate': hybrid_option, 'configuration_decision': decision, 'ceiling_effect': ceiling, 'ranking_instability': unstable, 'stages': STAGES, 'total_measurement_seconds': elapsed(started_all), 'case_sha256': case_hash, 'chunks_sha256': chunk_hash, 'documents': len(docs), 'chunks': len(chunks), 'dimensions': int(vectors.shape[1]), 'latency_note': 'warm CPU; sequential hybrid = dense query embedding/search + BM25 tokenization/search + RRF; excludes build/load; three rounds, not 216 independent quality cases', 'quality_note': '72 paired queries in 24 families, editor-authored from public MDN; document lookup, not answer accuracy or production traffic'} emit('metrics.json', result) docmap = {d['id']: d for d in docs} for group in GROUPS: records = [] for q in (q for q in tests if q['group'] == group): row = first[q['id']] output = {'case': q, 'arms': {}} for arm in ARMS: ranking = row['rankings'][arm] tops = [] for doc in ranking[:3]: chunk = (row['chunks']['dense'].get(doc) if arm == 'hybrid' else row['chunks'][arm].get(doc)) if chunk is None: chunk = row['chunks']['bm25'].get(doc) tops.append({'id': doc, 'title': docmap[doc]['title'], 'url': docmap[doc]['url'], 'score': round(row['scores'][arm][doc], 8), 'excerpt': chunks[chunk]['text'][:120] if chunk is not None else ''}) output['arms'][arm] = {'gold_rank_at_20': ranking.index(q['gold']) + 1 if q['gold'] in ranking else None, 'top3': tops, 'top20_ids': ranking} records.append(output) emit('rankings-' + group + '.json', {'run_id': RUN_ID, 'records': records}) buffer = io.StringIO() writer = csv.DictWriter(buffer, fieldnames=['round', 'case', 'group', 'arm', 'milliseconds']) writer.writeheader() writer.writerows(timings) emit('latency.csv', buffer.getvalue(), plain=True) versions = {line.split('==')[0]: importlib.metadata.version(line.split('==')[0]) for line in (LAB / 'requirements.lock').read_text().splitlines() if '==' in line} emit('environment.json', {'run_id': RUN_ID, 'machine': 'Apple M6・メモリー24GBのMac mini', 'python': sys.version.split()[0], 'packages': versions, 'device': 'cpu', 'dtype': 'float32', 'threads': 8, 'interop_threads': 1, 'model_revision': MODEL_REV, 'mdn_revision': MDN_REV, 'document_batch_size': 4, 'query_batch_size': 1, 'instruction': INSTRUCTION, 'rrf_constant': 60, 'candidate_documents_per_arm': 20, 'bm25': {'k1': 1.5, 'b': .75, 'epsilon': .25, 'normalization': 'NFKC lowercase; Janome wakati; discard punctuation-only tokens'}, 'chunking': 'title + up to 384 tokens total; body overlap 64 tokens; Unicode offsets; hard ceiling 480', 'model_bytes': sum(f['bytes'] for f in manifest['files']), 'memory_note': 'resources.txt is peak RSS for the entire measurement process; not per-arm memory'}) emit('README.md', '# 実験結果の読み方\n\n' 'metrics.json は事前基準による判定、rankings-*.json は全72問の各方式の上位結果、latency.csv は3巡の時間です。' '24種類の正解を3通りに言い換えたため、72問を独立した利用者の標本とは扱いません。' 'resources.txt の maximum resident set size は macOS のバイト単位で、実験プロセス全体の最大値です。\n\n' '対象は公開MDN技術文書の検索です。生成回答の正しさ、機密保持、実業務の時間削減、全社内文書への一般化は測っていません。' 'hypothesis_supported は番号群の改善を含むH1の判定です。構成の助言は configuration_decision を使います。' '判定順は不安定・天井効果による保留、BM25、hybrid、dense維持、条件が競合する場合の追加検証です。' 'BM25はdenseとhybridの両方に対する群別の正解件数差・新たな失敗・時間差で判断し、' 'bm25_paired_changes と bm25_new_failures_union に失う質問を残します。' 'H1不支持でも全体の改善と各群の悪化上限を満たせばhybridを候補にできます。' '失敗・天井効果を成功へ読み替えず、候補フラグだけで構成を勧めません。\n\n' 'Mozilla Contributors (MDN Web Docs), CC BY-SA 2.5 or later。検索用にマクロ・マークアップを除き分割しました。' '出典・版・個別URLはcorpus.jsonを参照。派生した抜粋・整形文書にも同じ条件を適用します。\n' 'https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Attrib_copyright_license\n' 'https://creativecommons.org/licenses/by-sa/2.5/\n', plain=True) emit('outcome.json', {'run_id': RUN_ID, 'status': 'complete', 'hypothesis_supported': all(success_tests.values()), 'ceiling_effect': ceiling, 'configuration_decision': decision}) try: run() except Exception as error: emit('errors.json', {'run_id': RUN_ID, 'errors': [{'type': type(error).__name__, 'message': scrub(str(error)), 'traceback': scrub(traceback.format_exc())[-16000:]}], 'completed_stages': STAGES}) emit('outcome.json', {'run_id': RUN_ID, 'status': 'failed', 'reason': scrub(str(error))}) raise PY if /usr/bin/time -l -o "$LAB/logs/resources.txt" \ "$LAB/venv/bin/python" -I "$LAB/measure.py" \ > "$LAB/logs/measurement.txt" 2>&1; then measure_rc=0 else measure_rc=$? fi # Stdlib only: preserve a bounded failure log even if a dependency import failed. "$LAB_PYTHON" -I - <<'PY' import os from pathlib import Path import re lab, out = Path(os.environ['LAB']), Path(os.environ['RESULTS']) for original, target in [('resources.txt', 'resources.txt'), ('measurement.txt', 'execution-log.txt')]: path = lab / 'logs' / original if path.exists(): with path.open('rb') as stream: stream.seek(max(0, path.stat().st_size - 60000)) text = stream.read().decode('utf-8', errors='replace') for key, replacement in [('RESULTS', '[RESULTS]'), ('HOME', '[HOME]'), ('LAB', '[LAB]')]: text = text.replace(os.environ[key], replacement) text = re.sub(r'/Users/[^/\s]+', '[USER]', text) (out / target).write_text(text) PY exit "$measure_rc"