knowledge-drift-experiments / validate_and_clean_dataset.py
Raniahossam33's picture
Upload folder using huggingface_hub
14b2318 verified
Raw
History Blame Contribute Delete
27.2 kB
"""
Dataset Validation & Cleaning for Knowledge Drift Detection
=============================================================
The Wikidata SPARQL queries have critical data quality issues:
PROBLEM: SPARQL temporal qualifiers return ALL historical holders,
not just the most recent change. So "head of state of Romania in 2025"
might return "Nicolae Ceaușescu" (executed 1989) because his end_date
is recorded as a datetime that Wikidata parsed oddly.
This script:
1. Diagnoses all samples for obvious errors
2. Filters to ONLY manually verified + web-validated facts
3. Expands the verified set with additional curated examples
4. Produces a clean dataset ready for experiments
Usage:
python validate_and_clean_dataset.py \
--input data/knowledge_drift_dataset.json \
--output data/knowledge_drift_clean.json
"""
import json
import argparse
import logging
import os
from datetime import datetime
from collections import Counter, defaultdict
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# ============================================================
# EXPANDED VERIFIED FACTS (Manually researched, high confidence)
# ============================================================
# Each entry has: entity, relation, old_answer (pre-cutoff), new_answer (post-cutoff),
# change_date, and query templates. These are the GOLD STANDARD.
VERIFIED_DRIFTED_FACTS = [
# === POLITICAL LEADERS (highest confidence) ===
{
"entity": "United Kingdom",
"relation": "Prime Minister",
"knowledge_type": "entity_role",
"old_answer": "Rishi Sunak",
"new_answer": "Keir Starmer",
"change_date": "2024-07-05",
"confidence": "high",
"source": "public_record",
"templates": [
"Who is the Prime Minister of the United Kingdom in {year}?",
"In {year}, the Prime Minister of the UK was ___.",
"As of {year}, who leads the British government?",
],
},
{
"entity": "United States",
"relation": "President",
"knowledge_type": "entity_role",
"old_answer": "Joe Biden",
"new_answer": "Donald Trump",
"change_date": "2025-01-20",
"confidence": "high",
"source": "public_record",
"templates": [
"Who is the President of the United States in {year}?",
"In {year}, the US President was ___.",
"As of {year}, who is the American president?",
],
},
{
"entity": "Japan",
"relation": "Prime Minister",
"knowledge_type": "entity_role",
"old_answer": "Fumio Kishida",
"new_answer": "Shigeru Ishiba",
"change_date": "2024-10-01",
"confidence": "high",
"source": "public_record",
"templates": [
"Who is the Prime Minister of Japan in {year}?",
"In {year}, Japan's Prime Minister was ___.",
],
},
{
"entity": "Syria",
"relation": "Leader",
"knowledge_type": "entity_role",
"old_answer": "Bashar al-Assad",
"new_answer": "Ahmad al-Sharaa",
"change_date": "2024-12-08",
"confidence": "high",
"source": "public_record",
"templates": [
"Who is the leader of Syria in {year}?",
"In {year}, Syria was led by ___.",
"As of {year}, who controls Syria?",
],
},
{
"entity": "Mexico",
"relation": "President",
"knowledge_type": "entity_role",
"old_answer": "Andrés Manuel López Obrador",
"new_answer": "Claudia Sheinbaum",
"change_date": "2024-10-01",
"confidence": "high",
"source": "public_record",
"templates": [
"Who is the President of Mexico in {year}?",
"In {year}, Mexico's President was ___.",
],
},
{
"entity": "Indonesia",
"relation": "President",
"knowledge_type": "entity_role",
"old_answer": "Joko Widodo",
"new_answer": "Prabowo Subianto",
"change_date": "2024-10-20",
"confidence": "high",
"source": "public_record",
"templates": [
"Who is the President of Indonesia in {year}?",
"In {year}, Indonesia's President was ___.",
],
},
{
"entity": "India",
"relation": "Prime Minister",
"knowledge_type": "entity_role",
"old_answer": "Narendra Modi",
"new_answer": "Narendra Modi", # re-elected — CONTROL
"change_date": "2024-06-09",
"confidence": "high",
"source": "public_record",
"note": "CONTROL: same person re-elected, answer unchanged despite event",
"templates": [
"Who is the Prime Minister of India in {year}?",
"In {year}, India's Prime Minister was ___.",
],
},
{
"entity": "South Korea",
"relation": "President",
"knowledge_type": "entity_role",
"old_answer": "Yoon Suk-yeol",
"new_answer": "Han Duck-soo",
"change_date": "2024-12-14",
"confidence": "medium",
"source": "public_record",
"note": "Yoon impeached Dec 2024, acting president Han Duck-soo",
"templates": [
"Who is the President of South Korea in {year}?",
"In {year}, South Korea's President was ___.",
],
},
{
"entity": "Sri Lanka",
"relation": "President",
"knowledge_type": "entity_role",
"old_answer": "Ranil Wickremesinghe",
"new_answer": "Anura Kumara Dissanayake",
"change_date": "2024-09-23",
"confidence": "high",
"source": "public_record",
"templates": [
"Who is the President of Sri Lanka in {year}?",
"In {year}, Sri Lanka's President was ___.",
],
},
# === CORPORATE ===
{
"entity": "Intel",
"relation": "CEO",
"knowledge_type": "entity_role",
"old_answer": "Pat Gelsinger",
"new_answer": "Lip-Bu Tan",
"change_date": "2024-12-01",
"confidence": "high",
"source": "public_record",
"note": "Gelsinger resigned Dec 2024; interim then Lip-Bu Tan appointed Mar 2025",
"templates": [
"Who is the CEO of Intel in {year}?",
"In {year}, Intel's CEO was ___.",
],
},
{
"entity": "Nike",
"relation": "CEO",
"knowledge_type": "entity_role",
"old_answer": "John Donahoe",
"new_answer": "Elliott Hill",
"change_date": "2024-10-14",
"confidence": "high",
"source": "public_record",
"templates": [
"Who is the CEO of Nike in {year}?",
"In {year}, Nike's CEO was ___.",
],
},
{
"entity": "Starbucks",
"relation": "CEO",
"knowledge_type": "entity_role",
"old_answer": "Laxman Narasimhan",
"new_answer": "Brian Niccol",
"change_date": "2024-09-09",
"confidence": "high",
"source": "public_record",
"templates": [
"Who is the CEO of Starbucks in {year}?",
"In {year}, the CEO of Starbucks was ___.",
],
},
# === ORGANIZATIONS / GEOPOLITICAL ===
{
"entity": "BRICS",
"relation": "member countries",
"knowledge_type": "relational",
"old_answer": "Brazil, Russia, India, China, South Africa",
"new_answer": "Brazil, Russia, India, China, South Africa, Iran, Egypt, Ethiopia, UAE, Saudi Arabia",
"change_date": "2024-01-01",
"confidence": "high",
"source": "public_record",
"note": "Expansion announced Aug 2023, effective Jan 2024. Near cutoff — model may partially know.",
"templates": [
"Which countries are members of BRICS in {year}?",
"In {year}, the BRICS members included ___.",
],
},
{
"entity": "OpenAI",
"relation": "corporate structure",
"knowledge_type": "relational",
"old_answer": "nonprofit with capped-profit subsidiary",
"new_answer": "public benefit corporation (for-profit transition)",
"change_date": "2024-12-27",
"confidence": "medium",
"source": "public_record",
"note": "Announced transition to PBC in late 2024",
"templates": [
"What is OpenAI's corporate structure in {year}?",
"In {year}, OpenAI was organized as ___.",
],
},
]
# === VERIFIED UNCHANGED FACTS (Category 4: same type, didn't change) ===
VERIFIED_UNCHANGED_FACTS = [
{"entity": "Saudi Arabia", "relation": "King", "answer": "King Salman bin Abdulaziz", "since": "2015",
"templates": ["Who is the King of Saudi Arabia in {year}?", "In {year}, the King of Saudi Arabia was ___."]},
{"entity": "UAE", "relation": "President", "answer": "Mohamed bin Zayed Al Nahyan", "since": "2022",
"templates": ["Who is the President of the UAE in {year}?", "In {year}, the UAE President was ___."]},
{"entity": "Russia", "relation": "President", "answer": "Vladimir Putin", "since": "2012",
"templates": ["Who is the President of Russia in {year}?", "In {year}, Russia's President was ___."]},
{"entity": "China", "relation": "President", "answer": "Xi Jinping", "since": "2013",
"templates": ["Who is the President of China in {year}?", "In {year}, China's President was ___."]},
{"entity": "France", "relation": "President", "answer": "Emmanuel Macron", "since": "2017",
"templates": ["Who is the President of France in {year}?", "In {year}, France's President was ___."]},
{"entity": "Egypt", "relation": "President", "answer": "Abdel Fattah el-Sisi", "since": "2014",
"templates": ["Who is the President of Egypt in {year}?", "In {year}, Egypt's President was ___."]},
{"entity": "Apple", "relation": "CEO", "answer": "Tim Cook", "since": "2011",
"templates": ["Who is the CEO of Apple in {year}?", "In {year}, Apple's CEO was ___."]},
{"entity": "Microsoft", "relation": "CEO", "answer": "Satya Nadella", "since": "2014",
"templates": ["Who is the CEO of Microsoft in {year}?", "In {year}, Microsoft's CEO was ___."]},
{"entity": "Amazon", "relation": "CEO", "answer": "Andy Jassy", "since": "2021",
"templates": ["Who is the CEO of Amazon in {year}?", "In {year}, Amazon's CEO was ___."]},
{"entity": "Tesla", "relation": "CEO", "answer": "Elon Musk", "since": "2008",
"templates": ["Who is the CEO of Tesla in {year}?", "In {year}, Tesla's CEO was ___."]},
{"entity": "Google", "relation": "CEO", "answer": "Sundar Pichai", "since": "2015",
"templates": ["Who is the CEO of Google in {year}?", "In {year}, Google's CEO was ___."]},
{"entity": "Turkey", "relation": "President", "answer": "Recep Tayyip Erdoğan", "since": "2014",
"templates": ["Who is the President of Turkey in {year}?", "In {year}, Turkey's President was ___."]},
{"entity": "Germany", "relation": "Chancellor", "answer": "Olaf Scholz", "since": "2021",
"templates": ["Who is the Chancellor of Germany in {year}?", "In {year}, Germany's Chancellor was ___."]},
{"entity": "Canada", "relation": "Prime Minister", "answer": "Justin Trudeau", "since": "2015",
"templates": ["Who is the Prime Minister of Canada in {year}?", "In {year}, Canada's PM was ___."]},
{"entity": "Israel", "relation": "Prime Minister", "answer": "Benjamin Netanyahu", "since": "2022",
"templates": ["Who is the Prime Minister of Israel in {year}?", "In {year}, Israel's PM was ___."]},
{"entity": "Meta", "relation": "CEO", "answer": "Mark Zuckerberg", "since": "2004",
"templates": ["Who is the CEO of Meta in {year}?", "In {year}, Meta's CEO was ___."]},
{"entity": "NVIDIA", "relation": "CEO", "answer": "Jensen Huang", "since": "1993",
"templates": ["Who is the CEO of NVIDIA in {year}?", "In {year}, NVIDIA's CEO was ___."]},
]
# === STABLE FACTS (Category 1: timeless, never change) ===
STABLE_FACTS_EXPANDED = [
# Geography
{"query": "What is the capital of France?", "answer": "Paris", "type": "geographical"},
{"query": "What is the capital of Japan?", "answer": "Tokyo", "type": "geographical"},
{"query": "What is the capital of Egypt?", "answer": "Cairo", "type": "geographical"},
{"query": "What is the capital of Germany?", "answer": "Berlin", "type": "geographical"},
{"query": "What is the capital of Saudi Arabia?", "answer": "Riyadh", "type": "geographical"},
{"query": "What is the capital of UAE?", "answer": "Abu Dhabi", "type": "geographical"},
{"query": "What is the capital of Brazil?", "answer": "Brasília", "type": "geographical"},
{"query": "What is the capital of Australia?", "answer": "Canberra", "type": "geographical"},
{"query": "What is the capital of South Korea?", "answer": "Seoul", "type": "geographical"},
{"query": "What is the capital of Morocco?", "answer": "Rabat", "type": "geographical"},
{"query": "What is the longest river in the world?", "answer": "the Nile", "type": "geographical"},
{"query": "What is the highest mountain in the world?", "answer": "Mount Everest", "type": "geographical"},
{"query": "What is the largest ocean?", "answer": "the Pacific Ocean", "type": "geographical"},
# Science
{"query": "What is the chemical formula for water?", "answer": "H2O", "type": "scientific"},
{"query": "What is the speed of light in km/s?", "answer": "approximately 300,000", "type": "scientific"},
{"query": "What does DNA stand for?", "answer": "deoxyribonucleic acid", "type": "scientific"},
{"query": "What is the force of gravity on Earth in m/s²?", "answer": "9.8", "type": "scientific"},
{"query": "What is absolute zero in Celsius?", "answer": "-273.15", "type": "scientific"},
# Math
{"query": "What is the value of pi to two decimal places?", "answer": "3.14", "type": "mathematical"},
{"query": "What is the square root of 144?", "answer": "12", "type": "mathematical"},
{"query": "What is 2 to the power of 10?", "answer": "1024", "type": "mathematical"},
# History
{"query": "When did World War II end?", "answer": "1945", "type": "historical"},
{"query": "When was the first moon landing?", "answer": "1969", "type": "historical"},
{"query": "When did the Berlin Wall fall?", "answer": "1989", "type": "historical"},
{"query": "Who painted the Mona Lisa?", "answer": "Leonardo da Vinci", "type": "historical"},
]
MODEL_CUTOFF = "2024-08-01"
TIMESTAMP_YEARS = [2020, 2022, 2023, 2024, 2025]
def diagnose_existing_dataset(dataset_path):
"""Analyze existing dataset for quality issues."""
with open(dataset_path, 'r') as f:
dataset = json.load(f)
samples = dataset.get("samples", [])
logger.info(f"Loaded {len(samples)} samples from {dataset_path}")
issues = []
stats = Counter()
# Known dead people / historical figures that should never appear as 2025 answers
impossible_2025 = [
"abraham lincoln", "Nicolae Ceaușescu".lower(), "george washington",
"winston churchill", "joseph stalin", "mao zedong", "gandhi",
"john f. kennedy", "josef klaus", "walter zenga", "wolfgang schüssel",
]
for i, s in enumerate(samples):
stats[s.get("category", "unknown")] += 1
stats[f"drifted={s.get('is_drifted_query', False)}"] += 1
stats[f"source={s.get('source', 'unknown')}"] += 1
# Check for obviously wrong answers
exp = s.get("expected_answer", "").lower()
old = s.get("model_likely_answer", "").lower()
year = s.get("year", 0)
entity = s.get("entity", "")
# Flag: historical figure as 2025 answer
for imp in impossible_2025:
if imp in exp and year >= 2024:
issues.append({
"index": i, "severity": "CRITICAL",
"issue": f"Historical/dead figure '{s.get('expected_answer')}' as {year} answer for {entity}",
"query": s.get("query", ""),
"expected": s.get("expected_answer"),
"source": s.get("source"),
})
# Flag: old and new answer are the same (not a real drift)
if s.get("is_drifted_query") and exp == old and exp:
issues.append({
"index": i, "severity": "WARNING",
"issue": f"Drifted query but old==new answer: '{exp}'",
"query": s.get("query", ""),
"entity": entity,
})
# Flag: duplicate queries for same entity+year with different answers
# (collected separately below)
# Check for duplicate entity+year with conflicting answers
entity_year_answers = defaultdict(list)
for i, s in enumerate(samples):
key = (s.get("entity", ""), s.get("year", 0), s.get("relation", ""))
entity_year_answers[key].append({
"index": i,
"expected": s.get("expected_answer", ""),
"query": s.get("query", ""),
})
for key, entries in entity_year_answers.items():
answers = set(e["expected"] for e in entries)
if len(answers) > 1:
issues.append({
"severity": "CRITICAL",
"issue": f"CONFLICTING answers for {key}: {answers}",
"entries": entries,
})
# Print report
print("\n" + "=" * 80)
print(" DATASET QUALITY DIAGNOSIS")
print("=" * 80)
print(f"\nTotal samples: {len(samples)}")
print("\nBy category:")
for k, v in sorted(stats.items()):
print(f" {k}: {v}")
print(f"\n{'='*80}")
print(f" ISSUES FOUND: {len(issues)}")
print(f"{'='*80}")
critical = [i for i in issues if i["severity"] == "CRITICAL"]
warnings = [i for i in issues if i["severity"] == "WARNING"]
print(f"\n CRITICAL: {len(critical)}")
for issue in critical[:20]:
print(f" ❌ {issue['issue']}")
if 'query' in issue:
print(f" Query: {issue.get('query', '')[:80]}")
print(f"\n WARNINGS: {len(warnings)}")
for issue in warnings[:10]:
print(f" ⚠️ {issue['issue']}")
return issues, stats
def build_clean_dataset():
"""Build a clean dataset from ONLY verified facts."""
samples = []
sample_id = 0
# === 1. DRIFTED FACTS (Category 3: unknown_drift) ===
for fact in VERIFIED_DRIFTED_FACTS:
is_control = (fact["old_answer"] == fact["new_answer"])
for template in fact["templates"]:
for year in TIMESTAMP_YEARS:
change_year = int(fact["change_date"][:4])
change_month = int(fact["change_date"][5:7])
# Determine correct answer for this year
if year < change_year:
expected = fact["old_answer"]
is_drifted = False
elif year == change_year and change_month > 8:
# Changed after Qwen cutoff (Aug 2024) in the same year
# For 2024 queries, model likely knows old answer
expected = fact["old_answer"]
is_drifted = False
else:
expected = fact["new_answer"]
is_drifted = not is_control and year > 2024
# Temporal zone
if year < 2024:
temporal_zone = "pre_cutoff"
elif year == 2024:
temporal_zone = "near_cutoff"
else:
temporal_zone = "post_cutoff"
query = template.format(year=year)
sample = {
"id": f"verified_{sample_id:04d}",
"query": query,
"expected_answer": expected,
"model_likely_answer": fact["old_answer"] if is_drifted else "",
"entity": fact["entity"],
"relation": fact["relation"],
"knowledge_type": fact["knowledge_type"],
"category": "unknown_drift" if not is_control else "no_drift",
"is_drifted_query": is_drifted,
"year": year,
"temporal_zone": temporal_zone,
"change_date": fact["change_date"],
"confidence": fact.get("confidence", "high"),
"source": "manual_verified",
"note": fact.get("note", ""),
}
samples.append(sample)
sample_id += 1
# === 2. UNCHANGED FACTS (Category 4: no_drift, same type) ===
for fact in VERIFIED_UNCHANGED_FACTS:
for template in fact["templates"]:
for year in TIMESTAMP_YEARS:
if year < 2024:
temporal_zone = "pre_cutoff"
elif year == 2024:
temporal_zone = "near_cutoff"
else:
temporal_zone = "post_cutoff"
query = template.format(year=year)
sample = {
"id": f"unchanged_{sample_id:04d}",
"query": query,
"expected_answer": fact["answer"],
"model_likely_answer": "",
"entity": fact["entity"],
"relation": fact["relation"],
"knowledge_type": "entity_role",
"category": "no_drift",
"is_drifted_query": False,
"year": year,
"temporal_zone": temporal_zone,
"confidence": "high",
"source": "manual_verified",
}
samples.append(sample)
sample_id += 1
# === 3. STABLE FACTS (Category 1: timeless) ===
for fact in STABLE_FACTS_EXPANDED:
for year in TIMESTAMP_YEARS:
if year < 2024:
temporal_zone = "pre_cutoff"
elif year == 2024:
temporal_zone = "near_cutoff"
else:
temporal_zone = "post_cutoff"
query = f"In {year}, {fact['query'].lower()}" if not fact["query"].startswith("In") else fact["query"]
sample = {
"id": f"stable_{sample_id:04d}",
"query": query,
"expected_answer": fact["answer"],
"model_likely_answer": "",
"entity": fact["query"].split("?")[0] if "?" in fact["query"] else fact["query"],
"relation": "fact",
"knowledge_type": fact["type"],
"category": "stable",
"is_drifted_query": False,
"year": year,
"temporal_zone": temporal_zone,
"confidence": "high",
"source": "manual_curated",
}
samples.append(sample)
sample_id += 1
return samples
def print_dataset_stats(samples):
"""Print comprehensive stats for the clean dataset."""
print("\n" + "=" * 80)
print(" CLEAN DATASET STATISTICS")
print("=" * 80)
total = len(samples)
print(f"\nTotal samples: {total}")
# By category
cats = Counter(s["category"] for s in samples)
print("\nBy category:")
for k, v in sorted(cats.items()):
print(f" {k}: {v} ({100*v/total:.1f}%)")
# By temporal zone
zones = Counter(s["temporal_zone"] for s in samples)
print("\nBy temporal zone:")
for k, v in sorted(zones.items()):
print(f" {k}: {v}")
# Drifted queries
drifted = [s for s in samples if s["is_drifted_query"]]
not_drifted_post = [s for s in samples if not s["is_drifted_query"]
and s["temporal_zone"] == "post_cutoff"]
print(f"\nDrifted queries (post-cutoff, answer changed): {len(drifted)}")
print(f"Non-drifted post-cutoff queries: {len(not_drifted_post)}")
print(f"Ratio drifted / non-drifted (post-cutoff): {len(drifted)}/{len(not_drifted_post)}")
# By entity (drifted only)
if drifted:
ent = Counter(s["entity"] for s in drifted)
print(f"\nDrifted entities ({len(ent)} unique):")
for k, v in ent.most_common(15):
print(f" {k}: {v} queries")
# By knowledge type
kt = Counter(s["knowledge_type"] for s in samples)
print("\nBy knowledge type:")
for k, v in sorted(kt.items()):
print(f" {k}: {v}")
# By source
src = Counter(s["source"] for s in samples)
print("\nBy source:")
for k, v in sorted(src.items()):
print(f" {k}: {v}")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--input", default="data/knowledge_drift_dataset.json",
help="Original dataset to diagnose")
parser.add_argument("--output", default="data/knowledge_drift_clean.json",
help="Clean dataset output path")
parser.add_argument("--diagnose_only", action="store_true",
help="Only diagnose, don't build clean dataset")
args = parser.parse_args()
# === Step 1: Diagnose existing dataset ===
if os.path.exists(args.input):
print("\n" + "█" * 80)
print(" DIAGNOSING EXISTING DATASET")
print("█" * 80)
issues, stats = diagnose_existing_dataset(args.input)
else:
logger.warning(f"No existing dataset at {args.input}, skipping diagnosis")
if args.diagnose_only:
return
# === Step 2: Build clean dataset ===
print("\n" + "█" * 80)
print(" BUILDING CLEAN DATASET")
print("█" * 80)
samples = build_clean_dataset()
print_dataset_stats(samples)
# === Step 3: Save ===
os.makedirs(os.path.dirname(args.output) or ".", exist_ok=True)
dataset = {
"metadata": {
"description": "Clean knowledge drift detection dataset (verified facts only)",
"model": "Qwen/Qwen2.5-7B-Instruct",
"model_cutoff": MODEL_CUTOFF,
"created": datetime.now().isoformat(),
"num_samples": len(samples),
"num_drifted": len([s for s in samples if s["is_drifted_query"]]),
"num_entities_drifted": len(set(s["entity"] for s in samples if s["is_drifted_query"])),
"categories": dict(Counter(s["category"] for s in samples)),
"note": "Built from manually verified facts only. No Wikidata SPARQL (unreliable temporal data).",
},
"samples": samples,
}
with open(args.output, 'w', encoding='utf-8') as f:
json.dump(dataset, f, indent=2, ensure_ascii=False)
logger.info(f"\n✅ Clean dataset saved to {args.output}")
logger.info(f" {len(samples)} samples, {dataset['metadata']['num_drifted']} drifted")
logger.info(f"\n Run experiments with:")
logger.info(f" python run_experiments.py --dataset {args.output} --all --max_samples 200")
if __name__ == "__main__":
main()