jbcs2025_experiments_report / create_parquet_files.py
abarbosa's picture
add tucano results to experiments
ff634e1
import pandas as pd
from pathlib import Path
import pyarrow # ensures pyarrow is installed for Parquet support
import numpy as np
import sys
from tqdm.auto import tqdm
import logging
from datetime import datetime
# Add the api_models directory to the Python path to import existing modules
sys.path.append(str(Path(__file__).parent / "runs" / "api_models"))
from compute_bootstrap_ci import (
load_inference_results_by_grader,
extract_config_from_log,
)
from metrics import compute_metrics
from omegaconf import OmegaConf
# Set up logging
log_dir = Path("logs")
log_dir.mkdir(exist_ok=True)
log_file = log_dir / f"create_parquet_files_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
# Configure logging to write to both file and console
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(log_file),
logging.StreamHandler(sys.stdout)
]
)
logger = logging.getLogger(__name__)
# Also create a separate error-only log file
error_log_file = log_dir / f"create_parquet_files_errors_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
error_handler = logging.FileHandler(error_log_file)
error_handler.setLevel(logging.ERROR)
error_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
logger.addHandler(error_handler)
def simplify_experiment_name(name):
"""Simplify experiment names according to the mapping rules."""
if pd.isna(name):
return name
# Convert to string to handle any non-string inputs
name = str(name)
# Define the mapping rules
mappings = {
# Sabia-3 mappings
'sabia-3-zero-shot': 'sabia3-studentPrompt',
'sabia-3-extractor-zero-shot': 'sabia3-extractor',
'sabia-3-grader-zero-shot': 'sabia3-graderPrompt',
# Deepseek mappings
'deepseek-reasoner-zero-shot': 'deepseekR1-studentPrompt',
'deepseek-reasoner-extractor-zero-shot': 'deepseekR1-extractor',
'deepseek-reasoner-grader-zero-shot': 'deepseekR1-graderPrompt',
# GPT-4o mappings
'gpt-4o-2024-11-20-zero-shot': 'gpt4o-studentPrompt',
'gpt-4o-2024-11-20-extractor-zero-shot': 'gpt4o-extractor',
'gpt-4o-2024-11-20-grader-zero-shot': 'gpt4o-graderPrompt',
}
# Apply direct mappings first
for pattern, replacement in mappings.items():
if pattern in name:
name = name.replace(pattern, replacement)
# Handle jbcs2025 prefixed names
if name.startswith('jbcs2025_'):
# Remove the prefix
name = name[9:]
# First, remove any duplicated model-specific patterns that appear multiple times
# These patterns indicate the experiment setup was duplicated in the name
duplication_patterns = [
'llama31_classification_lora',
'phi35_classification_lora',
'phi4_classification_lora',
'encoder_classification'
'tucano_classification_lora'
]
for pattern in duplication_patterns:
# Count occurrences
count = name.count(f'-{pattern}-')
if count > 1:
# Replace all but keep track of components
parts = name.split(f'-{pattern}-')
# Keep the first part and the last part (which has the config)
if len(parts) > 2:
name = parts[0] + '-' + parts[-1]
# Handle BERT variants
if 'bert-base-portuguese-cased' in name:
name = name.replace('bert-base-portuguese-cased', 'bertimbau-base')
elif 'BERTugues-base-portuguese-cased' in name:
name = name.replace('BERTugues-base-portuguese-cased', 'bertugues-base')
elif 'bert-base-multilingual-cased' in name:
name = name.replace('bert-base-multilingual-cased', 'mbert-base')
elif 'bert-large-portuguese-cased' in name:
name = name.replace('bert-large-portuguese-cased', 'bertimbau-large')
elif 'albertina-1b5-portuguese-ptbr-encoder' in name:
name = name.replace('albertina-1b5-portuguese-ptbr-encoder', 'albertina-1b5-ptbr')
# Handle Llama variants
elif 'Llama-3.1-8B-llama31_classification_lora' in name:
name = name.replace('Llama-3.1-8B-llama31_classification_lora', 'llama3.1-8b-lora')
elif 'Llama-3.1-8B' in name:
name = name.replace('Llama-3.1-8B', 'llama3.1-8b-lora')
# Handle Tucano variants
elif 'Tucano-2b4-Instruct-tucano_classification_lora' in name:
name = name.replace('Tucano-2b4-Instruct-tucano_classification_lora', 'tucano2b4-lora')
elif 'Tucano-2b4-Instruct' in name:
name = name.replace('Tucano-2b4-Instruct', 'tucano2b4-lora')
# Handle Phi variants
elif 'Phi-3.5-mini-instruct-phi35_classification_lora' in name:
name = name.replace('Phi-3.5-mini-instruct-phi35_classification_lora', 'phi3.5-mini-lora')
elif 'Phi-3.5-mini-instruct' in name:
name = name.replace('Phi-3.5-mini-instruct', 'phi3.5-mini-lora')
elif 'phi-4-phi4_classification_lora' in name:
name = name.replace('phi-4-phi4_classification_lora', 'phi4-lora')
elif 'phi-4' in name:
name = name.replace('phi-4', 'phi4-lora')
# Clean up any remaining classification patterns
name = name.replace('-encoder_classification', '')
name = name.replace('_classification_lora', '')
name = name.replace('-llama31', '')
name = name.replace('-phi35', '')
name = name.replace('-phi4', '')
name = name.replace('-tucano', '')
# Extract components and reorder
parts = name.split('-')
# Look for competency (C1-C5), context type, and LoRA rank
competency = None
context = None
lora_rank = None
model_parts = []
i = 0
while i < len(parts):
part = parts[i]
if part in ['C1', 'C2', 'C3', 'C4', 'C5']:
competency = part
elif part == 'essay_only':
context = 'essay-only'
elif part == 'full_context':
context = 'full-context'
elif part in ['essay', 'full'] and i + 1 < len(parts):
# Handle split context names
if parts[i+1] == 'only':
context = 'essay-only'
i += 1 # Skip next part
elif parts[i+1] == 'context':
context = 'full-context'
i += 1 # Skip next part
elif part in ['r8', 'r16']:
lora_rank = part
elif part and part not in ['only', 'context']: # Skip empty parts and orphaned context words
model_parts.append(part)
i += 1
# Reconstruct the name in the desired order: model-competency-context-rank
new_parts = model_parts
if competency:
new_parts.append(competency)
if context:
new_parts.append(context)
if lora_rank:
new_parts.append(lora_rank)
name = '-'.join(new_parts)
# Final cleanup: remove any double dashes
while '--' in name:
name = name.replace('--', '-')
return name
def find_and_group_csvs():
base = Path(".")
groups = {
"evaluation_results": sorted(base.rglob("evaluation_results.csv")),
"bootstrap_confidence_intervals": sorted(
base.rglob("bootstrap_confidence_intervals.csv")
),
}
for name, paths in groups.items():
logger.info(f"Found {len(paths)} files for '{name}'")
if not paths:
logger.warning(f"No files found for '{name}'")
return groups
def enhance_evaluation_results(eval_df, csv_paths):
"""Enhance evaluation results with additional metrics from JSONL files."""
enhanced_rows = []
failed_count = 0
# Create a mapping from row index to CSV path
# Since we're processing multiple CSVs that get concatenated,
# we need to track which rows came from which CSV file
row_to_path = {}
current_idx = 0
for path in csv_paths:
df = pd.read_csv(path)
for i in range(len(df)):
row_to_path[current_idx + i] = path
current_idx += len(df)
for idx, row in tqdm(
eval_df.iterrows(), desc="Processing evaluation rows", total=len(eval_df)
):
# Get the CSV path for this row
csv_path = row_to_path.get(idx)
if csv_path is None:
error_msg = f"CSV file not found for row {idx}"
logger.error(error_msg)
failed_count += 1
continue
try:
# Extract experiment ID from the path
# The experiment ID is typically the parent directory name
experiment_id = csv_path.parent.name
# Simplify the experiment ID
experiment_id = simplify_experiment_name(experiment_id)
# Find corresponding JSONL file in the same directory
jsonl_path = csv_path.parent / "inference_results.jsonl"
if not jsonl_path.exists():
# Try with experiment name prefix
jsonl_files = list(csv_path.parent.glob("*_inference_results.jsonl"))
if jsonl_files:
jsonl_path = jsonl_files[0]
else:
raise FileNotFoundError(f"JSONL file not found in {csv_path.parent}")
# Find log file to extract configuration
log_files = list(csv_path.parent.glob("*run_inference_experiment.log"))
if not log_files:
raise FileNotFoundError(f"Log file not found in {csv_path.parent}")
log_path = log_files[0]
# Load inference results and compute metrics
# Extract configuration from log file
config_dict = extract_config_from_log(log_path)
# Convert to OmegaConf DictConfig for compatibility with compute_metrics
cfg = OmegaConf.create(config_dict)
# Load data using the existing function
grader_a_data, grader_b_data = load_inference_results_by_grader(jsonl_path)
# Extract predictions and labels for each grader
all_predictions_a = np.array(
[data["prediction"] for data in grader_a_data.values()]
)
all_labels_a = np.array([data["label"] for data in grader_a_data.values()])
all_predictions_b = np.array(
[data["prediction"] for data in grader_b_data.values()]
)
all_labels_b = np.array([data["label"] for data in grader_b_data.values()])
# Compute concat(A,B) metrics for verification
# Concatenate predictions and labels from both graders
concat_predictions = np.concatenate([all_predictions_a, all_predictions_b])
concat_labels = np.concatenate([all_labels_a, all_labels_b])
metrics_concat = compute_metrics((concat_predictions, concat_labels), cfg)
# Verify that computed concat metrics match original CSV values
# Check a few key metrics with some tolerance for floating point comparison
tolerance = 1e-6
for metric in ["accuracy", "QWK", "Macro_F1", "Weighted_F1"]:
if metric in row and metric in metrics_concat:
original_value = row[metric]
computed_value = metrics_concat[metric]
# You can make this a hard assertion if needed:
assert abs(original_value - computed_value) <= tolerance, (
f"Metric {metric} mismatch: CSV={original_value}, Computed={computed_value}"
)
# 1. Add original row with concat(A,B) metrics
concat_row = row.copy()
concat_row["experiment_id"] = experiment_id
concat_row["metric_group"] = "concat(A,B)"
enhanced_rows.append(concat_row)
# 2. Compute metrics for A and B separately first
metrics_a = compute_metrics((all_predictions_a, all_labels_a), cfg)
metrics_b = compute_metrics((all_predictions_b, all_labels_b), cfg)
# 3. Compute avg(A,B) as the average of metrics, not metrics of averaged predictions
avg_row = row.copy()
avg_row["experiment_id"] = experiment_id
avg_row["metric_group"] = "avg(A,B)"
# Average the metrics from A and B
for metric in metrics_a:
if metric in metrics_b and metric in avg_row:
avg_value = (metrics_a[metric] + metrics_b[metric]) / 2
avg_row[metric] = avg_value
enhanced_rows.append(avg_row)
# 4. Add onlyA metrics
only_a_row = row.copy()
only_a_row["experiment_id"] = experiment_id
only_a_row["metric_group"] = "onlyA"
# Update metric columns with onlyA values
for metric, value in metrics_a.items():
if metric in only_a_row:
only_a_row[metric] = value
enhanced_rows.append(only_a_row)
# 5. Add onlyB metrics
only_b_row = row.copy()
only_b_row["experiment_id"] = experiment_id
only_b_row["metric_group"] = "onlyB"
# Update metric columns with onlyB values
for metric, value in metrics_b.items():
if metric in only_b_row:
only_b_row[metric] = value
enhanced_rows.append(only_b_row)
except Exception as e:
failed_count += 1
error_msg = f"Failed to process {csv_path.parent if csv_path else 'unknown path'}: {str(e)}"
logger.error(error_msg)
# Log full traceback for debugging
import traceback
logger.error(f"Traceback:\n{traceback.format_exc()}")
# Skip this row and continue with the next one
continue
logger.info(f"Successfully processed {len(enhanced_rows)//4} out of {len(eval_df)} rows")
if failed_count > 0:
logger.warning(f"Failed to process {failed_count} rows. Check error log: {error_log_file}")
return pd.DataFrame(enhanced_rows)
def combine(paths, out_path):
if not paths:
logger.info(f"No files to combine for {out_path}")
return
logger.info(f"Combining {len(paths)} files into {out_path}")
dfs = []
for p in paths:
df = pd.read_csv(p)
# Add experiment_id column based on the parent directory name
experiment_id = p.parent.name
experiment_id = simplify_experiment_name(experiment_id)
df["experiment_id"] = experiment_id
dfs.append(df)
# Basic schema validation
cols = {tuple(df.columns) for df in dfs}
if len(cols) > 1:
error_msg = f"{out_path}: header mismatch across shards"
logger.error(error_msg)
raise ValueError(error_msg)
combined = pd.concat(dfs, ignore_index=True)
# Enhance evaluation results with additional metrics
if "evaluation_results" in out_path:
logger.info("Enhancing evaluation results with additional metrics...")
combined = enhance_evaluation_results(combined, paths)
combined.to_parquet(out_path, engine="pyarrow", index=False)
logger.info(f"Successfully written {out_path} with {len(combined)} rows")
if __name__ == "__main__":
logger.info(f"Starting parquet file creation. Logs will be saved to: {log_file}")
logger.info(f"Error-only log will be saved to: {error_log_file}")
groups = find_and_group_csvs()
combine(groups["evaluation_results"], "evaluation_results-00000-of-00001.parquet")
combine(
groups["bootstrap_confidence_intervals"],
"bootstrap_confidence_intervals-00000-of-00001.parquet",
)
logger.info("Parquet file creation completed")