MeningiomaBench / code /actual_completed_index_builder.py
dfdu233's picture
Silver research draft; expert review pending
32c7cac verified
Raw History Blame Contribute Delete
25 kB
"""Build the medical nano-graphrag method on the SAME public abstracts as hybrid RAG."""
import asyncio
import argparse
import hashlib
import json
import pathlib
import sqlite3
import sys
import threading
import time
OUT = pathlib.Path(__file__).resolve().parent
BASE = OUT / 'matched_public167'
parser = argparse.ArgumentParser()
parser.add_argument('--base-dir', default=str(BASE))
parser.add_argument('--questions', default=str(OUT / 'release_items_internal.jsonl'))
parser.add_argument('--contexts-name', default='graph_contexts.jsonl')
parser.add_argument('--marker-name', default='graph_complete.json')
parser.add_argument('--max-community-size', type=int, default=10)
parser.add_argument('--index-model', choices=('deepseek-v4.1-flash', 'gpt-6-luna'),
default='deepseek-v4.1-flash')
parser.add_argument('--llm-concurrency', type=int, default=4,
help='Operational callback concurrency; does not change prompts or extraction settings')
parser.add_argument('--embedding-device', choices=('cpu', 'cuda:0', 'cuda:1'), default='cpu',
help='BGE-M3 float32 device; existing embedding checkpoints are reused')
parser.add_argument('--index-call-limit', type=int, help='Maximum LLM callbacks outside the graph cache for this run')
parser.add_argument('--prepare-checkpoint', action='store_true', help='Create the prepared checkpoint without any LLM calls')
parser.add_argument('--source-only-graph', action='store_true', help='Skip community summaries for source selection only')
parser.add_argument('--official-platform', action='store_true', help='Separately authorized official Luna API, provider-default temperature, isolated response cache')
parser.add_argument('--index-reasoning-effort', choices=('provider_default', 'low'), default='provider_default', help='Explicit official API reasoning policy; recorded in identity and isolated cache keys')
parser.add_argument('--official-length-retry-cap', type=int, default=0, help='One bounded larger-budget retry after finish_reason=length; never accept truncated extraction')
parser.add_argument('--preformatted-documents', action='store_true', help='Read exact source-only index_content strings instead of wrapping individual source units')
parser.add_argument('--allow-bounded-checkpoint', action='store_true', help='Treat the configured callback boundary as a checked partial run')
ARGS = parser.parse_args()
if ARGS.official_platform and ARGS.index_model != 'gpt-6-luna':
parser.error('--official-platform requires --index-model gpt-6-luna')
if ARGS.index_reasoning_effort != 'provider_default' and not ARGS.official_platform:
parser.error('Explicit reasoning policy requires --official-platform')
if ARGS.official_length_retry_cap and (not ARGS.official_platform or ARGS.official_length_retry_cap <= 4000):
parser.error('Length retry requires official platform and a cap greater than 4000')
if not 1 <= ARGS.llm_concurrency <= 16:
parser.error('--llm-concurrency must be between 1 and 16')
if ARGS.allow_bounded_checkpoint and (ARGS.index_call_limit is None or ARGS.index_call_limit <= 0):
parser.error('--allow-bounded-checkpoint requires a positive --index-call-limit')
if ARGS.prepare_checkpoint and ARGS.index_call_limit is not None:
parser.error('--prepare-checkpoint sets a zero LLM callback limit')
if ARGS.prepare_checkpoint:
ARGS.index_call_limit = 0
BASE = pathlib.Path(ARGS.base_dir).resolve()
RUNTIME = pathlib.Path('/home/dbw/MedicalGraphRAG-deploy/MedicalGraphRAG-linux-x86_64')
sys.path.insert(0, str(RUNTIME / 'app'))
sys.path.insert(0, str(OUT.parent / 'optimization_20261117'))
from opencode_client import call, wait_for_quota
from nano_graphrag import GraphRAG, QueryParam
from nano_graphrag import graphrag as graph_runtime
from nano_graphrag._utils import EmbeddingFunc
from sentence_transformers import SentenceTransformer
import torch
class CallbackLimitReached(RuntimeError):
pass
def official_index_call(messages, max_tokens):
import requests
endpoint = 'https://api.openai.com/v1/chat/completions'
limit = int(max_tokens)
cache_identity = {'messages': messages, 'model': ARGS.index_model,
'endpoint': endpoint, 'max_completion_tokens': limit, 'temperature': 'provider_default'}
if ARGS.index_reasoning_effort != 'provider_default':cache_identity['reasoning_effort'] = ARGS.index_reasoning_effort
key = hashlib.sha256(json.dumps(cache_identity, sort_keys=True).encode()).hexdigest()
cache_path = BASE / 'official_luna_index_response_cache.sqlite3'
with sqlite3.connect(cache_path, timeout=30) as db:
db.execute('CREATE TABLE IF NOT EXISTS responses (key TEXT PRIMARY KEY, value TEXT NOT NULL)')
prior = db.execute('SELECT value FROM responses WHERE key=?', (key,)).fetchone()
if prior:
text, parsed, usage, model = json.loads(prior[0])
return text, parsed, {'local_cache_hit': True, 'total_tokens': 0, 'original_usage': usage, 'transport_calls': 0}, model
# A previously logged length failure for the identical request is the first
# stage of this policy, not a reason to pay for that exhausted stage again.
failures_path = BASE / 'official_failed_responses.jsonl'
if limit < ARGS.official_length_retry_cap and failures_path.exists():
prior_length = any(row.get('request_key') == key and row.get('finish_reason') == 'length'
for row in map(json.loads, failures_path.read_text().splitlines()))
if prior_length:
return official_index_call(messages, ARGS.official_length_retry_cap)
secret = pathlib.Path('/home/dbw/.config/meningioma-eval/openai_platform_key').read_text().strip()
body = {'model': ARGS.index_model, 'messages': messages, 'max_completion_tokens': limit}
if ARGS.index_reasoning_effort != 'provider_default':body['reasoning_effort'] = ARGS.index_reasoning_effort
for attempt in range(3):
response = None
try:
with requests.Session() as session:
session.trust_env = False
session.proxies = {'https': 'http://172.17.0.1:7890', 'http': 'http://172.17.0.1:7890'}
response = session.post(endpoint, headers={'Authorization': 'Bearer ' + secret}, json=body, timeout=(15, 180))
response.raise_for_status(); data = response.json(); choice = data['choices'][0]
usage = data.get('usage') or {}
event = {'request_key': key, 'model_requested': ARGS.index_model, 'model_returned': data.get('model'),
'reasoning_effort': ARGS.index_reasoning_effort,
'max_completion_tokens': limit, 'finish_reason': choice.get('finish_reason'), 'usage': usage,
'http_status': response.status_code, 'time_epoch': time.time()}
with (BASE / 'official_transport_usage.jsonl').open('a') as stream:
stream.write(json.dumps(event) + '\n')
if data.get('model') != ARGS.index_model:
raise RuntimeError('Official index model identity differs')
if choice.get('finish_reason') != 'stop' or not choice['message'].get('content'):
with (BASE / 'official_failed_responses.jsonl').open('a') as stream:
stream.write(json.dumps({**event, 'output': choice['message'].get('content')}) + '\n')
if choice.get('finish_reason') == 'length' and limit < ARGS.official_length_retry_cap:
retried_text, retried_parsed, retried_usage, retried_model = official_index_call(messages, ARGS.official_length_retry_cap)
return retried_text, retried_parsed, {**retried_usage,
'transport_calls': retried_usage.get('transport_calls', 0 if retried_usage.get('local_cache_hit') else 1) + 1,
'all_provider_usage_ledger': 'official_transport_usage.jsonl'}, retried_model
raise RuntimeError('Non-stop or empty extraction retained as failed transport event; not accepted into graph cache')
text = choice['message']['content']
try:parsed = json.loads(text)
except ValueError:parsed = None
result = text, parsed, {**usage, 'completion_finish_reason': 'stop', 'transport_calls': 1}, data['model']
with sqlite3.connect(cache_path, timeout=30) as db:
db.execute('INSERT OR IGNORE INTO responses VALUES (?,?)', (key, json.dumps(result)))
return result
except (requests.RequestException, ValueError, KeyError, IndexError) as exc:
status = response.status_code if response is not None else None
transient = isinstance(exc, (requests.ConnectionError, requests.Timeout)) or status in (408, 500, 502, 503, 504)
with (BASE / 'index_call_retry_events.jsonl').open('a') as stream:
stream.write(json.dumps({'request_key': key, 'error_type': type(exc).__name__, 'http_status': status,
'attempt': attempt + 1, 'retryable': transient, 'provider_usage_available': False, 'time_epoch': time.time()}) + '\n')
if not transient or attempt == 2:raise
time.sleep(2 ** (attempt + 1))
def index_call(messages, max_tokens):
if ARGS.official_platform:
return official_index_call(messages, max_tokens)
if ARGS.index_model == 'deepseek-v4.1-flash':
return call(messages, max_tokens)
# Use the already configured GPT gateway, with a cache isolated from DeepSeek.
sys.path.insert(0, str(OUT.parent / 'benchmark_v2'))
from create_questions import call as gpt_call, CONFIG
key = hashlib.sha256(json.dumps({'messages': messages, 'max_tokens': max_tokens,
'model': ARGS.index_model, 'temperature': 0, 'base_url': CONFIG['base_url']},
sort_keys=True).encode()).hexdigest()
with sqlite3.connect(BASE / 'gpt_index_response_cache.sqlite3', timeout=30) as db:
db.execute('CREATE TABLE IF NOT EXISTS responses (key TEXT PRIMARY KEY, value TEXT NOT NULL)')
old = db.execute('SELECT value FROM responses WHERE key=?', (key,)).fetchone()
if old:
text, parsed, usage, model = json.loads(old[0])
return text, parsed, {'local_cache_hit': True, 'total_tokens': 0,
'original_usage': usage}, model
import requests
for attempt in range(4):
try:
result = gpt_call(ARGS.index_model, messages, max_tokens)
break
except (requests.HTTPError, requests.ConnectionError, requests.Timeout) as error:
status = error.response.status_code if getattr(error, 'response', None) is not None else None
retryable = status == 408 or isinstance(error, (requests.ConnectionError, requests.Timeout))
with (BASE / 'index_call_retry_events.jsonl').open('a') as log:
log.write(json.dumps({'request_key': key, 'model': ARGS.index_model,
'attempt': attempt + 1, 'error_type': type(error).__name__,
'http_status': status, 'retryable': retryable, 'time_epoch': time.time(),
'provider_usage_available': False}) + '\n')
if not retryable or attempt == 3:
raise
time.sleep(min(2 ** (attempt + 1), 15))
if result[3] != ARGS.index_model:
raise RuntimeError('Unexpected GPT index model: ' + str(result[3]))
with sqlite3.connect(BASE / 'gpt_index_response_cache.sqlite3', timeout=30) as db:
db.execute('INSERT OR IGNORE INTO responses VALUES (?,?)', (key, json.dumps(result)))
return result
async def main():
identity_path = BASE / 'index_model_identity.json'
identity = {'index_model': ARGS.index_model,
'corpus_sha256': hashlib.sha256((BASE / 'corpus.jsonl').read_bytes()).hexdigest(),
'source_only_without_community_reports': ARGS.source_only_graph}
if ARGS.official_platform:
identity.update(index_endpoint='https://api.openai.com/v1', index_temperature='provider_default',
completion_limit_parameter='max_completion_tokens', accept_truncated_callbacks=False)
if ARGS.index_reasoning_effort != 'provider_default':identity['index_reasoning_effort'] = ARGS.index_reasoning_effort
if ARGS.official_length_retry_cap:
identity['length_retry_policy'] = {'trigger': 'finish_reason=length', 'retry_cap': ARGS.official_length_retry_cap, 'maximum_larger_budget_retries': 1, 'reuse_identical_logged_failure': True}
if ARGS.preformatted_documents:
identity['document_format'] = 'exact_preformatted_index_content'
seed_path = BASE / 'seeded_extraction_provenance.json'
seed = None
if seed_path.exists():
seed = json.loads(seed_path.read_text())
if seed['target_corpus_sha256'] != identity['corpus_sha256']:
raise RuntimeError('Seed extraction provenance differs from target corpus')
identity['seeded_extraction_provenance_sha256'] = hashlib.sha256(seed_path.read_bytes()).hexdigest()
if identity_path.exists():
if json.loads(identity_path.read_text()) != identity:
raise RuntimeError('Index model/corpus/variant differs from saved identity; use a separate directory')
else:
if (BASE / 'graph/.insert_checkpoint/progress.sqlite3').exists() and ARGS.index_model != 'deepseek-v4.1-flash':
raise RuntimeError('Unlabelled existing checkpoint must not be resumed with another model')
identity_path.write_text(json.dumps(identity, indent=2) + '\n')
if ARGS.index_call_limit != 0 and ARGS.index_model == 'deepseek-v4.1-flash':
await asyncio.to_thread(wait_for_quota)
torch.set_num_threads(4)
corpus = list(map(json.loads, (BASE / 'corpus.jsonl').open()))
items = list(map(json.loads, pathlib.Path(ARGS.questions).open()))
if ARGS.embedding_device != 'cpu':
device_index = int(ARGS.embedding_device.split(':')[1])
if torch.cuda.mem_get_info(device_index)[0] < 6 * 1024**3:
raise RuntimeError('Embedding device requires at least 6 GiB free memory')
torch.cuda.set_per_process_memory_fraction(0.12, device_index)
embedding_model = SentenceTransformer(str(RUNTIME / 'models/bge-m3'), device=ARGS.embedding_device)
with (BASE / 'embedding_runtime_history.jsonl').open('a') as stream:
stream.write(json.dumps({'time_epoch': time.time(), 'device': ARGS.embedding_device,
'dtype': str(next(embedding_model.parameters()).dtype),
'cuda_allocator_fraction': 0.12 if ARGS.embedding_device != 'cpu' else None,
'reuse_existing_vectors': True}) + '\n')
lock = asyncio.Lock()
attempted = 0
pending = 0
drained = asyncio.Event()
drained.set()
skipped_reports = 0
async def omit_reports(report_store, graph, tokenizer, config):
nonlocal skipped_reports
communities = await graph.community_schema()
await report_store.upsert({
k: {**v, 'report_string': '', 'report_json': {'rating': 0.0}} for k, v in communities.items()
})
skipped_reports += 1
if ARGS.source_only_graph:
graph_runtime.generate_community_report = omit_reports
def encode_texts(texts):
batch_size = 16
while True:
try:
return embedding_model.encode(texts, batch_size=batch_size,
normalize_embeddings=True, show_progress_bar=False, convert_to_numpy=True)
except torch.cuda.OutOfMemoryError:
if ARGS.embedding_device == 'cpu' or batch_size == 1:
raise
torch.cuda.empty_cache()
batch_size //= 2
async def embed(texts):
async with lock:
return await asyncio.to_thread(encode_texts, texts)
async def complete(prompt, system_prompt=None, history_messages=None, **kwargs):
nonlocal attempted, pending
started = time.monotonic()
messages = ([{'role': 'system', 'content': system_prompt}] if system_prompt else []) + list(history_messages or []) + [{'role': 'user', 'content': prompt}]
max_tokens = kwargs.get('max_tokens', 4000)
key = hashlib.sha256(json.dumps({'messages': messages, 'max_tokens': max_tokens,
'model': ARGS.index_model}, sort_keys=True).encode()).hexdigest()
cache = kwargs.get('hashing_kv')
if cache is not None:
old = await cache.get_by_id(key)
if old is not None:
with (BASE / 'index_call_usage_resume.jsonl').open('a') as log:
log.write(json.dumps({'prompt_key': key, 'cache_layer': 'graph', 'new_api_usage': None,
'new_api_calls': 0, 'max_tokens': max_tokens, 'seconds': time.monotonic() - started}) + '\n')
return old['return']
if ARGS.index_call_limit is not None and attempted >= ARGS.index_call_limit:
await drained.wait()
raise CallbackLimitReached('Configured index callback limit reached')
attempted += 1
pending += 1
drained.clear()
try:
text, parsed, usage, returned = await asyncio.to_thread(index_call, messages, max_tokens)
with (BASE / 'index_call_usage_resume.jsonl').open('a') as log:
log.write(json.dumps({'prompt_key': key, 'cache_layer': 'response' if (usage or {}).get('local_cache_hit') else 'api',
'new_api_usage': usage, 'new_api_calls': (usage or {}).get('transport_calls', 0 if (usage or {}).get('local_cache_hit') else 1),
'max_tokens': max_tokens, 'seconds': time.monotonic() - started,
'index_model': ARGS.index_model, 'model_returned': returned,
'llm_concurrency': ARGS.llm_concurrency,
'coverage': 'Successful callbacks recorded; provider failures and retries without usage are excluded.'}) + '\n')
if returned != ARGS.index_model:
raise RuntimeError('Unexpected index model: ' + str(returned))
if cache is not None:
await cache.upsert({key: {'return': text, 'model': returned}})
return text
finally:
pending -= 1
if not pending:
drained.set()
rag = GraphRAG(working_dir=str(BASE / 'graph'), chunk_token_size=1200, chunk_overlap_token_size=100,
entity_extract_max_gleaning=1, embedding_func=EmbeddingFunc(embedding_dim=1024, max_token_size=8192, func=embed),
embedding_batch_num=32, embedding_func_max_async=4,
best_model_func=complete, cheap_model_func=complete,
best_model_max_async=ARGS.llm_concurrency, cheap_model_max_async=ARGS.llm_concurrency,
addon_params={'domain': 'medical'}, enable_insert_checkpoint=True,
max_graph_cluster_size=ARGS.max_community_size)
print('MATCHED GRAPH INSERT', len(corpus), 'documents', flush=True)
texts = [graph_document(x) for x in corpus]
try:
await rag.ainsert(texts)
except CallbackLimitReached:
if not (ARGS.prepare_checkpoint or ARGS.allow_bounded_checkpoint):
raise
checkpoint = BASE / 'graph/.insert_checkpoint/progress.sqlite3'
with sqlite3.connect(checkpoint.as_uri() + '?mode=ro', uri=True) as db:
state = json.loads(db.execute('SELECT value FROM state WHERE id = 1').fetchone()[0])
records = dict(db.execute('SELECT namespace, count(*) FROM records WHERE job_id=? GROUP BY namespace',
(state['job_id'],)))
if ARGS.allow_bounded_checkpoint:
if pending or attempted != ARGS.index_call_limit:
raise RuntimeError('Bounded checkpoint reached with unsettled callbacks')
marker = {'stage': state['stage'], 'admitted_callbacks': attempted,
'llm_concurrency': ARGS.llm_concurrency,
'checkpoint_records': records, 'build_complete': False}
with (BASE / 'bounded_checkpoints.jsonl').open('a') as log:
log.write(json.dumps(marker) + '\n')
print('MATCHED GRAPH BOUNDED CHECKPOINT', marker, flush=True)
return
if state['stage'] != 'prepared' or len(state['documents']) != len(corpus):
raise RuntimeError('Unexpected checkpoint stage for prepare-only run')
prepared_contents = {row['content'] for row in state['documents'].values()}
expected_contents = {text.strip() for text in texts} if ARGS.preformatted_documents else set(texts)
if expected_contents != prepared_contents:
raise RuntimeError('Prepared checkpoint documents differ from inputs')
if ARGS.preformatted_documents:
boundary_changes = []
for source, text in zip(corpus, texts):
canonical = text.strip()
if text != canonical:
boundary_changes.append({'source_id': source['source_id'],
'raw_content_sha256': hashlib.sha256(text.encode()).hexdigest(),
'backend_content_sha256': hashlib.sha256(canonical.encode()).hexdigest(),
'leading_characters_stripped': len(text) - len(text.lstrip()),
'trailing_characters_stripped': len(text) - len(text.rstrip())})
boundary_audit = {'scope': 'Observed native ingestion boundary-whitespace normalization, not rewritten source content.',
'documents': len(corpus), 'changed_documents': boundary_changes,
'all_canonical_documents_match_prepared_checkpoint': True, 'new_api_calls': 0}
(BASE / 'backend_ingestion_boundary_audit.json').write_text(json.dumps(boundary_audit, indent=2) + '\n')
summary = {'stage': 'prepared', 'documents': len(corpus), 'chunks': len(state['chunks']),
'corpus_sha256': hashlib.sha256((BASE / 'corpus.jsonl').read_bytes()).hexdigest(),
'new_api_calls': 0}
(BASE / 'prepared_checkpoint.json').write_text(json.dumps(summary, indent=2) + '\n')
print('MATCHED GRAPH CHECKPOINT PREPARED', summary, flush=True)
return
if ARGS.prepare_checkpoint:
raise RuntimeError('No zero-call boundary seen during checkpoint preparation')
if ARGS.source_only_graph:
reports_path = BASE / 'graph/kv_store_community_reports.json'
if skipped_reports == 0:
reports = json.loads(reports_path.read_text())
if not reports or any(row.get('report_string') or row.get('report_json') != {'rating': 0.0}
for row in reports.values()):
raise RuntimeError('Resumed source-only graph has unexpected report contents')
elif skipped_reports != 1:
raise RuntimeError('Source-only run repeated the community-report bypass')
print('MATCHED GRAPH INSERT COMPLETE', flush=True)
dest = BASE / ARGS.contexts_name
done = {x['id'] for x in map(json.loads, dest.open())} if dest.exists() else set()
for item in items:
if item['id'] in done:
continue
query_param = QueryParam(mode='local', top_k=10, only_need_context=True)
if ARGS.source_only_graph:
query_param.local_max_token_for_community_report = 0
context = await rag.aquery(item['question'], param=query_param)
with dest.open('a') as stream:
stream.write(json.dumps({'id': item['id'], 'method': 'graph', 'context': context, 'sources': []}, ensure_ascii=True) + '\n')
done.add(item['id'])
print('MATCHED GRAPH CONTEXT', len(done), '/', len(items), flush=True)
current_done = len({x['id'] for x in items} & done)
(BASE / ARGS.marker_name).write_text(json.dumps({'corpus_documents': len(corpus), 'questions': current_done,
'questions_file_sha256': hashlib.sha256(pathlib.Path(ARGS.questions).read_bytes()).hexdigest(),
'index_model': ARGS.index_model, 'method': 'Medical nano-graphrag compiled package, medical domain, local search top10, BGE-M3.',
'llm_concurrency_at_completion': ARGS.llm_concurrency,
'max_graph_cluster_size': ARGS.max_community_size,
'source_only_without_community_reports': ARGS.source_only_graph,
'seeded_extraction_provenance': seed,
'original_private_graph_unchanged': True}, indent=2))
def graph_document(row):
if ARGS.preformatted_documents:
return row['index_content']
if 'source_id' in row:
return f"SourceID:{row['source_id']}\nTitle: {row['title']}\nPassage: {row['text']}"
return f"PMID:{row['pmid']}\nTitle: {row['title']}\nPublication date: {row['publication_date']}\nAbstract: {row['text']}"
if __name__ == '__main__':
asyncio.run(main())