File size: 8,113 Bytes
3627825 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | """Source-only six-arm matched graph/BM/native parent contexts on full511.
No annotations, reference answers or reader predictions are opened for selection.
"""
import collections,hashlib,json,re,sqlite3,sys
from pathlib import Path
import tiktoken
from openqa_graph_source_adapter import source_chunks,graph_ranked_sources
from parent_passage_retrieval import expand_ranked_sources
from prepare_openqa_dev161_equal_budget import freeze
ROOT=Path(__file__).resolve().parent;BASE=ROOT/'miriad_public'
FULL=BASE/'graph_common_corpus_gpt_20261121/full4685';OUT=FULL/'human511_retrieval_prospective_v1'
HEADER=re.compile(r'^\[E[1-9]\d*\] SourceID:(\S+)[^\n]*\n',re.M)
def read(p):return [json.loads(x) for x in p.read_text().splitlines()]
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def digest(s):return hashlib.sha256(s.encode()).hexdigest()
def main():
protocol=json.loads((OUT/'protocol_before_queries.json').read_text());queries=read(OUT/'source_only_queries511_local_only.jsonl');assert sha(OUT/'source_only_queries511_local_only.jsonl')==protocol['queries_sha256']
corpus={r['source_id']:r for r in read(FULL/'corpus.jsonl')};assert len(corpus)==4685 and sha(FULL/'corpus.jsonl')==protocol['corpus_sha256']
raw={}
for budget in [4000,12000]:
marker=json.loads((OUT/f'graph_source{budget}_complete.json').read_text());assert marker['questions']==511 and marker['questions_file_sha256']==protocol['queries_sha256']
rows=read(OUT/f'raw_graph_source{budget}_contexts511_local_only.jsonl');assert len(rows)==511 and {r['id'] for r in rows}=={r['id'] for r in queries};raw[budget]={r['id']:r['context'] for r in rows}
templates={(r['id'],r['method']):r for r in read(BASE/'openqa_human511_readers/requests2555.jsonl')}
sys.path.insert(0,str(ROOT.parents[1]/'MedicalGraphRAG-linux-x86_64/app'));from nano_graphrag._utils import list_of_list_to_csv
lookup=source_chunks(FULL/'graph',{f"SourceID:{k}\nTitle: {r['title']}\nPassage: {r['text']}":k for k,r in corpus.items()})
for content,ids in list(lookup.items()):
displayed=list_of_list_to_csv([[0,content]]);assert displayed.startswith('0,\t"') and displayed.endswith('"');lookup.setdefault(displayed[4:-1],set()).update(ids)
db=sqlite3.connect(':memory:');db.execute('CREATE VIRTUAL TABLE sources USING fts5(source_id UNINDEXED,title,body)');tokenize=lambda s:' '.join(re.findall(r'[a-z0-9]+',s.lower()))
for k,r in corpus.items():db.execute('INSERT INTO sources VALUES(?,?,?)',(k,tokenize(r['title']),tokenize(r['text'])))
freeze(OUT/'context_assembly_policy_before_selection.json',json.dumps({'empty_policy':'Retain empty arms as failures. If ANY arm empty, preserve all parent contexts capped6000 and mark strict_equal_actual_length false; do not erase all other contexts or drop question. Matches existing development build_contexts empty handling.',
'nonempty_policy':'Per-question minimum across6arms, then common stable prefix after UTF boundary decoding, <=6000sharedtokens, no padding. Preserve candidate sets/ranks before reading reference annotations.',
'arms':['bm25_parent_commoncap','native_parent_commoncap','graph4000_original','graph4000_question_bm25','graph12000_original','graph12000_question_bm25'],
'original_bm_native_candidates':'First8unique source IDs actually displayed by archived BM25/hybrid inputs. These are source-parent comparisons, not re-labeled unchanged chunk baselines.',
'graph_candidates':'First8unique source parents returned by frozen compiledgraph; questionBM25 only sorts WITHINthese candidates, nonmatches retain graphorder.',
'lexical':'Original development ASCII lowercase ORquery first120unique words; FTS5bm25(0,1,1),source_id tie break.',
'reader_system_prompt':'Exact archived original human511system prompt, same question. No outputs opened; this code creates requests ONLY.',
'selection_code_sha256':sha(Path(__file__)),'new_llm_calls':0},indent=2)+'\n')
encoder=tiktoken.encoding_for_model('gpt-4o');requests=[];selection=[];counts=collections.Counter()
for q in queries:
ident=q['id'];orig=templates[(ident,'hybrid')];candidate={};ranked={}
for old,new in [('bm25','bm25_parent_commoncap'),('hybrid','native_parent_commoncap')]:
text=json.loads(templates[(ident,old)]['messages'][1]['content'])['evidence'];ids=list(dict.fromkeys(HEADER.findall(text)))[:8];assert all(i in corpus for i in ids);candidate[new]=ids;ranked[new]=ids
words=list(dict.fromkeys(tokenize(q['question']).split()))[:120];query=' OR '.join('"'+w+'"' for w in words)
matches=[r[0] for r in db.execute('SELECT source_id FROM sources WHERE sources MATCH ? ORDER BY bm25(sources,0,1,1),source_id',(query,))] if query else [];positions={k:i for i,k in enumerate(matches)}
for budget in [4000,12000]:
ids,ambiguous=graph_ranked_sources(raw[budget][ident],lookup);assert ambiguous==0;ids=ids[:8]
for order in ['original','question_bm25']:
method=f'graph{budget}_{order}';candidate[method]=ids;ranked[method]=ids if order=='original' else sorted(ids,key=lambda k:positions.get(k,len(positions)+ids.index(k)))
contexts={m:expand_ranked_sources(ids,corpus,encoder,budget=6000) for m,ids in ranked.items()}
tokenized={m:encoder.encode(text) for m,text in contexts.items()};strict=all(tokenized.values());cap=min(map(len,tokenized.values())) if strict else None
if strict:
for _ in range(32):
contexts={m:encoder.decode(t[:cap],errors='ignore') for m,t in tokenized.items()};lengths={m:len(encoder.encode(t)) for m,t in contexts.items()}
if len(set(lengths.values()))==1:break
cap=min(lengths.values())
else:raise RuntimeError('Cannot stabilize common UTF prefix')
lengths={m:len(encoder.encode(t)) for m,t in contexts.items()};assert max(lengths.values())<=6000
counts['strict_equal_actual_length_questions']+=strict;counts['questions_with_empty_arm']+=not strict
for method,context in contexts.items():
row={**orig,'method':method,'messages':[orig['messages'][0],{'role':'user','content':json.dumps({'question':q['question'],'evidence':context},ensure_ascii=False)}],
'context_sha256':digest(context),'context_tokens_unified':lengths[method],'track':'human511_same_corpus_matched_parent_graph_exploratory'};requests.append(row)
counts[method+'_empty']+=not bool(context)
selection.append({'id':ident,'source_candidates':candidate,'ranked_sources':ranked,'actual_context_tokens':lengths,'strict_equal_actual_length':strict,'gold_or_reference_opened_for_selection':False})
freeze(OUT/'source_only_selection511_local_only.jsonl',''.join(json.dumps(x)+'\n' for x in selection));freeze(OUT/'matched_reader_requests3066_local_only.jsonl',''.join(json.dumps(x)+'\n' for x in requests))
ledgers={p.name:sha(p) for p in FULL.glob('*usage*.jsonl')};assert ledgers==protocol['before_query_usage_ledgers_sha256'],'Query changed provider usage ledgers'
result={'questions':511,'reader_requests_prepared':len(requests),'method_arms':6,'counts':dict(counts),'all_parent_context_caps6000':True,'new_model_calls':0,'provider_usage_ledgers_unchanged':True,'reference_annotations_used_for_selection':False,
'query_sourcebudgets':[4000,12000],'original_corpus_passages':4685,'graph_variant':'MixedDeepSeek/Luna Medicalnano compiled fork, not officialMicrosoftGraphRAG','reader_requests_sha256':sha(OUT/'matched_reader_requests3066_local_only.jsonl'),
'limits':'No new reader answers or semantic evaluation yet. Historically exposed exploratory511, not untouchedtest. Empty arms retained; strictactualmatch only where allarmsnonempty. BM/native are parent-expansion comparison arms, not unchanged original chunk methods. Different embedding/index extractors remain method confounds.'}
freeze(OUT/'matched_context_preparation_audit.json',json.dumps(result,indent=2)+'\n');print(json.dumps(result))
if __name__=='__main__':main()
|