knowledge-drift-experiments / fix_query_grammar.py
Raniahossam33's picture
Upload folder using huggingface_hub
14b2318 verified
Raw
History Blame Contribute Delete
11.6 kB
"""
Fix Query Grammar with LLM
============================
After mechanically adding "In YYYY," to TempLAMA queries,
use Gemini to fix grammar while preserving:
- The year
- The entity
- The relation
- The ___ blank (if present)
- The factual meaning
Usage:
cd ~/svd_kg/knowledge_drift
python fix_query_grammar.py
"""
import json, os, re, time, sys
from collections import Counter
from concurrent.futures import ThreadPoolExecutor, as_completed
from threading import Lock
import google.generativeai as genai
# ============================================================
# CONFIG
# ============================================================
GEMINI_MODEL = "gemini-2.5-flash"
GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY", "")
if not GOOGLE_API_KEY:
print("Set GOOGLE_API_KEY environment variable or edit this script")
sys.exit(1)
RATE_LIMIT_DELAY = 0.15
MAX_WORKERS = 100
BATCH_SIZE = 20 # queries per LLM call
TIER1_PATH = "data/knowledge_drift_unified_tier1.json"
OUTPUT_PATH = "data/knowledge_drift_unified_tier1_clean.json"
BACKUP_PATH = "data/knowledge_drift_unified_tier1_prefixed_backup.json"
# ============================================================
# SETUP
# ============================================================
genai.configure(api_key=GOOGLE_API_KEY)
model = genai.GenerativeModel(GEMINI_MODEL)
print("=" * 70)
print(" FIX QUERY GRAMMAR WITH LLM")
print("=" * 70)
# ============================================================
# STEP 1: LOAD AND ADD YEAR PREFIXES MECHANICALLY
# ============================================================
print("\nStep 1: Loading and adding year prefixes...")
with open(TIER1_PATH) as f:
tier1 = json.load(f)
samples = tier1["samples"]
print(f" Loaded: {len(samples)} samples")
# Remove noise first
REMOVE_RELATIONS = {"", "رئيس", "رئيس الوزراء", "معايير الصكوك", "ولي العهد",
"member countries expansion", "political situation",
"board and leadership changes"}
samples = [s for s in samples if s.get("relation", "") not in REMOVE_RELATIONS]
print(f" After noise removal: {len(samples)}")
def has_year_prefix(query):
return bool(re.match(r'^In \d{4},?\s', query))
# Track which queries need fixing
queries_to_fix = [] # list of (index, original_query, year)
for i, s in enumerate(samples):
query = s.get("query", "")
year = s.get("year", None)
if not has_year_prefix(query) and year:
try:
year_int = int(year)
# Mechanical prefix first
if query.startswith("_"):
mechanical = f"In {year_int}, {query}"
else:
mechanical = f"In {year_int}, {query[0].lower()}{query[1:]}"
queries_to_fix.append((i, query, mechanical, year_int))
s["query_original"] = query
s["query"] = mechanical # temporary, will be overwritten by LLM
except (ValueError, TypeError):
pass
print(f" Queries needing year prefix: {len(queries_to_fix)}")
print(f" Queries already with prefix: {len(samples) - len(queries_to_fix)}")
# ============================================================
# STEP 2: FIX GRAMMAR WITH GEMINI IN BATCHES
# ============================================================
print(f"\nStep 2: Fixing grammar with {GEMINI_MODEL}...")
print(f" Batches: {len(queries_to_fix) // BATCH_SIZE + 1} ({BATCH_SIZE} queries each)")
SYSTEM_PROMPT = """You are a grammar editor. You will receive a batch of factual queries that have been mechanically modified by prepending "In YYYY," to them. Some may read awkwardly.
Your job: Fix ONLY the grammar to make each query read naturally, while preserving:
1. The exact year mentioned
2. The entity names (do NOT change names)
3. The blank marker "___" (keep it exactly as ___)
4. The factual meaning (do NOT change what is being asked)
Rules:
- Keep it concise — don't add extra words unnecessarily
- Preserve the format: the query should be a factual statement or question
- If the query already reads fine, return it unchanged
- Do NOT add periods or punctuation that wasn't there
Return ONLY a JSON array of fixed queries, one per input, in the same order. No explanation."""
lock = Lock()
fixed_queries = {} # index -> fixed query
errors = []
total_done = 0
def fix_batch(batch):
"""Send a batch of queries to Gemini, return fixed versions."""
indices = [b[0] for b in batch]
mechanicals = [b[2] for b in batch]
prompt = f"""Fix the grammar of these {len(mechanicals)} queries. Return a JSON array of strings.
Queries:
{json.dumps(mechanicals, indent=2)}"""
try:
response = model.generate_content(
[{"role": "user", "parts": [prompt]}],
generation_config=genai.types.GenerationConfig(
temperature=0.0,
max_output_tokens=4096,
),
)
text = response.text.strip()
# Extract JSON array from response
# Handle markdown code blocks
if "```json" in text:
text = text.split("```json")[1].split("```")[0].strip()
elif "```" in text:
text = text.split("```")[1].split("```")[0].strip()
fixed = json.loads(text)
if len(fixed) != len(indices):
# Length mismatch — fall back to mechanical
return {idx: mech for idx, mech in zip(indices, mechanicals)}
return {idx: f for idx, f in zip(indices, fixed)}
except Exception as e:
# Fall back to mechanical version
return {idx: mech for idx, mech in zip(indices, mechanicals)}
# Create batches
batches = []
for i in range(0, len(queries_to_fix), BATCH_SIZE):
batches.append(queries_to_fix[i:i + BATCH_SIZE])
print(f" Processing {len(batches)} batches with {MAX_WORKERS} workers...")
with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
futures = {}
for batch_idx, batch in enumerate(batches):
future = executor.submit(fix_batch, batch)
futures[future] = batch_idx
time.sleep(RATE_LIMIT_DELAY)
for future in as_completed(futures):
batch_idx = futures[future]
try:
result = future.result()
with lock:
fixed_queries.update(result)
total_done += len(result)
if total_done % 200 == 0 or total_done == len(queries_to_fix):
print(f" Progress: {total_done}/{len(queries_to_fix)} ({total_done/len(queries_to_fix)*100:.1f}%)")
except Exception as e:
errors.append((batch_idx, str(e)))
# Use mechanical versions for failed batches
batch = batches[batch_idx]
with lock:
for idx, orig, mech, yr in batch:
fixed_queries[idx] = mech
total_done += len(batch)
print(f" Done. Fixed: {len(fixed_queries)}, Errors: {len(errors)}")
# ============================================================
# STEP 3: APPLY FIXES
# ============================================================
print("\nStep 3: Applying fixes...")
applied = 0
for idx, orig, mech, yr in queries_to_fix:
if idx in fixed_queries:
fixed = fixed_queries[idx]
# Validate: must still contain the year
if str(yr) in fixed and len(fixed) > 10:
samples[idx]["query"] = fixed
else:
# LLM broke it — use mechanical
samples[idx]["query"] = mech
applied += 1
else:
samples[idx]["query"] = mech
applied += 1
print(f" Applied: {applied} fixes")
# ============================================================
# STEP 4: SHOW EXAMPLES
# ============================================================
print("\nStep 4: Examples of fixes...")
print(f"\n {'Original':50s}{'Fixed':50s}")
print(" " + "-" * 105)
count = 0
for idx, orig, mech, yr in queries_to_fix[:15]:
fixed = samples[idx]["query"]
if fixed != mech: # LLM actually changed something
print(f" {orig[:50]:50s}{fixed[:50]:50s}")
count += 1
if count >= 10:
break
if count == 0:
print(" (LLM kept all mechanical versions unchanged — grammar was fine)")
for idx, orig, mech, yr in queries_to_fix[:5]:
print(f" {orig[:50]:50s}{samples[idx]['query'][:50]:50s}")
# ============================================================
# STEP 5: VERIFY
# ============================================================
print("\nStep 5: Verification...")
n_with = sum(1 for s in samples if has_year_prefix(s.get("query", "")))
n_without = len(samples) - n_with
print(f" With year prefix: {n_with}/{len(samples)} ({n_with/len(samples)*100:.1f}%)")
print(f" Without year prefix: {n_without}")
# Check drift rate is no longer confounded with format
for has_yr in [True, False]:
subset = [s for s in samples if has_year_prefix(s.get("query", "")) == has_yr]
if not subset:
continue
n_d = sum(1 for s in subset if s.get("is_drifted_qwen25", False))
pct = n_d / len(subset) * 100
label = "with year" if has_yr else "no year"
print(f" {label}: {n_d}/{len(subset)} drifted for Qwen ({pct:.1f}%)")
# ============================================================
# STEP 6: SAVE
# ============================================================
print("\nStep 6: Saving...")
# Re-number
for i, s in enumerate(samples):
s["sample_id"] = f"tier1_v2_{str(i).zfill(6)}"
tier1["samples"] = samples
tier1["metadata"]["total_samples"] = len(samples)
tier1["metadata"]["version"] = "2.1_grammar_fixed"
# Save clean version
with open(OUTPUT_PATH, "w") as f:
json.dump(tier1, f, indent=2, ensure_ascii=False)
print(f" Saved: {OUTPUT_PATH} ({len(samples)} samples)")
# Also update main tier1
with open(TIER1_PATH, "w") as f:
json.dump(tier1, f, indent=2, ensure_ascii=False)
print(f" Updated: {TIER1_PATH}")
# ============================================================
# STEP 7: CREATE PER-MODEL DATASETS
# ============================================================
print("\nStep 7: Creating per-model datasets...")
MODELS = {
"llama2": "is_drifted_llama2",
"mistral": "is_drifted_mistral",
"llama31": "is_drifted_llama31",
"qwen25": "is_drifted_qwen25",
"gemma2": "is_drifted_gemma2",
}
for model_name, drift_key in MODELS.items():
model_dataset = json.loads(json.dumps(tier1))
for s in model_dataset["samples"]:
s["is_drifted_query"] = s.get(drift_key, False)
s["temporal_zone"] = "post_cutoff"
path = f"data/tier1_{model_name}.json"
with open(path, "w") as f:
json.dump(model_dataset, f, indent=2, ensure_ascii=False)
n_d = sum(1 for s in model_dataset["samples"] if s["is_drifted_query"])
print(f" {model_name:10s}: {path} ({n_d} drifted, {len(samples)-n_d} stable)")
# ============================================================
# DONE
# ============================================================
print(f"""
{'=' * 70}
DONE — ALL DATASETS READY
{'=' * 70}
Clean Tier 1: {OUTPUT_PATH} ({len(samples)} samples)
All queries now have uniform year-prefix format.
Grammar verified by {GEMINI_MODEL}.
Noise samples removed.
Per-model datasets created.
NEXT: Re-extract hidden states for Qwen on the fixed data:
python disentanglement_v2.py \\
--model Qwen/Qwen2.5-7B-Instruct \\
--dataset data/tier1_qwen25.json \\
--output_dir data/experiments/tier1_qwen25_v2
{'=' * 70}
""")