Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296import gradio as grimport jsonimport loggingimport multiprocessingimport osimport pickleimport threadingimport timefrom collections import Counter, defaultdictfrom concurrent.futures import ProcessPoolExecutor, as_completed, wait, FIRST_COMPLETEDfrom datetime import datetimefrom typing import Any, Dict, List, Tuplefrom warnings import warnimport gcimport numpy as npfrom huggingface_hub import HfApifrom bigcodebench.data import get_bigcodebench, get_bigcodebench_hash, load_solutionsfrom bigcodebench.data.utils import CACHE_DIRfrom bigcodebench.eval import PASS, compatible_eval_result, estimate_pass_at_k, untrusted_checkfrom bigcodebench.gen.util import trusted_checkfrom apscheduler.schedulers.background import BackgroundSchedulerREPO_ID = "bigcode/bigcodebench-evaluator"HF_TOKEN = os.environ.get("HF_TOKEN", None)API = HfApi(token=HF_TOKEN)Result = Tuple[str, List[bool]]def get_groundtruth(n_workers, problems, hashcode, check_gt_only, max_as_limit, max_data_limit, max_stack_limit, min_time_limit):cache_file = os.path.join(CACHE_DIR, f"{hashcode}.pkl")if os.path.exists(cache_file):with open(cache_file, "rb") as f:return pickle.load(f)os.makedirs(CACHE_DIR, exist_ok=True)tbegin = time.time()with ProcessPoolExecutor(max_workers=n_workers) as executor:futures = []n_samples = 0expected_time = dict()for problem in problems.values():args = (problem["complete_prompt"] + "\n" + problem["canonical_solution"],problem["test"],problem["task_id"],max_as_limit,max_data_limit,max_stack_limit,min_time_limit,)futures.append(executor.submit(trusted_check, *args))n_samples += 1for future in as_completed(futures):result = future.result()expected_time[result["task_id"]] = result["time"]if any(expected_time.values()):with open(cache_file, "wb") as f:pickle.dump(expected_time, f)return expected_timedef check_correctness(completion_id: int,problem: Dict[str, Any],solution: str,max_as_limit: float,max_data_limit: float,max_stack_limit: float,identifier=None,min_time_limit: float = 0.1,gt_time_limit: float = 2.0,) -> Dict[str, Result]:ret = {"completion_id": completion_id,"task_id": problem["task_id"],"_identifier": identifier,"solution": solution,}ret["base"] = untrusted_check(solution,problem["test"],problem["entry_point"],max_as_limit,max_data_limit,max_stack_limit,min_time_limit,gt_time_limit,)return retdef evaluate(split: str,subset: str,samples: str,pass_k: str="1,5,10",parallel: int = -1,min_time_limit: float = 1,max_as_limit: int = 30 * 1024,max_data_limit: int = 30 * 1024,max_stack_limit: int = 10,calibrated: bool = True,check_gt_only: bool = False,no_gt: bool = False,selective_evaluate: str = "",):passk = [int(k.strip()) for k in pass_k.split(',') if k.strip().isdigit()]if parallel < 1:n_workers = max(1, multiprocessing.cpu_count() // 2)else:n_workers = parallelif check_gt_only:samples = "__dummy__.jsonl"extra = subset + "_" if subset != "full" else ""problems = get_bigcodebench(subset=subset)# Add selective evaluation logicif selective_evaluate:selected_ids = ["BigCodeBench/" + id for id in sorted(set(selective_evaluate.split(",")))]problems = {k: v for k, v in problems.items() if k in selected_ids}if not problems:raise ValueError(f"None of the provided task IDs {selected_ids} were found in the dataset")dataset_hash = get_bigcodebench_hash(subset=subset)if not no_gt:expected_time = get_groundtruth(n_workers, problems, dataset_hash, check_gt_only, max_as_limit, max_data_limit, max_stack_limit, min_time_limit)else:expected_time = {task_id: None for task_id in problems}gt_pass_rate = np.mean([1 if v is not None else 0 for k, v in expected_time.items() if k in problems])failed_tasks = [k for k, v in expected_time.items() if v is None and k in problems]pass_at_k = dict()results = {"date": datetime.now().strftime("%Y-%m-%d %H:%M"),"eval": {},}if not check_gt_only:with ProcessPoolExecutor(max_workers=n_workers) as executor:futures = []completion_id = Counter()n_samples = 0eval_results = defaultdict(list) # task_id ->remainings = set()for sample in load_solutions(samples):task_id = sample["task_id"]if task_id not in problems:continuesolution = (sample["solution"]if "solution" in sampleelse problems[task_id]["complete_prompt"] + sample["completion"])if calibrated:solution = problems[task_id]["code_prompt"] + "\n pass\n" + solutionremainings.add(sample["_identifier"])args = (completion_id[task_id],problems[task_id],solution,max_as_limit,max_data_limit,max_stack_limit,sample["_identifier"],min_time_limit,expected_time[task_id] if expected_time[task_id] else 20)futures.append(executor.submit(check_correctness, *args))completion_id[task_id] += 1n_samples += 1assert n_samples == len(remainings), "Missing problems in unfinished"assert len(completion_id) == len(problems), "Missing problems in samples"for future in as_completed(futures):result = future.result()remainings.remove(result["_identifier"])eval_results[result["task_id"]].append(result)del future, resultgc.collect()# sort the results for each problem by completion_idfor task_id, task_results in eval_results.items():task_results.sort(key=lambda x: x["completion_id"])results["eval"][task_id] = []for res in task_results:stat, details = res["base"]results["eval"][task_id].append({"task_id": task_id,"solution": res["solution"],"status": stat,"details": details,})# Calculate pass@k.total = np.array([len(r) for k, r in results["eval"].items() if k in problems])base_correct = []for key, res in results["eval"].items():if key not in problems:continuebc = sum([r["status"] == PASS for r in res])base_correct.append(bc)base_correct = np.array(base_correct)pass_at_k.update({f"pass@{k}": estimate_pass_at_k(total, base_correct, k).mean()for k in passkif total.min() >= k})del problems, futuresgc.collect()pass_at_k["model"] = os.path.basename(samples).split("--bigcodebench-")[0]pass_at_k["split"] = splitpass_at_k["subset"] = subsetpass_at_k["calibrated"] = calibratedpass_at_k["gt_pass_rate"] = gt_pass_ratepass_at_k["failed_tasks"] = failed_tasksreturn results, pass_at_k# def run_gradio():interface = gr.Interface(fn=evaluate,inputs=[gr.Dropdown(["complete", "instruct"], label="BigCodeBench Split"),gr.Dropdown(["full", "hard"], label="BigCodeBench Subset"),gr.File(label="Samples Path (.jsonl)"),gr.Textbox(label="Pass k Values (comma-separated)", value="1,5,10"),gr.Slider(-1, multiprocessing.cpu_count(), step=1, label="Parallel Workers", value=-1),gr.Slider(0.1, 10, step=0.1, label="Min Time Limit", value=1),gr.Slider(1, 100 * 1024, step=1024, label="Max AS Limit", value=30 * 1024),gr.Slider(1, 100 * 1024, step=1024, label="Max Data Limit", value=30 * 1024),gr.Slider(1, 100, step=1, label="Max Stack Limit", value=10),gr.Checkbox(label="Calibrated", value=True),gr.Checkbox(label="Check GT Only"),gr.Checkbox(label="No GT"),gr.Textbox(label="Selective Evaluated Task IDs (comma-separated, e.g. '0,1,2')", value=""),],outputs=[gr.JSON(label="Results"),gr.JSON(label="Eval Results"),],# concurrency_limit=None)interface.queue(default_concurrency_limit=None)def preload_gt():evaluate(split="complete", subset="full", samples="", check_gt_only=True)evaluate(split="complete", subset="hard", samples="", check_gt_only=True)def restart_space():logging.info(f"Restarting space with repo ID: {REPO_ID}")try:# Now restart the spaceAPI.restart_space(repo_id=REPO_ID, token=HF_TOKEN)logging.info("Space restarted successfully.")except Exception as e:logging.error(f"Failed to restart space: {e}")# if __name__ == "__main__":while True:try:preload_gt()breakexcept:continuescheduler = BackgroundScheduler()scheduler.add_job(restart_space, "interval", hours=1) # Restart every 2hsscheduler.start()interface.launch(show_error=True)
app.py+296