wikikg-fact-phd / src /utils /model_smoke_test.py
minhy112's picture
Add files using upload-large-folder tool
cd58795 verified
Raw
History Blame Contribute Delete
23.5 kB
from __future__ import annotations
import argparse
import copy
import gc
import importlib.util
import json
import os
import time
import traceback
from pathlib import Path
from typing import Any
import yaml
from src.data.io_utils import write_csv, write_json
REQUIRED_PACKAGES = ["torch", "transformers", "accelerate"]
PASS_STATUSES = {"PASS", "PASS_BACKUP"}
VALID_GROUPS = {"all", "encoders", "retrieval", "llm_small", "llm_large"}
MINIMUM_REQUIRED_MODULES = {
"Dense retrieval",
"Reranker",
"ViFactCheck verifier",
"AVeriTeC verifier",
"HealthVer verifier",
"Vietnamese NLI",
"English NLI",
}
WIKIKG_REQUIRED_MODULES = {"Extraction"}
LLM_BASELINE_REQUIRED_MODULES = {"LLM judge"}
def package_available(name: str) -> bool:
return importlib.util.find_spec(name) is not None
def dependency_status() -> dict[str, bool]:
packages = {name: package_available(name) for name in REQUIRED_PACKAGES}
packages["bitsandbytes"] = package_available("bitsandbytes")
return packages
def cuda_status() -> dict[str, Any]:
if not package_available("torch"):
return {"torch_available": False, "cuda_available": False, "device_count": 0, "devices": []}
import torch
devices = []
if torch.cuda.is_available():
for idx in range(torch.cuda.device_count()):
props = torch.cuda.get_device_properties(idx)
devices.append(
{
"index": idx,
"name": props.name,
"total_memory_gb": round(props.total_memory / (1024**3), 3),
}
)
return {
"torch_available": True,
"torch_version": torch.__version__,
"cuda_available": torch.cuda.is_available(),
"device_count": torch.cuda.device_count() if torch.cuda.is_available() else 0,
"devices": devices,
}
def reset_peak_memory() -> None:
import torch
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.cuda.reset_peak_memory_stats()
def peak_vram_gb() -> float | None:
import torch
if not torch.cuda.is_available():
return None
return round(torch.cuda.max_memory_allocated() / (1024**3), 4)
def cleanup_torch() -> None:
gc.collect()
if package_available("torch"):
import torch
if torch.cuda.is_available():
torch.cuda.empty_cache()
def dtype_for_device():
import torch
if torch.cuda.is_available():
return torch.bfloat16 if torch.cuda.is_bf16_supported() else torch.float16
return torch.float32
def build_quantization_config(spec: dict[str, Any]):
quantization = str(spec.get("quantization", "")).casefold()
if "4bit" not in quantization:
return None
if not package_available("bitsandbytes"):
raise RuntimeError("bitsandbytes is required for bnb_4bit quantization")
from transformers import BitsAndBytesConfig
return BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=dtype_for_device(),
bnb_4bit_use_double_quant=True,
)
def load_tokenizer(model_id: str):
from transformers import AutoTokenizer
return AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
def smoke_embedding(spec: dict[str, Any]) -> dict[str, Any]:
import torch
from transformers import AutoModel
model_id = spec["model_id"]
tokenizer = load_tokenizer(model_id)
model = AutoModel.from_pretrained(
model_id,
torch_dtype=dtype_for_device(),
device_map="auto" if torch.cuda.is_available() else None,
trust_remote_code=True,
)
sentences = [
"A claim needs evidence with clear provenance.",
"Kiểm chứng thông tin cần bằng chứng có nguồn.",
"Hydroxychloroquine does not improve COVID-19 outcomes in this trial.",
"The statement is not supported by the cited article.",
"Entity overlap can help retrieve relevant context chunks.",
"The dataset split must avoid claim-level leakage.",
"Biomedical verification needs careful terminology.",
"A reranker scores claim and evidence pairs.",
"Knowledge graph triples must keep source sentence IDs.",
"Not enough evidence should not be forced into support or refute.",
]
inputs = tokenizer(sentences, padding=True, truncation=True, max_length=128, return_tensors="pt")
if torch.cuda.is_available():
inputs = {key: value.to(model.device) for key, value in inputs.items()}
with torch.no_grad():
output = model(**inputs)
hidden = output.last_hidden_state
embedding = hidden.mean(dim=1)
return {"output_shape": list(embedding.shape), "batch": len(sentences)}
def smoke_reranker(spec: dict[str, Any]) -> dict[str, Any]:
import torch
model_id = spec["model_id"]
tokenizer = load_tokenizer(model_id)
pairs = [
("Does HCQ treat COVID-19?", "The trial found no significant difference in outcomes."),
("Did the police salary change?", "The salary was 24000 in 2010 and 23000 in 2018."),
] * 5
inputs = tokenizer(
[claim for claim, _ in pairs],
[evidence for _, evidence in pairs],
padding=True,
truncation=True,
max_length=256,
return_tensors="pt",
)
quantization_config = build_quantization_config(spec)
try:
from transformers import AutoModelForSequenceClassification
model = AutoModelForSequenceClassification.from_pretrained(
model_id,
torch_dtype=dtype_for_device(),
device_map="auto" if torch.cuda.is_available() else None,
trust_remote_code=True,
quantization_config=quantization_config,
)
if torch.cuda.is_available():
inputs = {key: value.to(model.device) for key, value in inputs.items()}
with torch.no_grad():
logits = model(**inputs).logits
return {"output_shape": list(logits.shape), "batch": len(pairs), "loader": "AutoModelForSequenceClassification"}
except Exception:
from transformers import AutoModelForCausalLM
model = AutoModelForCausalLM.from_pretrained(
model_id,
torch_dtype=dtype_for_device(),
device_map="auto" if torch.cuda.is_available() else None,
trust_remote_code=True,
quantization_config=quantization_config,
)
prompt = "Given a query and a passage, output yes if the passage is relevant.\nQuery: Does HCQ treat COVID-19?\nPassage: The trial found no significant difference.\nAnswer:"
inputs = tokenizer(prompt, return_tensors="pt")
if torch.cuda.is_available():
inputs = {key: value.to(model.device) for key, value in inputs.items()}
with torch.no_grad():
output = model.generate(**inputs, max_new_tokens=4)
return {"output_shape": list(output.shape), "batch": 1, "loader": "AutoModelForCausalLM"}
def smoke_encoder_classifier(spec: dict[str, Any]) -> dict[str, Any]:
import torch
from transformers import AutoModelForSequenceClassification
model_id = spec["model_id"]
tokenizer = load_tokenizer(model_id)
texts = [
"Claim: The statement is supported. Evidence: The source directly states it.",
"Claim: The claim is false. Evidence: The cited source contradicts it.",
]
inputs = tokenizer(texts, padding=True, truncation=True, max_length=256, return_tensors="pt")
model = AutoModelForSequenceClassification.from_pretrained(
model_id,
num_labels=3,
torch_dtype=dtype_for_device(),
device_map="auto" if torch.cuda.is_available() else None,
trust_remote_code=True,
)
if torch.cuda.is_available():
inputs = {key: value.to(model.device) for key, value in inputs.items()}
with torch.no_grad():
logits = model(**inputs).logits
return {"output_shape": list(logits.shape), "batch": len(texts)}
def smoke_nli(spec: dict[str, Any]) -> dict[str, Any]:
import torch
from transformers import AutoModelForSequenceClassification
model_id = spec["model_id"]
tokenizer = load_tokenizer(model_id)
premises = [
"The clinical trial found no statistically significant improvement.",
"Bài báo nói sự kiện được tổ chức tại Hải Phòng.",
]
hypotheses = [
"The treatment improved patient outcomes.",
"Sự kiện diễn ra tại Hải Phòng.",
]
inputs = tokenizer(premises, hypotheses, padding=True, truncation=True, max_length=256, return_tensors="pt")
model = AutoModelForSequenceClassification.from_pretrained(
model_id,
torch_dtype=dtype_for_device(),
device_map="auto" if torch.cuda.is_available() else None,
trust_remote_code=True,
)
if torch.cuda.is_available():
inputs = {key: value.to(model.device) for key, value in inputs.items()}
with torch.no_grad():
logits = model(**inputs).logits
return {"output_shape": list(logits.shape), "batch": len(premises)}
def smoke_causal_json(spec: dict[str, Any]) -> dict[str, Any]:
import torch
from transformers import AutoModelForCausalLM, AutoProcessor
model_id = spec["model_id"]
quantization_config = build_quantization_config(spec)
prompt = (
"Extract one source-grounded fact as strict JSON with keys fact, subject, relation, object.\n"
"Claim: Masks reduce COVID-19 transmission.\n"
"Evidence: Broad adoption of face masks may meaningfully reduce community transmission.\n"
"JSON:"
)
processor_causal_error = ""
tokenizer_causal_error = ""
try:
processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
model_id,
torch_dtype=dtype_for_device(),
device_map="auto" if torch.cuda.is_available() else None,
trust_remote_code=True,
quantization_config=quantization_config,
)
inputs = processor(text=prompt, return_tensors="pt")
if torch.cuda.is_available():
inputs = {key: value.to(model.device) for key, value in inputs.items()}
with torch.no_grad():
output = model.generate(**inputs, max_new_tokens=64, do_sample=False)
try:
decoded = processor.decode(output[0], skip_special_tokens=True)
except Exception:
decoded = processor.batch_decode(output, skip_special_tokens=True)[0]
return {"output_text_tail": decoded[-500:], "batch": 1, "loader": "AutoProcessor+AutoModelForCausalLM"}
except Exception as exc:
processor_causal_error = repr(exc)
try:
tokenizer = load_tokenizer(model_id)
model = AutoModelForCausalLM.from_pretrained(
model_id,
torch_dtype=dtype_for_device(),
device_map="auto" if torch.cuda.is_available() else None,
trust_remote_code=True,
quantization_config=quantization_config,
)
inputs = tokenizer(prompt, return_tensors="pt")
if torch.cuda.is_available():
inputs = {key: value.to(model.device) for key, value in inputs.items()}
with torch.no_grad():
output = model.generate(**inputs, max_new_tokens=64, do_sample=False)
decoded = tokenizer.decode(output[0], skip_special_tokens=True)
return {
"output_text_tail": decoded[-500:],
"batch": 1,
"loader": "AutoTokenizer+AutoModelForCausalLM",
"processor_causal_loader_error": processor_causal_error,
}
except Exception as exc:
tokenizer_causal_error = repr(exc)
pass
try:
from transformers import AutoModelForImageTextToText, AutoProcessor
processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
model = AutoModelForImageTextToText.from_pretrained(
model_id,
torch_dtype=dtype_for_device(),
device_map="auto" if torch.cuda.is_available() else None,
trust_remote_code=True,
quantization_config=quantization_config,
)
inputs = processor(text=prompt, return_tensors="pt")
if torch.cuda.is_available():
inputs = {key: value.to(model.device) for key, value in inputs.items()}
with torch.no_grad():
output = model.generate(**inputs, max_new_tokens=64, do_sample=False)
try:
decoded = processor.batch_decode(output, skip_special_tokens=True)[0]
except Exception:
decoded = str(output)
return {
"output_text_tail": decoded[-500:],
"batch": 1,
"loader": "AutoModelForImageTextToText",
"processor_causal_loader_error": processor_causal_error,
"tokenizer_causal_loader_error": tokenizer_causal_error,
}
except Exception as image_text_exc:
raise RuntimeError(
"All causal/multimodal loaders failed: "
f"processor_causal={processor_causal_error}; "
f"tokenizer_causal={tokenizer_causal_error}; "
f"image_text={image_text_exc!r}"
) from image_text_exc
TASK_RUNNERS = {
"embedding": smoke_embedding,
"reranker": smoke_reranker,
"encoder_classifier": smoke_encoder_classifier,
"nli": smoke_nli,
"causal_json": smoke_causal_json,
}
def result_key(result: dict[str, Any]) -> str:
return f"{result['module']}::{result['dataset']}"
def spec_key(spec: dict[str, Any]) -> str:
return f"{spec['module']}::{spec['dataset']}"
def run_runner(spec: dict[str, Any]) -> tuple[dict[str, Any], float | None]:
reset_peak_memory()
runner = TASK_RUNNERS[spec["task"]]
details = runner(spec)
peak = peak_vram_gb()
return details, peak
def run_one(spec: dict[str, Any], mode: str, allow_cpu: bool) -> dict[str, Any]:
deps = dependency_status()
cuda = cuda_status()
missing = [name for name, ok in deps.items() if name in REQUIRED_PACKAGES and not ok]
if "4bit" in str(spec.get("quantization", "")).casefold() and not deps.get("bitsandbytes"):
missing.append("bitsandbytes")
result: dict[str, Any] = {
"module": spec["module"],
"group": spec.get("group", ""),
"dataset": spec["dataset"],
"main_model": spec["main_model"],
"model_id": spec["model_id"],
"backup": spec.get("backup", ""),
"backup_model_id": spec.get("backup_model_id", ""),
"task": spec["task"],
"quantization": spec.get("quantization", ""),
"max_test_batch": spec.get("max_test_batch", ""),
"load_status": "PENDING",
"peak_vram_gb": "",
"decision": "pending",
"error": "",
"details": {},
"tested_model_id": "",
"used_backup": False,
}
if missing:
result["load_status"] = "BLOCKED_MISSING_DEPENDENCY"
result["decision"] = "install_dependencies"
result["error"] = "Missing packages: " + ", ".join(sorted(set(missing)))
return result
if spec.get("requires_cuda", True) and not cuda.get("cuda_available") and not allow_cpu:
result["load_status"] = "BLOCKED_NO_CUDA"
result["decision"] = "wait_for_cuda_or_run_with_allow_cpu"
result["error"] = "CUDA is required by config"
return result
if mode == "metadata":
result["load_status"] = "PENDING_METADATA_ONLY"
result["decision"] = "run_full_smoke"
return result
start = time.time()
try:
details, peak = run_runner(copy.deepcopy(spec))
result["details"] = details
result["peak_vram_gb"] = peak
result["load_status"] = "PASS"
result["decision"] = "keep"
result["tested_model_id"] = spec["model_id"]
except Exception as exc: # noqa: BLE001 - report must capture model load failures.
main_error = repr(exc)
main_traceback = traceback.format_exc(limit=8)
backup_model_id = spec.get("backup_model_id")
if backup_model_id:
try:
cleanup_torch()
backup_spec = copy.deepcopy(spec)
backup_spec["model_id"] = backup_model_id
backup_spec["main_model"] = spec.get("backup", backup_model_id)
details, peak = run_runner(backup_spec)
result["details"] = details
result["details"]["main_model_error"] = main_error
result["peak_vram_gb"] = peak
result["load_status"] = "PASS_BACKUP"
result["decision"] = "fallback"
result["tested_model_id"] = backup_model_id
result["used_backup"] = True
except Exception as backup_exc: # noqa: BLE001
result["load_status"] = "FAIL"
result["decision"] = "fallback_or_fix"
result["error"] = f"main={main_error}; backup={backup_exc!r}"
result["traceback"] = main_traceback + "\n--- BACKUP TRACEBACK ---\n" + traceback.format_exc(limit=8)
try:
result["peak_vram_gb"] = peak_vram_gb()
except Exception: # noqa: BLE001
result["peak_vram_gb"] = ""
else:
result["load_status"] = "FAIL"
result["decision"] = "fallback_or_fix"
result["error"] = main_error
result["traceback"] = main_traceback
try:
result["peak_vram_gb"] = peak_vram_gb()
except Exception: # noqa: BLE001
result["peak_vram_gb"] = ""
finally:
cleanup_torch()
result["elapsed_sec"] = round(time.time() - start, 3)
return result
def status_is_pass(status: str) -> bool:
return status in PASS_STATUSES
def filter_specs(specs: list[dict[str, Any]], group: str) -> list[dict[str, Any]]:
if group == "all":
return specs
return [spec for spec in specs if spec.get("group") == group]
def placeholder_result(spec: dict[str, Any]) -> dict[str, Any]:
return {
"module": spec["module"],
"group": spec.get("group", ""),
"dataset": spec["dataset"],
"main_model": spec["main_model"],
"model_id": spec["model_id"],
"backup": spec.get("backup", ""),
"backup_model_id": spec.get("backup_model_id", ""),
"task": spec["task"],
"quantization": spec.get("quantization", ""),
"max_test_batch": spec.get("max_test_batch", ""),
"load_status": "NOT_RUN",
"peak_vram_gb": "",
"decision": "run_smoke_test",
"error": "",
"details": {},
"tested_model_id": "",
"used_backup": False,
}
def merge_results(existing_report: dict[str, Any], specs: list[dict[str, Any]], new_results: list[dict[str, Any]]) -> list[dict[str, Any]]:
merged = {spec_key(spec): placeholder_result(spec) for spec in specs}
for result in existing_report.get("results", []) or []:
key = result_key(result)
if key in merged:
if result.get("load_status") == "BLOCKED_MISSING_DEPENDENCY":
continue
merged[key].update(result)
for result in new_results:
merged[result_key(result)] = result
return [merged[spec_key(spec)] for spec in specs]
def modules_pass(results: list[dict[str, Any]], required_modules: set[str]) -> bool:
status_by_module = {result["module"]: result["load_status"] for result in results}
return all(status_is_pass(status_by_module.get(module, "")) for module in required_modules)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--config", type=Path, default=Path("configs/model/model_stack.yaml"))
parser.add_argument("--report", type=Path, default=Path("outputs/stats/model_smoke_test_report.json"))
parser.add_argument("--memory-csv", type=Path, default=Path("outputs/stats/model_memory_report.csv"))
parser.add_argument("--table", type=Path, default=Path("outputs/tables/T4_model_stack.csv"))
parser.add_argument("--mode", choices=["full", "metadata"], default=os.environ.get("SMOKE_TEST_MODE", "full"))
parser.add_argument("--group", choices=sorted(VALID_GROUPS), default="all")
parser.add_argument("--merge-existing", action="store_true")
parser.add_argument("--allow-cpu", action="store_true")
parser.add_argument("--strict", action="store_true")
args = parser.parse_args()
config = yaml.safe_load(args.config.read_text(encoding="utf-8"))
specs = config["models"]
selected_specs = filter_specs(specs, args.group)
if not selected_specs and args.group != "all":
print(f"No model specs selected for group={args.group}")
new_results = [run_one(spec, mode=args.mode, allow_cpu=args.allow_cpu) for spec in selected_specs]
existing_report = {}
if args.merge_existing and args.report.exists():
try:
existing_report = json.loads(args.report.read_text(encoding="utf-8"))
except json.JSONDecodeError:
existing_report = {}
results = merge_results(existing_report, specs, new_results)
overall_pass = all(status_is_pass(result["load_status"]) for result in results)
minimum_pass = modules_pass(results, MINIMUM_REQUIRED_MODULES)
wikikg_pass = modules_pass(results, WIKIKG_REQUIRED_MODULES)
llm_baseline_pass = modules_pass(results, LLM_BASELINE_REQUIRED_MODULES)
report = {
"mode": args.mode,
"requested_group": args.group,
"overall_pass": overall_pass,
"minimum_pass": minimum_pass,
"wikikg_pass": wikikg_pass,
"llm_baseline_pass": llm_baseline_pass,
"dependencies": dependency_status(),
"cuda": cuda_status(),
"results": results,
}
write_json(args.report, report)
memory_rows = [
{
"module": result["module"],
"group": result.get("group", ""),
"dataset": result["dataset"],
"model_id": result["model_id"],
"tested_model_id": result.get("tested_model_id", ""),
"task": result["task"],
"load_status": result["load_status"],
"peak_vram_gb": result["peak_vram_gb"],
"elapsed_sec": result.get("elapsed_sec", ""),
"max_test_batch": result["max_test_batch"],
"error": result["error"],
}
for result in results
]
write_csv(args.memory_csv, memory_rows)
t4_rows = [
{
"Module": result["module"],
"Dataset": result["dataset"],
"Main model": result["main_model"],
"Backup": result["backup"],
"Load status": result["load_status"],
"Peak VRAM GB": result["peak_vram_gb"],
"Max test batch": result["max_test_batch"],
"Decision": result["decision"],
}
for result in results
]
write_csv(args.table, t4_rows)
print(
f"Wrote model smoke report to {args.report}. "
f"PASS={overall_pass} MINIMUM_PASS={minimum_pass} WIKIKG_PASS={wikikg_pass}"
)
if args.strict and not overall_pass:
raise SystemExit(1)
if __name__ == "__main__":
main()