Spaces:
Build error
Build error
adding_log_visualizer (#1)
Browse files- Adding logging visualizer (a130fc382412b1c3f664e294da1aeb43ed30fa00)
- Keeping default of checking every 10 min (ccb39b1f08fe0f04412d9e0401a1dc556b149fb0)
- Increasing log lines to visualize (ef89b19123267a7694493f28cd25a8ac8ed4942b)
- Adding better console handling (d800d714b0f2ae12ffaa23c053413f1951123238)
Co-authored-by: Derek Thomas <derek-thomas@users.noreply.huggingface.co>
Files changed (12)
- .gitignore+1
- app.py+19-20
- main_backend_harness.py+4-2
- main_backend_lighteval.py+7-3
- requirements.txt+6-1
- src/backend/manage_requests.py+7-4
- src/backend/run_eval_suite_harness.py+6-4
- src/backend/run_eval_suite_lighteval.py+4-2
- src/display/css_html_js.pyAdded+20
- src/display/log_visualizer.pyAdded+42
- src/envs.py+3
- src/logging.py+53-31
4 unmodified lines56789104 unmodified lines.ipynb_checkpoints*ipynb.vscode/eval-queue/eval-results/4 unmodified lines5678910114 unmodified lines.ipynb_checkpoints*ipynb.vscode/.idea/eval-queue/eval-results/
123456789101112131415161718192021222324252627import sysimport loggingimport subprocessimport gradio as grfrom apscheduler.schedulers.background import BackgroundSchedulerlogging.basicConfig(level=logging.ERROR)from src.logging import LOGGER, read_logssys.stdout = LOGGERsys.stderr = LOGGER#subprocess.run(["python", "scripts/fix_harness_import.py"])def launch_backend():_ = subprocess.run(["python", "main_backend_lighteval.py"])demo = gr.Blocks()with demo:logs = gr.Code(interactive=False)demo.load(read_logs, None, logs, every=1)scheduler = BackgroundScheduler()scheduler.add_job(launch_backend, "interval", seconds=60) # will only allow one job to be run at the same timescheduler.start()demo.queue(default_concurrency_limit=40).launch()1234567891011121314151617181920212223242526import loggingimport sysimport gradio as grfrom main_backend_lighteval import run_auto_evalfrom src.display.log_visualizer import log_file_to_html_stringfrom src.display.css_html_js import dark_mode_gradio_jsfrom src.envs import REFRESH_RATElogging.basicConfig(level=logging.INFO)intro_md = f"""# IntroThis is just a visual for the auto evaluator. Note that the lines of the log visual are reversed.# Logs"""with gr.Blocks(js=dark_mode_gradio_js) as demo:with gr.Tab("Application"):gr.Markdown(intro_md)dummy = gr.Markdown(run_auto_eval, every=REFRESH_RATE, visible=False)output = gr.HTML(log_file_to_html_string, every=10)if __name__ == '__main__':demo.queue(default_concurrency_limit=40).launch(server_name="0.0.0.0", show_error=True, server_port=7860)
10 unmodified lines11121314151617181931 unmodified lines5152535455565710 unmodified linesfrom src.envs import QUEUE_REPO, EVAL_REQUESTS_PATH_BACKEND, RESULTS_REPO, EVAL_RESULTS_PATH_BACKEND, DEVICE, API, LIMIT, TOKENfrom src.about import Tasks, NUM_FEWSHOTTASKS_HARNESS = [task.value.benchmark for task in Tasks]logging.basicConfig(level=logging.ERROR)pp = pprint.PrettyPrinter(width=80)PENDING_STATUS = "PENDING"31 unmodified linesreturneval_request = eval_requests[0]pp.pprint(eval_request)set_eval_request(api=API,10 unmodified lines111213141516171819202131 unmodified lines5354555657585910 unmodified linesfrom src.envs import QUEUE_REPO, EVAL_REQUESTS_PATH_BACKEND, RESULTS_REPO, EVAL_RESULTS_PATH_BACKEND, DEVICE, API, LIMIT, TOKENfrom src.about import Tasks, NUM_FEWSHOTfrom src.logging import setup_loggerTASKS_HARNESS = [task.value.benchmark for task in Tasks]# logging.basicConfig(level=logging.ERROR)logger = setup_logger(__name__)pp = pprint.PrettyPrinter(width=80)PENDING_STATUS = "PENDING"31 unmodified linesreturneval_request = eval_requests[0]logger.info(pp.pformat(eval_request))set_eval_request(api=API,
10 unmodified lines111213141516171825 unmodified lines4445464748495051525354555610 unmodified linesfrom src.envs import QUEUE_REPO, EVAL_REQUESTS_PATH_BACKEND, RESULTS_REPO, EVAL_RESULTS_PATH_BACKEND, API, LIMIT, TOKEN, ACCELERATOR, VENDOR, REGIONfrom src.about import TASKS_LIGHTEVALlogging.basicConfig(level=logging.ERROR)pp = pprint.PrettyPrinter(width=80)PENDING_STATUS = "PENDING"25 unmodified lines# Sort the evals by priority (first submitted first run)eval_requests = sort_models_by_priority(api=API, models=eval_requests)print(f"Found {len(eval_requests)} {','.join(current_pending_status)} eval requests")if len(eval_requests) == 0:returneval_request = eval_requests[0]pp.pprint(eval_request)set_eval_request(api=API,10 unmodified lines111213141516171819202125 unmodified lines474849505152535455565758596010 unmodified linesfrom src.envs import QUEUE_REPO, EVAL_REQUESTS_PATH_BACKEND, RESULTS_REPO, EVAL_RESULTS_PATH_BACKEND, API, LIMIT, TOKEN, ACCELERATOR, VENDOR, REGIONfrom src.about import TASKS_LIGHTEVALfrom src.logging import setup_loggerlogger = setup_logger(__name__)# logging.basicConfig(level=logging.ERROR)pp = pprint.PrettyPrinter(width=80)PENDING_STATUS = "PENDING"25 unmodified lines# Sort the evals by priority (first submitted first run)eval_requests = sort_models_by_priority(api=API, models=eval_requests)logger.info(f"Found {len(eval_requests)} {','.join(current_pending_status)} eval requests")if len(eval_requests) == 0:returneval_request = eval_requests[0]logger.info(pp.pformat(eval_request))set_eval_request(api=API,
15 unmodified lines1617181915 unmodified linesgit+https://github.com/EleutherAI/lm-evaluation-harness.git@b281b0921b636bc36ad05c0b0b0763bd6dd43463#egg=lm-evalgit+https://github.com/huggingface/lighteval.git#egg=lightevalaccelerate==0.24.1sentencepiece15 unmodified lines16171819202122232415 unmodified linesgit+https://github.com/EleutherAI/lm-evaluation-harness.git@b281b0921b636bc36ad05c0b0b0763bd6dd43463#egg=lm-evalgit+https://github.com/huggingface/lighteval.git#egg=lightevalaccelerate==0.24.1sentencepiece# Log Visualizerbeautifulsoup4==4.12.2lxml==4.9.3rich==13.3.4
4 unmodified lines567891092 unmodified lines1031041051061071081091101111121131141151161171181191201211224 unmodified linesfrom huggingface_hub import HfApi, snapshot_downloadfrom src.envs import TOKEN@dataclassclass EvalRequest:92 unmodified linesfor eval_request in running_evals:model = eval_request.modelprint("====================================")print(f"Checking {model}")output_path = modeloutput_file = f"{local_dir_results}/{output_path}/results*.json"output_file_exists = len(glob.glob(output_file)) > 0if output_file_exists:print(f"EXISTS output file exists for {model} setting it to {completed_status}")set_eval_request(api, eval_request, completed_status, hf_repo, local_dir)else:print(f"No result file found for {model} setting it to {failed_status}")set_eval_request(api, eval_request, failed_status, hf_repo, local_dir)4 unmodified lines567891011121392 unmodified lines1061071081091101111121131141151161171181191201211221231241254 unmodified linesfrom huggingface_hub import HfApi, snapshot_downloadfrom src.envs import TOKENfrom src.logging import setup_loggerlogger = setup_logger(__name__)@dataclassclass EvalRequest:92 unmodified linesfor eval_request in running_evals:model = eval_request.modellogger.info("====================================")logger.info(f"Checking {model}")output_path = modeloutput_file = f"{local_dir_results}/{output_path}/results*.json"output_file_exists = len(glob.glob(output_file)) > 0if output_file_exists:logger.info(f"EXISTS output file exists for {model} setting it to {completed_status}")set_eval_request(api, eval_request, completed_status, hf_repo, local_dir)else:logger.info(f"No result file found for {model} setting it to {failed_status}")set_eval_request(api, eval_request, failed_status, hf_repo, local_dir)
6 unmodified lines78910111213141516171819202122232413 unmodified lines38394041424344454647484950516 unmodified linesfrom src.envs import RESULTS_REPO, APIfrom src.backend.manage_requests import EvalRequestlogging.getLogger("openai").setLevel(logging.WARNING)def run_evaluation(eval_request: EvalRequest, task_names, num_fewshot, batch_size, device, local_dir: str, results_repo: str, no_cache=True, limit=None):if limit:print("WARNING: --limit SHOULD ONLY BE USED FOR TESTING. REAL METRICS SHOULD NOT BE COMPUTED USING LIMIT.")task_names = utils.pattern_match(task_names, tasks.ALL_TASKS)print(f"Selected Tasks: {task_names}")results = evaluator.simple_evaluate(model="hf-causal-experimental", # "hf-causal"13 unmodified linesresults["config"]["model_sha"] = eval_request.revisiondumped = json.dumps(results, indent=2)print(dumped)output_path = os.path.join(local_dir, *eval_request.model.split("/"), f"results_{datetime.now()}.json")os.makedirs(os.path.dirname(output_path), exist_ok=True)with open(output_path, "w") as f:f.write(dumped)print(evaluator.make_table(results))API.upload_file(path_or_fileobj=output_path,6 unmodified lines789101112131415161718192021222324252613 unmodified lines40414243444546474849505152536 unmodified linesfrom src.envs import RESULTS_REPO, APIfrom src.backend.manage_requests import EvalRequestfrom src.logging import setup_loggerlogging.getLogger("openai").setLevel(logging.WARNING)logger = setup_logger(__name__)def run_evaluation(eval_request: EvalRequest, task_names, num_fewshot, batch_size, device, local_dir: str, results_repo: str, no_cache=True, limit=None):if limit:logger.info("WARNING: --limit SHOULD ONLY BE USED FOR TESTING. REAL METRICS SHOULD NOT BE COMPUTED USING LIMIT.")task_names = utils.pattern_match(task_names, tasks.ALL_TASKS)logger.info(f"Selected Tasks: {task_names}")results = evaluator.simple_evaluate(model="hf-causal-experimental", # "hf-causal"13 unmodified linesresults["config"]["model_sha"] = eval_request.revisiondumped = json.dumps(results, indent=2)logger.info(dumped)output_path = os.path.join(local_dir, *eval_request.model.split("/"), f"results_{datetime.now()}.json")os.makedirs(os.path.dirname(output_path), exist_ok=True)with open(output_path, "w") as f:f.write(dumped)logger.info(evaluator.make_table(results))API.upload_file(path_or_fileobj=output_path,
6 unmodified lines78910111213141516171824 unmodified lines434445464748496 unmodified linesfrom src.envs import RESULTS_REPO, CACHE_PATH, TOKENfrom src.backend.manage_requests import EvalRequestlogging.getLogger("openai").setLevel(logging.WARNING)def run_evaluation(eval_request: EvalRequest, task_names: str, batch_size: int, local_dir: str, accelerator: str, region: str, vendor: str, instance_size: str, instance_type: str, limit=None):if limit:print("WARNING: --limit SHOULD ONLY BE USED FOR TESTING. REAL METRICS SHOULD NOT BE COMPUTED USING LIMIT.")args = {"endpoint_model_name":f"{eval_request.model}_{eval_request.precision}".lower(),24 unmodified linesresults["config"]["model_sha"] = eval_request.revisiondumped = json.dumps(results, indent=2)print(dumped)except Exception: # if eval failed, we force a cleanupenv_config = EnvConfig(token=TOKEN, cache_dir=args['cache_dir'])6 unmodified lines789101112131415161718192024 unmodified lines454647484950516 unmodified linesfrom src.envs import RESULTS_REPO, CACHE_PATH, TOKENfrom src.backend.manage_requests import EvalRequestfrom src.logging import setup_loggerlogging.getLogger("openai").setLevel(logging.WARNING)logger = setup_logger(__name__)def run_evaluation(eval_request: EvalRequest, task_names: str, batch_size: int, local_dir: str, accelerator: str, region: str, vendor: str, instance_size: str, instance_type: str, limit=None):if limit:logger.info("WARNING: --limit SHOULD ONLY BE USED FOR TESTING. REAL METRICS SHOULD NOT BE COMPUTED USING LIMIT.")args = {"endpoint_model_name":f"{eval_request.model}_{eval_request.precision}".lower(),24 unmodified linesresults["config"]["model_sha"] = eval_request.revisiondumped = json.dumps(results, indent=2)logger.info(dumped)except Exception: # if eval failed, we force a cleanupenv_config = EnvConfig(token=TOKEN, cache_dir=args['cache_dir'])
1234567891011121314151617181920style_content = """pre, code { background-color: #272822;} .scrollable { font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace; height: 500px; overflow: auto; } """dark_mode_gradio_js = """function refresh() { const url = new URL(window.location);
if (url.searchParams.get('__theme') !== 'dark') { url.searchParams.set('__theme', 'dark'); window.location.href = url.href; }}"""123456789101112131415161718192021222324252627282930313233343536373839404142from io import StringIOfrom pathlib import Path
from bs4 import BeautifulSoupfrom rich.console import Consolefrom rich.syntax import Syntax
from src.display.css_html_js import style_contentfrom src.envs import NUM_LINES_VISUALIZEfrom src.logging import log_file
proj_dir = Path(__name__).parent
def log_file_to_html_string(): with open(log_file, "rt") as f: # Seek to the end of the file minus 300 lines # Read the last 300 lines of the file lines = f.readlines() lines = lines[-NUM_LINES_VISUALIZE:]
# Syntax-highlight the last 300 lines of the file using the Python lexer and Monokai style output = "".join(reversed(lines)) syntax = Syntax(output, "python", theme="monokai", word_wrap=True)
console = Console(record=True, width=150, style="#272822", file=StringIO()) console.print(syntax) html_content = console.export_html(inline_styles=True)
# Parse the HTML content using BeautifulSoup soup = BeautifulSoup(html_content, 'lxml')
# Modify the <pre> tag pre_tag = soup.pre pre_tag['class'] = 'scrollable' del pre_tag['style']
# Add your custom styles and the .scrollable CSS to the <style> tag style_tag = soup.style style_tag.append(style_content)
return soup.prettify()30 unmodified lines313233343530 unmodified linesEVAL_REQUESTS_PATH_BACKEND = os.path.join(CACHE_PATH, "eval-queue-bk")EVAL_RESULTS_PATH_BACKEND = os.path.join(CACHE_PATH, "eval-results-bk")API = HfApi(token=TOKEN)30 unmodified lines313233343536373830 unmodified linesEVAL_REQUESTS_PATH_BACKEND = os.path.join(CACHE_PATH, "eval-queue-bk")EVAL_RESULTS_PATH_BACKEND = os.path.join(CACHE_PATH, "eval-results-bk")REFRESH_RATE = 10 * 60 # 10 minNUM_LINES_VISUALIZE = 300API = HfApi(token=TOKEN)
1234567891011121314151617181920212223242526272829303132import sysfrom src.envs import APIclass Logger:def __init__(self, filename):self.terminal = sys.stdoutself.log = open(filename, "a+")def write(self, message):self.terminal.write(message)self.log.write(message)def flush(self):self.terminal.flush()self.log.flush()def isatty(self):return Falsedef read_logs():sys.stdout.flush()#API.upload_file(# path_or_fileobj="output.log",# path_in_repo="demo-backend.log",# repo_id="demo-leaderboard-backend/logs",# repo_type="dataset",#)with open("output.log", "r") as f:return f.read()LOGGER = Logger("output.log")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354import sysfrom pathlib import Pathproj_dir = Path(__file__).parents[1]log_file = proj_dir/"output.log"import loggingdef setup_logger(name: str):logger = logging.getLogger(name)logger.setLevel(logging.INFO)formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')# Create a file handler to write logs to a filefile_handler = logging.FileHandler(log_file)file_handler.setLevel(logging.INFO)file_handler.setFormatter(formatter)logger.addHandler(file_handler)return logger# class Logger:# def __init__(self):# self.terminal = sys.stdout# self.log = open(log_file, "a+")## def write(self, message):# self.terminal.write(message)# self.log.write(message)## def flush(self):# self.terminal.flush()# self.log.flush()## def isatty(self):# return False## def read_logs():# sys.stdout.flush()# #API.upload_file(# # path_or_fileobj="output.log",# # path_in_repo="demo-backend.log",# # repo_id="demo-leaderboard-backend/logs",# # repo_type="dataset",# #)## with open(log_file, "r") as f:# return f.read()## LOGGER = Logger()
.gitignore+1
app.py+19-20
main_backend_harness.py+4-2
main_backend_lighteval.py+7-3
requirements.txt+6-1
src/backend/manage_requests.py+7-4
src/backend/run_eval_suite_harness.py+6-4
src/backend/run_eval_suite_lighteval.py+4-2
src/display/css_html_js.pyAdded+20
src/display/log_visualizer.pyAdded+42
src/envs.py+3
src/logging.py+53-31