diff --git a/Magpie/benchmark_config.yaml.example b/Magpie/benchmark_config.yaml.example index 439f783..b51f948 100644 --- a/Magpie/benchmark_config.yaml.example +++ b/Magpie/benchmark_config.yaml.example @@ -300,6 +300,12 @@ benchmark: # RANDOM_RANGE_RATIO - Randomness in sequence lengths (0-1, 1 = fixed) # MAX_MODEL_LEN - Maximum model context length # GPU_MEM_UTIL - GPU memory utilization fraction (0-1) +# RUN_EVAL - "true" to run lm-eval after throughput (quote it) +# MAGPIE_EVAL_TASKS - comma-separated lm-eval tasks (e.g. gsm8k,mmlu) +# MAGPIE_EVAL_CONCURRENCY - space-separated eval concs (independent of CONC) +# MAGPIE_EVAL_LIMIT - optional sample cap +# EVAL_MAX_MODEL_LEN - lm-eval local-completions context length +# EVAL_MAX_GEN_TOKS - lm-eval generation budget # # vLLM specific: # EXTRA_VLLM_ARGS - Additional vLLM server arguments diff --git a/Magpie/scripts/benchmark/magpie_bench_remote_compat.sh b/Magpie/scripts/benchmark/magpie_bench_remote_compat.sh index 7b20ff3..0bd82ee 100644 --- a/Magpie/scripts/benchmark/magpie_bench_remote_compat.sh +++ b/Magpie/scripts/benchmark/magpie_bench_remote_compat.sh @@ -89,6 +89,285 @@ magpie_run_benchmark_serving_remote_direct() { return "$rc" } +############################################################################### +# magpie_eval_needs_unsafe_code +# +# lm-eval refuses HumanEval (and other tasks with unsafe_code: true) unless +# --confirm_run_unsafe_code is set. Enable that flag when MAGPIE_EVAL_TASKS +# contains humaneval*, or when MAGPIE_EVAL_CONFIRM_UNSAFE_CODE is true/1. +############################################################################### +magpie_eval_needs_unsafe_code() { + case "${MAGPIE_EVAL_CONFIRM_UNSAFE_CODE:-}" in + 1|true|TRUE|yes|YES) return 0 ;; + esac + local tasks="${MAGPIE_EVAL_TASKS:-}" + [[ ",${tasks}," == *humaneval* ]] +} + +############################################################################### +# magpie_eval_apply_code_eval_env +# +# HumanEval's Hugging Face code_eval metric also requires HF_ALLOW_CODE_EVAL=1 +# at task-load time, independent of --confirm_run_unsafe_code. +############################################################################### +magpie_eval_apply_code_eval_env() { + if magpie_eval_needs_unsafe_code; then + export HF_ALLOW_CODE_EVAL=1 + fi +} + +############################################################################### +# magpie_eval_prepare_deps +# +# InferenceX run_lm_eval installs packages with _install_lm_eval_deps and then +# applies _patch_lm_eval before launching the evaluator. Magpie-owned +# invocations skip run_lm_eval, so run those same hooks when they are sourced. +# If they are absent, install lm-eval into MAGPIE_EVAL_PYTHON. +############################################################################### +magpie_eval_prepare_deps() { + local py="${MAGPIE_EVAL_PYTHON:-python3}" + if declare -F _install_lm_eval_deps &>/dev/null; then + _install_lm_eval_deps + fi + if declare -F _patch_lm_eval &>/dev/null; then + _patch_lm_eval + fi + if [[ "${MAGPIE_EVAL_SKIP_DEPS:-}" == "1" ]]; then + return 0 + fi + if ! "$py" -c "import sys" >/dev/null 2>&1; then + return 0 + fi + if "$py" -c "import lm_eval" >/dev/null 2>&1; then + return 0 + fi + echo "[magpie_bench_remote_compat] lm-eval missing for $py; installing lm-eval[api]" >&2 + "$py" -m pip install --quiet "lm-eval[api]" +} + +############################################################################### +# magpie_eval_context_length / magpie_eval_generation_budget +# +# InferenceX run_lm_eval passes max_length from EVAL_MAX_MODEL_LEN and a +# generation budget via --gen_kwargs max_tokens (context minus 4096, cap +# 16384). Unset, local-completions defaults to 2048 / 256. +############################################################################### +magpie_eval_context_length() { + local max_length="${EVAL_MAX_MODEL_LEN:-${MAGPIE_EVAL_MAX_LENGTH:-${MAX_MODEL_LEN:-16384}}}" + printf '%s\n' "$max_length" +} + +magpie_eval_generation_budget() { + local max_length="$1" + local explicit="${EVAL_MAX_GEN_TOKS:-${MAGPIE_EVAL_MAX_GEN_TOKS:-}}" + if [[ -n "$explicit" ]]; then + printf '%s\n' "$explicit" + return 0 + fi + if [[ ! "$max_length" =~ ^[1-9][0-9]*$ ]]; then + printf '%s\n' "256" + return 0 + fi + local max_output_tokens + if [[ "$max_length" -gt 4096 ]]; then + max_output_tokens=$((max_length - 4096)) + else + max_output_tokens=$((max_length / 2)) + fi + if [[ "$max_output_tokens" -gt 16384 ]]; then + max_output_tokens=16384 + fi + printf '%s\n' "$max_output_tokens" +} + +############################################################################### +# magpie_eval_model_args +# +# local-completions defaults to 2048 context / 256 generated tokens unless the +# task overrides generation. Carry EVAL_MAX_MODEL_LEN and the generation budget +# so long prompts are not truncated. +############################################################################### +magpie_eval_model_args() { + local conc="$1" + local base_url="$2" + local max_length="$3" + local max_gen_toks="$4" + local args="model=${MODEL},base_url=${base_url},num_concurrent=${conc},tokenizer_backend=huggingface,trust_remote_code=true,max_length=${max_length},max_gen_toks=${max_gen_toks}" + if [[ -n "${MAGPIE_EVAL_TOKENIZED_REQUESTS:-}" ]]; then + args+=",tokenized_requests=${MAGPIE_EVAL_TOKENIZED_REQUESTS}" + fi + printf '%s\n' "$args" +} + +############################################################################### +# magpie_prepare_eval_include_and_limit +# +# Optional include path and sample limit for Magpie-owned lm-eval invocations. +# Resolve relative directories to an absolute path here: magpie_run_eval_persisted +# later cds into a temp results directory, which would otherwise hide a +# relative MAGPIE_EVAL_INCLUDE_PATH such as custom-tasks. +############################################################################### +magpie_prepare_eval_include_and_limit() { + if [[ -z "${EVAL_LIMIT:-}" && -n "${MAGPIE_EVAL_LIMIT:-}" ]]; then + export EVAL_LIMIT="$MAGPIE_EVAL_LIMIT" + fi + local include="${MAGPIE_EVAL_INCLUDE_PATH:-${MAGPIE_EVAL_TASK_PATH:-}}" + if [[ -n "$include" && "$include" != *","* ]]; then + if [[ -d "$include" ]]; then + export EVAL_INCLUDE_PATH="$(cd "$include" && pwd)" + elif [[ -f "$include" ]]; then + export EVAL_INCLUDE_PATH="$(cd "$(dirname "$include")" && pwd)" + fi + fi +} + +magpie_eval_port_from_args() { + while [[ $# -gt 0 ]]; do + if [[ "$1" == "--port" && -n "${2:-}" && "$2" != --* ]]; then + printf '%s\n' "$2" + return 0 + fi + shift + done + printf '%s\n' "${PORT:-8888}" +} + +magpie_eval_concurrency_values() { + local raw="${MAGPIE_EVAL_CONCURRENCY:-${EVAL_CONCURRENT_REQUESTS:-${CONC:-8}}}" + raw="${raw//,/ }" + # shellcheck disable=SC2086 + printf '%s\n' $raw +} + +############################################################################### +# magpie_run_eval_concurrency_loop +# +# Run magpie_run_lm_eval once per requested concurrency. Keep going after a +# failure so later concs still produce artifacts, but record completed vs +# failed lists instead of marking every requested value as completed. +############################################################################### +magpie_run_eval_concurrency_loop() { + local out_dir="$1" + local base_url="$2" + local conc + local requested_concs="" + local completed_concs="" + local failed_concs="" + local eval_rc=0 + local rc=0 + + while read -r conc; do + [[ -z "$conc" ]] && continue + requested_concs+="${requested_concs:+ }${conc}" + rc=0 + magpie_run_lm_eval "$out_dir" "$conc" "$base_url" || rc=$? + if [[ "$rc" -eq 0 ]]; then + completed_concs+="${completed_concs:+ }${conc}" + else + eval_rc="$rc" + failed_concs+="${failed_concs:+ }${conc}" + fi + done < <(magpie_eval_concurrency_values) + + export EVAL_BATCHED_CONCS="$requested_concs" + export EVAL_BATCHED_COMPLETED_CONCS="$completed_concs" + export EVAL_BATCHED_FAILED_CONCS="$failed_concs" + return "$eval_rc" +} + +############################################################################### +# magpie_publish_conc_result +# +# lm-eval treats --output_path as a directory and writes results_*.json inside +# it. Downstream gates match concurrency from the basename (results_conc8.json), +# so copy the newest result out of the per-concurrency directory. +############################################################################### +magpie_publish_conc_result() { + local source_dir="$1" + local dest_dir="$2" + local conc="$3" + local dest="${dest_dir%/}/results_conc${conc}.json" + local newest="" path + + [[ -d "$source_dir" ]] || return 0 + mkdir -p "$dest_dir" || return 1 + + while IFS= read -r -d '' path; do + if [[ "$(basename "$path")" == "accuracy_report.json" ]]; then + continue + fi + if [[ -z "$newest" || "$path" -nt "$newest" ]]; then + newest="$path" + fi + done < <(find "$source_dir" -type f -name '*.json' -print0 2>/dev/null) + + if [[ -z "$newest" ]]; then + return 0 + fi + cp -p "$newest" "$dest" || return 1 +} + +############################################################################### +# magpie_run_lm_eval +# +# Drive lm-eval with the local-completions backend so multiple-choice tasks +# that need loglikelihood (mmlu, hellaswag) work against an OpenAI-compatible +# /v1/completions server. InferenceX's local run_eval uses +# local-chat-completions, which raises NotImplementedError for those requests. +# +# Magpie builds the argv here so --confirm_run_unsafe_code is on the actual +# lm-eval process even when a later InferenceX server-watch wrapper would +# hide a Bash python3() intercept. +############################################################################### +magpie_run_lm_eval() { + local out_dir="$1" + local conc="$2" + local base_url="$3" + local py="${MAGPIE_EVAL_PYTHON:-python3}" + local tasks="${MAGPIE_EVAL_TASKS:-gsm8k}" + tasks="${tasks// /}" + local batch_size="${MAGPIE_EVAL_BATCH_SIZE:-auto}" + local conc_dir="${out_dir%/}/conc${conc}" + mkdir -p "$conc_dir" || return 1 + local max_length max_gen_toks model_args gen_kwargs + max_length="$(magpie_eval_context_length)" + max_gen_toks="$(magpie_eval_generation_budget "$max_length")" + model_args="$(magpie_eval_model_args "$conc" "$base_url" "$max_length" "$max_gen_toks")" + gen_kwargs="max_tokens=${max_gen_toks},temperature=0,top_p=1" + local -a cmd=( + "$py" -m lm_eval + --model local-completions + --tasks "$tasks" + --model_args "$model_args" + --gen_kwargs "$gen_kwargs" + --batch_size "$batch_size" + --output_path "$conc_dir" + ) + local limit="${EVAL_LIMIT:-${MAGPIE_EVAL_LIMIT:-}}" + if [[ -n "$limit" ]]; then + cmd+=(--limit "$limit") + fi + if [[ -n "${EVAL_INCLUDE_PATH:-}" ]]; then + cmd+=(--include_path "$EVAL_INCLUDE_PATH") + fi + if magpie_eval_needs_unsafe_code; then + cmd+=(--confirm_run_unsafe_code) + fi + + echo "[magpie_bench_remote_compat] lm_eval cmd: ${cmd[*]}" >&2 + set -x + "${cmd[@]}" + local rc=$? + set +x + magpie_publish_conc_result "$conc_dir" "$out_dir" "$conc" || { + if [[ "$rc" -ne 0 ]]; then + return "$rc" + fi + return 1 + } + return "$rc" +} + ############################################################################### # magpie_run_eval_remote_direct # @@ -122,7 +401,10 @@ magpie_run_eval_remote_direct() { return 1 fi - local py="${MAGPIE_EVAL_PYTHON:-python3}" + magpie_eval_apply_code_eval_env + magpie_prepare_eval_include_and_limit + magpie_eval_prepare_deps || return $? + local result_dir="${RESULT_DIR:-${WORKSPACE_DIR:-/workspace}}" local out_dir="${result_dir%/}/lm_eval" mkdir -p "$out_dir" || { @@ -130,47 +412,22 @@ magpie_run_eval_remote_direct() { return 1 } - local tasks="${MAGPIE_EVAL_TASKS:-gsm8k}" - local batch_size="${MAGPIE_EVAL_BATCH_SIZE:-auto}" - local conc="${MAGPIE_EVAL_CONCURRENCY:-${EVAL_CONCURRENT_REQUESTS:-${CONC:-8}}}" - # local-completions hits an OpenAI-compatible /v1/completions endpoint. - # base_url ends in /v1/completions; tokenizer_backend=huggingface uses - # the local hub tokenizer (model path/id) so we don't pay a server-side - # tokenization roundtrip. - # # MAGPIE_EVAL_TOKENIZED_REQUESTS (optional) controls the prompt wire format. # Unset => lm_eval's default (token-id-array prompts), which a direct sglang # server accepts. A PD-disaggregated sglang_router's /v1/completions only - # accepts StringOrArray and rejects token-id arrays with HTTP 422, collapsing - # the accuracy eval; set MAGPIE_EVAL_TOKENIZED_REQUESTS=false there to send - # string prompts instead. Absent env => byte-for-byte the previous behaviour. + # accepts StringOrArray and rejects token-id arrays with HTTP 422; set + # MAGPIE_EVAL_TOKENIZED_REQUESTS=false there to send string prompts instead. local base_url="${BENCHMARK_BASE_URL%/}/v1/completions" - local model_args="model=${MODEL},base_url=${base_url},num_concurrent=${conc},tokenizer_backend=huggingface,trust_remote_code=true${MAGPIE_EVAL_TOKENIZED_REQUESTS:+,tokenized_requests=${MAGPIE_EVAL_TOKENIZED_REQUESTS}}" - local -a cmd=( - "$py" -m lm_eval - --model local-completions - --tasks "$tasks" - --model_args "$model_args" - --batch_size "$batch_size" - --output_path "$out_dir" - ) - if [[ -n "${MAGPIE_EVAL_LIMIT:-}" ]]; then - cmd+=(--limit "$MAGPIE_EVAL_LIMIT") - fi - - echo "[magpie_bench_remote_compat] lm_eval cmd: ${cmd[*]}" >&2 - set -x - "${cmd[@]}" - local rc=$? - set +x - if [[ $rc -ne 0 ]]; then - echo "[magpie_bench_remote_compat] WARN lm_eval exited rc=$rc; accuracy gate will see no results" >&2 + local eval_rc=0 + magpie_run_eval_concurrency_loop "$out_dir" "$base_url" || eval_rc=$? + if [[ "$eval_rc" -ne 0 ]]; then + echo "[magpie_bench_remote_compat] WARN lm_eval exited rc=$eval_rc; accuracy gate will see no results" >&2 fi local report_rc=0 - magpie_write_accuracy_result "$out_dir" "$rc" "$result_dir" || report_rc=$? - if [[ $rc -ne 0 ]]; then - return "$rc" + magpie_write_accuracy_result "$out_dir" "$eval_rc" "$result_dir" || report_rc=$? + if [[ "$eval_rc" -ne 0 ]]; then + return "$eval_rc" fi return "$report_rc" } @@ -186,7 +443,7 @@ magpie_write_accuracy_result() { local eval_dir="$1" local eval_rc="${2:-0}" local summary_dir="${3:-$eval_dir}" - local py="${MAGPIE_EVAL_PYTHON:-python3}" + local py="${MAGPIE_ACCURACY_REPORT_PYTHON:-python3}" "$py" - "$eval_dir" "$eval_rc" "$summary_dir" <<'PY' import json @@ -291,18 +548,60 @@ print(f"[magpie_bench_remote_compat] accuracy artifact: {output}", file=sys.stde PY } +############################################################################### +# magpie_write_batched_eval_meta +# +# Fallback when InferenceX append_lm_eval_summary is not sourced. Record +# requested, completed, and failed concurrencies instead of treating every +# requested value as completed. +############################################################################### +magpie_write_batched_eval_meta() { + local dest="$1" + local py="${MAGPIE_ACCURACY_REPORT_PYTHON:-python3}" + EVAL_BATCHED_CONCS="${EVAL_BATCHED_CONCS:-}" \ + EVAL_BATCHED_COMPLETED_CONCS="${EVAL_BATCHED_COMPLETED_CONCS:-}" \ + EVAL_BATCHED_FAILED_CONCS="${EVAL_BATCHED_FAILED_CONCS:-}" \ + "$py" - "$dest" <<'PY' +import json +import os +import sys +from pathlib import Path + +def numbers(raw): + return [int(part) for part in str(raw or "").split() if part] + +Path(sys.argv[1]).write_text( + json.dumps( + { + "eval_concs": numbers(os.environ.get("EVAL_BATCHED_CONCS")), + "completed_eval_concs": numbers( + os.environ.get("EVAL_BATCHED_COMPLETED_CONCS") + ), + "failed_eval_concs": numbers(os.environ.get("EVAL_BATCHED_FAILED_CONCS")), + } + ) + + "\n", + encoding="utf-8", +) +PY +} + ############################################################################### # magpie_run_eval_persisted # -# Run InferenceX's local-server eval and copy its result artifacts into -# Magpie's mounted workspace. The source lm-eval directory is left untouched; -# Magpie owns only the copies under $RESULT_DIR/lm_eval. +# Persist lm-eval artifacts under $RESULT_DIR/lm_eval. +# +# When MAGPIE_EVAL_TASKS is set, Magpie drives lm-eval with local-completions +# against the local server port. That path supports loglikelihood multiple-choice +# tasks and puts --confirm_run_unsafe_code on the lm-eval argv (including when +# InferenceX server-watch would otherwise spawn lm-eval as a subprocess). +# +# When MAGPIE_EVAL_TASKS is unset, keep InferenceX run_eval for the default +# single-YAML GSM8K flow. ############################################################################### magpie_run_eval_persisted() { - if ! declare -F run_eval &>/dev/null; then - echo "[magpie_bench_remote_compat] ERROR run_eval is unavailable" >&2 - return 1 - fi + magpie_eval_apply_code_eval_env + magpie_prepare_eval_include_and_limit local result_dir="${RESULT_DIR:-${WORKSPACE_DIR:-/workspace}}" local eval_dir="${result_dir%/}/lm_eval" @@ -324,24 +623,44 @@ magpie_run_eval_persisted() { export EVAL_RESULT_DIR="$raw_dir" local caller_dir="$PWD" - # InferenceX stages batched-concurrency results into PWD rather than - # EVAL_RESULT_DIR. Run from raw_dir so both single and batched evaluations - # have one source tree that can be copied without modifying the artifacts. cd "$raw_dir" || return 1 - run_eval "$@" || eval_rc=$? + + if [[ -n "${MAGPIE_EVAL_TASKS:-}" ]]; then + magpie_eval_prepare_deps || { + eval_rc=$? + cd "$caller_dir" || return 1 + return "$eval_rc" + } + local port + port="$(magpie_eval_port_from_args "$@")" + local base_url="http://127.0.0.1:${port}/v1/completions" + magpie_run_eval_concurrency_loop "$raw_dir" "$base_url" || eval_rc=$? + else + if ! declare -F run_eval &>/dev/null; then + echo "[magpie_bench_remote_compat] ERROR run_eval is unavailable" >&2 + cd "$caller_dir" || return 1 + return 1 + fi + run_eval "$@" || eval_rc=$? + fi cd "$caller_dir" || return 1 if [[ -n "${EVAL_BATCHED_CONCS:-}" ]]; then if declare -F append_lm_eval_summary &>/dev/null; then (cd "$raw_dir" && append_lm_eval_summary) || stage_rc=$? + elif declare -F _write_lm_eval_meta_json &>/dev/null; then + _write_lm_eval_meta_json \ + "$raw_dir/meta_env.json" "" \ + "${EVAL_CONCURRENT_REQUESTS:-${CONC:-1}}" || stage_rc=$? else - echo "[magpie_bench_remote_compat] ERROR append_lm_eval_summary is unavailable for batched eval" >&2 - stage_rc=1 + magpie_write_batched_eval_meta "$raw_dir/meta_env.json" || stage_rc=$? fi else - _write_lm_eval_meta_json \ - "$raw_dir/meta_env.json" "" \ - "${EVAL_CONCURRENT_REQUESTS:-${CONC:-1}}" || stage_rc=$? + if declare -F _write_lm_eval_meta_json &>/dev/null; then + _write_lm_eval_meta_json \ + "$raw_dir/meta_env.json" "" \ + "${EVAL_CONCURRENT_REQUESTS:-${CONC:-1}}" || stage_rc=$? + fi fi local source_file destination diff --git a/examples/benchmarks/sglang_mi355x/benchmark_sglang_qwen3_next_80b_fp8.yaml b/examples/benchmarks/sglang_mi355x/benchmark_sglang_qwen3_next_80b_fp8.yaml index 91446dc..e357a1f 100644 --- a/examples/benchmarks/sglang_mi355x/benchmark_sglang_qwen3_next_80b_fp8.yaml +++ b/examples/benchmarks/sglang_mi355x/benchmark_sglang_qwen3_next_80b_fp8.yaml @@ -23,6 +23,14 @@ benchmark: RANDOM_RANGE_RATIO: 0.8 SGLANG_USE_AITER: 1 EXTRA_SGLANG_ARGS: "--kv-cache-dtype fp8_e4m3" + # Accuracy (optional). Quote "true" so the runner sees lowercase true. + # Magpie runs lm-eval after the throughput sweep against this server. + # RUN_EVAL: "true" + # MAGPIE_EVAL_TASKS: gsm8k,mmlu,hellaswag,gpqa_diamond_cot_n_shot,humaneval_instruct + # MAGPIE_EVAL_CONCURRENCY: "8 64" + # MAGPIE_EVAL_LIMIT: 100 + # EVAL_MAX_MODEL_LEN: 16384 + # EVAL_MAX_GEN_TOKS: 1024 # Profiler configuration profiler: diff --git a/tests/test_eval_concurrency_scripts.py b/tests/test_eval_concurrency_scripts.py index b7acfe2..704d500 100644 --- a/tests/test_eval_concurrency_scripts.py +++ b/tests/test_eval_concurrency_scripts.py @@ -2,6 +2,7 @@ import os import shutil import subprocess +import sys from pathlib import Path import pytest @@ -127,30 +128,77 @@ def test_local_scripts_keep_docker_server_container_alive(script_name: str): assert "magpie_stop_benchmark_server_stack" in contents -def test_remote_eval_prefers_independent_accuracy_concurrency(): - script = ( - ROOT - / "Magpie" - / "scripts" - / "benchmark" - / "magpie_bench_remote_compat.sh" +def _compat_script() -> Path: + return ROOT / "Magpie" / "scripts" / "benchmark" / "magpie_bench_remote_compat.sh" + + +def _lm_eval_python_stub(tmp_path: Path, args_file: Path) -> Path: + stub = tmp_path / "lm_eval_python" + stub.write_text( + "#!/usr/bin/python3\n" + "import json\n" + "import os\n" + "import sys\n" + "from pathlib import Path\n" + "\n" + "args_file = Path(os.environ['LM_EVAL_ARGS_FILE'])\n" + "if len(sys.argv) >= 2 and sys.argv[1] == '-c':\n" + " code = sys.argv[2] if len(sys.argv) > 2 else ''\n" + " raise SystemExit(1 if 'import lm_eval' in code and os.environ.get('LM_EVAL_MISSING') == '1' else 0)\n" + "if len(sys.argv) >= 3 and sys.argv[1] == '-m' and sys.argv[2] == 'pip':\n" + " with args_file.open('a', encoding='utf-8') as handle:\n" + " handle.write(' '.join(sys.argv[1:]) + '\\n')\n" + " marker = os.environ.get('LM_EVAL_PIP_MARKER')\n" + " if marker:\n" + " Path(marker).write_text('installed\\n', encoding='utf-8')\n" + " raise SystemExit(int(os.environ.get('LM_EVAL_PIP_RC', '0')))\n" + "fail_conc = os.environ.get('LM_EVAL_FAIL_CONC')\n" + "if fail_conc and any(\n" + " f'num_concurrent={fail_conc}' in arg for arg in sys.argv\n" + "):\n" + " with args_file.open('a', encoding='utf-8') as handle:\n" + " handle.write(' '.join(sys.argv[1:]) + '\\n')\n" + " raise SystemExit(int(os.environ.get('LM_EVAL_FAIL_RC', '17')))\n" + "with args_file.open('a', encoding='utf-8') as handle:\n" + " handle.write(' '.join(sys.argv[1:]) + '\\n')\n" + " handle.write('HF_ALLOW_CODE_EVAL=' + os.environ.get('HF_ALLOW_CODE_EVAL', '') + '\\n')\n" + "out_dir = Path('.')\n" + "for index, arg in enumerate(sys.argv):\n" + " if arg == '--output_path' and index + 1 < len(sys.argv):\n" + " out_dir = Path(sys.argv[index + 1])\n" + " break\n" + "payload = {\n" + " 'lm_eval_version': '0.4.8',\n" + " 'results': {\n" + " 'gsm8k': {'exact_match,strict-match': 0.9},\n" + " 'mmlu': {'acc,none': 0.8},\n" + " 'hellaswag': {'acc,none': 0.85},\n" + " 'humaneval_instruct': {'pass@1': 0.7},\n" + " }\n" + "}\n" + "out_dir.mkdir(parents=True, exist_ok=True)\n" + "(out_dir / 'results.json').write_text(json.dumps(payload) + '\\n', encoding='utf-8')\n", + encoding="utf-8", ) - contents = script.read_text(encoding="utf-8") + stub.chmod(0o755) + return stub + +def test_remote_eval_prefers_independent_accuracy_concurrency(): + contents = _compat_script().read_text(encoding="utf-8") + + assert "magpie_eval_concurrency_values()" in contents assert ( - 'local conc="${MAGPIE_EVAL_CONCURRENCY:-' + 'local raw="${MAGPIE_EVAL_CONCURRENCY:-' '${EVAL_CONCURRENT_REQUESTS:-${CONC:-8}}}"' ) in contents + assert "--model local-completions" in contents + assert "--model local-chat-completions" not in contents + assert "unset -f python3" not in contents + assert "Crystal" not in contents def test_persisted_eval_writes_raw_and_formatted_results(tmp_path: Path): - compat = ( - ROOT - / "Magpie" - / "scripts" - / "benchmark" - / "magpie_bench_remote_compat.sh" - ) result_payload = { "lm_eval_version": "0.4.8", "results": { @@ -173,19 +221,20 @@ def test_persisted_eval_writes_raw_and_formatted_results(tmp_path: Path): _write_lm_eval_meta_json() { printf '{"model":"test","conc":%s}\n' "$3" > "$1" } +unset MAGPIE_EVAL_TASKS magpie_run_eval_persisted --framework lm-eval --port 8888 ''' source_dir = tmp_path / "source" env = { **os.environ, - "MAGPIE_COMPAT": str(compat), + "MAGPIE_COMPAT": str(_compat_script()), "RESULT_DIR": str(tmp_path), "EVAL_RESULT_DIR": str(source_dir), "FAKE_EVAL_RESULT": json.dumps(result_payload), - "MAGPIE_EVAL_TASKS": "gsm8k", "CONC": "64", "EVAL_CONCURRENT_REQUESTS": "8", } + env.pop("MAGPIE_EVAL_TASKS", None) subprocess.run(["bash", "-c", shell], check=True, env=env) eval_dir = tmp_path / "lm_eval" @@ -204,13 +253,6 @@ def test_persisted_eval_writes_raw_and_formatted_results(tmp_path: Path): def test_persisted_eval_collects_batched_concurrency_results(tmp_path: Path): - compat = ( - ROOT - / "Magpie" - / "scripts" - / "benchmark" - / "magpie_bench_remote_compat.sh" - ) shell = r''' source "$MAGPIE_COMPAT" run_eval() { @@ -230,15 +272,16 @@ def test_persisted_eval_collects_batched_concurrency_results(tmp_path: Path): _write_lm_eval_meta_json() { return 99 } +unset MAGPIE_EVAL_TASKS magpie_run_eval_persisted --framework lm-eval --port 8888 ''' env = { **os.environ, - "MAGPIE_COMPAT": str(compat), + "MAGPIE_COMPAT": str(_compat_script()), "RESULT_DIR": str(tmp_path), "EVAL_CONCURRENT_REQUESTS": "2 4", - "MAGPIE_EVAL_TASKS": "gsm8k", } + env.pop("MAGPIE_EVAL_TASKS", None) subprocess.run(["bash", "-c", shell], check=True, env=env) eval_dir = tmp_path / "lm_eval" @@ -253,6 +296,160 @@ def test_persisted_eval_collects_batched_concurrency_results(tmp_path: Path): assert summary["task"] == "gsm8k" +def test_persisted_eval_drives_local_completions_for_multi_task(tmp_path: Path): + args_file = tmp_path / "lm_eval.args" + python_stub = _lm_eval_python_stub(tmp_path, args_file) + shell = r''' +source "$MAGPIE_COMPAT" +run_eval() { + printf 'run_eval_should_not_run\n' > "$EVAL_RESULT_DIR/run_eval.txt" + return 99 +} +_write_lm_eval_meta_json() { + printf '{"model":"test","conc":%s}\n' "$3" > "$1" +} +magpie_run_eval_persisted --framework lm-eval --port 7777 +''' + source_dir = tmp_path / "source" + source_dir.mkdir() + env = { + **os.environ, + "MAGPIE_COMPAT": str(_compat_script()), + "RESULT_DIR": str(tmp_path), + "EVAL_RESULT_DIR": str(source_dir), + "MAGPIE_EVAL_PYTHON": str(python_stub), + "MAGPIE_ACCURACY_REPORT_PYTHON": sys.executable, + "MAGPIE_EVAL_TASKS": "gsm8k,mmlu,hellaswag", + "MAGPIE_EVAL_LIMIT": "100", + "EVAL_CONCURRENT_REQUESTS": "8", + "LM_EVAL_ARGS_FILE": str(args_file), + "MODEL": "test-model", + } + env.pop("HF_ALLOW_CODE_EVAL", None) + subprocess.run(["bash", "-c", shell], check=True, env=env) + assert not (source_dir / "run_eval.txt").exists() + args = args_file.read_text() + assert "-m lm_eval" in args + assert "--model local-completions" in args + assert "local-chat-completions" not in args + assert "--tasks gsm8k,mmlu,hellaswag" in args + assert "--limit 100" in args + assert "base_url=http://127.0.0.1:7777/v1/completions" in args + assert "num_concurrent=8" in args + assert "--output_path" in args + assert str(source_dir / "conc8") in args + assert (source_dir / "results_conc8.json").is_file() + assert json.loads((source_dir / "results_conc8.json").read_text())["lm_eval_version"] == "0.4.8" + summary = json.loads((tmp_path / "accuracy_report.json").read_text()) + assert summary["status"] == "COMPLETED" + assert "gsm8k" in summary["tasks"] + assert "mmlu" in summary["tasks"] + assert "hellaswag" in summary["tasks"] + + +def test_persisted_eval_writes_per_concurrency_result_files(tmp_path: Path): + args_file = tmp_path / "lm_eval.args" + python_stub = _lm_eval_python_stub(tmp_path, args_file) + shell = r''' +source "$MAGPIE_COMPAT" +_write_lm_eval_meta_json() { + printf '{"model":"test","conc":%s}\n' "$3" > "$1" +} +append_lm_eval_summary() { + printf '%s\n' '{"eval_concs":[8,64]}' > ./meta_env.json +} +magpie_run_eval_persisted --framework lm-eval --port 8888 +''' + source_dir = tmp_path / "source" + source_dir.mkdir() + env = { + **os.environ, + "MAGPIE_COMPAT": str(_compat_script()), + "RESULT_DIR": str(tmp_path), + "EVAL_RESULT_DIR": str(source_dir), + "MAGPIE_EVAL_PYTHON": str(python_stub), + "MAGPIE_ACCURACY_REPORT_PYTHON": sys.executable, + "MAGPIE_EVAL_TASKS": "gsm8k,mmlu", + "MAGPIE_EVAL_CONCURRENCY": "8 64", + "LM_EVAL_ARGS_FILE": str(args_file), + "MODEL": "test-model", + } + subprocess.run(["bash", "-c", shell], check=True, env=env) + args = args_file.read_text() + assert "num_concurrent=8" in args + assert "num_concurrent=64" in args + assert (source_dir / "results_conc8.json").is_file() + assert (source_dir / "results_conc64.json").is_file() + eval_dir = tmp_path / "lm_eval" + assert (eval_dir / "results_conc8.json").is_file() + assert (eval_dir / "results_conc64.json").is_file() + + +def test_persisted_eval_adds_unsafe_flag_and_code_eval_env_for_humaneval(tmp_path: Path): + args_file = tmp_path / "lm_eval.args" + python_stub = _lm_eval_python_stub(tmp_path, args_file) + shell = r''' +source "$MAGPIE_COMPAT" +run_eval() { + printf 'run_eval_should_not_run\n' > "$EVAL_RESULT_DIR/run_eval.txt" + return 99 +} +_write_lm_eval_meta_json() { + printf '{"model":"test","conc":8}\n' > "$1" +} +magpie_run_eval_persisted --framework lm-eval --port 8888 +''' + source_dir = tmp_path / "source" + source_dir.mkdir() + env = { + **os.environ, + "MAGPIE_COMPAT": str(_compat_script()), + "RESULT_DIR": str(tmp_path), + "EVAL_RESULT_DIR": str(source_dir), + "MAGPIE_EVAL_PYTHON": str(python_stub), + "MAGPIE_ACCURACY_REPORT_PYTHON": sys.executable, + "MAGPIE_EVAL_TASKS": "gsm8k,humaneval_instruct", + "EVAL_CONCURRENT_REQUESTS": "8", + "LM_EVAL_ARGS_FILE": str(args_file), + "MODEL": "test-model", + } + env.pop("HF_ALLOW_CODE_EVAL", None) + subprocess.run(["bash", "-c", shell], check=True, env=env) + assert not (source_dir / "run_eval.txt").exists() + args = args_file.read_text() + assert "--confirm_run_unsafe_code" in args + assert "--model local-completions" in args + assert "HF_ALLOW_CODE_EVAL=1" in args + assert "unset -f python3" not in _compat_script().read_text(encoding="utf-8") + + +def test_remote_eval_adds_unsafe_flag_and_code_eval_env_for_humaneval(tmp_path: Path): + args_file = tmp_path / "lm_eval.args" + python_stub = _lm_eval_python_stub(tmp_path, args_file) + shell = r''' +source "$MAGPIE_COMPAT" +magpie_write_accuracy_result() { return 0; } +magpie_run_eval_remote_direct +''' + env = { + **os.environ, + "MAGPIE_COMPAT": str(_compat_script()), + "RESULT_DIR": str(tmp_path), + "BENCHMARK_BASE_URL": "http://127.0.0.1:8888", + "MAGPIE_EVAL_PYTHON": str(python_stub), + "MAGPIE_EVAL_TASKS": "gsm8k,humaneval_instruct", + "LM_EVAL_ARGS_FILE": str(args_file), + "MODEL": "test-model", + } + env.pop("HF_ALLOW_CODE_EVAL", None) + subprocess.run(["bash", "-c", shell], check=True, env=env) + args = args_file.read_text() + assert "--confirm_run_unsafe_code" in args + assert "--model local-completions" in args + assert "--tasks gsm8k,humaneval_instruct" in args + assert "HF_ALLOW_CODE_EVAL=1" in args + + def test_remote_eval_propagates_accuracy_report_failure(tmp_path: Path): compat = ( ROOT @@ -280,3 +477,307 @@ def test_remote_eval_propagates_accuracy_report_failure(tmp_path: Path): completed = subprocess.run(["bash", "-c", shell], check=False, env=env) assert completed.returncode == 73 + + +def test_persisted_eval_calls_inferencex_dep_installer(tmp_path: Path): + args_file = tmp_path / "lm_eval.args" + python_stub = _lm_eval_python_stub(tmp_path, args_file) + marker = tmp_path / "deps.txt" + shell = r''' +source "$MAGPIE_COMPAT" +_install_lm_eval_deps() { + printf 'installed\n' > "$DEPS_MARKER" +} +_write_lm_eval_meta_json() { + printf '{"model":"test","conc":%s}\n' "$3" > "$1" +} +magpie_run_eval_persisted --framework lm-eval --port 8888 +''' + source_dir = tmp_path / "source" + source_dir.mkdir() + env = { + **os.environ, + "MAGPIE_COMPAT": str(_compat_script()), + "RESULT_DIR": str(tmp_path), + "EVAL_RESULT_DIR": str(source_dir), + "MAGPIE_EVAL_PYTHON": str(python_stub), + "MAGPIE_ACCURACY_REPORT_PYTHON": sys.executable, + "MAGPIE_EVAL_TASKS": "gsm8k", + "EVAL_CONCURRENT_REQUESTS": "8", + "LM_EVAL_ARGS_FILE": str(args_file), + "DEPS_MARKER": str(marker), + "MODEL": "test-model", + } + subprocess.run(["bash", "-c", shell], check=True, env=env) + assert marker.read_text() == "installed\n" + assert "-m lm_eval" in args_file.read_text() + + +def test_persisted_eval_applies_inferencex_lm_eval_patch(tmp_path: Path): + args_file = tmp_path / "lm_eval.args" + python_stub = _lm_eval_python_stub(tmp_path, args_file) + marker = tmp_path / "patch.txt" + shell = r''' +source "$MAGPIE_COMPAT" +_install_lm_eval_deps() { :; } +_patch_lm_eval() { + printf 'patched\n' > "$PATCH_MARKER" +} +_write_lm_eval_meta_json() { + printf '{"model":"test","conc":%s}\n' "$3" > "$1" +} +magpie_run_eval_persisted --framework lm-eval --port 8888 +''' + source_dir = tmp_path / "source" + source_dir.mkdir() + env = { + **os.environ, + "MAGPIE_COMPAT": str(_compat_script()), + "RESULT_DIR": str(tmp_path), + "EVAL_RESULT_DIR": str(source_dir), + "MAGPIE_EVAL_PYTHON": str(python_stub), + "MAGPIE_ACCURACY_REPORT_PYTHON": sys.executable, + "MAGPIE_EVAL_TASKS": "gsm8k", + "EVAL_CONCURRENT_REQUESTS": "8", + "LM_EVAL_ARGS_FILE": str(args_file), + "PATCH_MARKER": str(marker), + "MODEL": "test-model", + } + subprocess.run(["bash", "-c", shell], check=True, env=env) + assert marker.read_text() == "patched\n" + +def test_persisted_eval_installs_lm_eval_when_missing(tmp_path: Path): + args_file = tmp_path / "lm_eval.args" + python_stub = _lm_eval_python_stub(tmp_path, args_file) + pip_marker = tmp_path / "pip.txt" + shell = r''' +source "$MAGPIE_COMPAT" +_write_lm_eval_meta_json() { + printf '{"model":"test","conc":%s}\n' "$3" > "$1" +} +magpie_run_eval_persisted --framework lm-eval --port 8888 +''' + source_dir = tmp_path / "source" + source_dir.mkdir() + env = { + **os.environ, + "MAGPIE_COMPAT": str(_compat_script()), + "RESULT_DIR": str(tmp_path), + "EVAL_RESULT_DIR": str(source_dir), + "MAGPIE_EVAL_PYTHON": str(python_stub), + "MAGPIE_ACCURACY_REPORT_PYTHON": sys.executable, + "MAGPIE_EVAL_TASKS": "gsm8k", + "EVAL_CONCURRENT_REQUESTS": "8", + "LM_EVAL_ARGS_FILE": str(args_file), + "LM_EVAL_MISSING": "1", + "LM_EVAL_PIP_MARKER": str(pip_marker), + "MODEL": "test-model", + } + subprocess.run(["bash", "-c", shell], check=True, env=env) + assert pip_marker.read_text() == "installed\n" + args = args_file.read_text() + assert "-m pip install" in args + assert "lm-eval[api]" in args + assert "-m lm_eval" in args + + +def test_persisted_eval_forwards_context_and_generation_limits(tmp_path: Path): + args_file = tmp_path / "lm_eval.args" + python_stub = _lm_eval_python_stub(tmp_path, args_file) + shell = r''' +source "$MAGPIE_COMPAT" +_write_lm_eval_meta_json() { + printf '{"model":"test","conc":%s}\n' "$3" > "$1" +} +magpie_run_eval_persisted --framework lm-eval --port 8888 +''' + source_dir = tmp_path / "source" + source_dir.mkdir() + env = { + **os.environ, + "MAGPIE_COMPAT": str(_compat_script()), + "RESULT_DIR": str(tmp_path), + "EVAL_RESULT_DIR": str(source_dir), + "MAGPIE_EVAL_PYTHON": str(python_stub), + "MAGPIE_ACCURACY_REPORT_PYTHON": sys.executable, + "MAGPIE_EVAL_TASKS": "gsm8k", + "EVAL_CONCURRENT_REQUESTS": "8", + "EVAL_MAX_MODEL_LEN": "16384", + "EVAL_MAX_GEN_TOKS": "512", + "LM_EVAL_ARGS_FILE": str(args_file), + "MODEL": "test-model", + } + env.pop("OSL", None) + env.pop("MAX_MODEL_LEN", None) + subprocess.run(["bash", "-c", shell], check=True, env=env) + args = args_file.read_text() + assert "max_length=16384" in args + assert "max_gen_toks=512" in args + assert "--gen_kwargs" in args + assert "max_tokens=512" in args + assert "--model local-completions" in args + + +def test_persisted_eval_derives_generation_budget_from_context(tmp_path: Path): + args_file = tmp_path / "lm_eval.args" + python_stub = _lm_eval_python_stub(tmp_path, args_file) + shell = r''' +source "$MAGPIE_COMPAT" +_write_lm_eval_meta_json() { + printf '{"model":"test","conc":%s}\n' "$3" > "$1" +} +magpie_run_eval_persisted --framework lm-eval --port 8888 +''' + source_dir = tmp_path / "source" + source_dir.mkdir() + env = { + **os.environ, + "MAGPIE_COMPAT": str(_compat_script()), + "RESULT_DIR": str(tmp_path), + "EVAL_RESULT_DIR": str(source_dir), + "MAGPIE_EVAL_PYTHON": str(python_stub), + "MAGPIE_ACCURACY_REPORT_PYTHON": sys.executable, + "MAGPIE_EVAL_TASKS": "gsm8k", + "EVAL_CONCURRENT_REQUESTS": "8", + "EVAL_MAX_MODEL_LEN": "16384", + "LM_EVAL_ARGS_FILE": str(args_file), + "MODEL": "test-model", + } + env.pop("OSL", None) + env.pop("MAX_MODEL_LEN", None) + env.pop("EVAL_MAX_GEN_TOKS", None) + env.pop("MAGPIE_EVAL_MAX_GEN_TOKS", None) + subprocess.run(["bash", "-c", shell], check=True, env=env) + args = args_file.read_text() + assert "max_length=16384" in args + assert "max_gen_toks=12288" in args + assert "max_tokens=12288" in args + +def test_persisted_eval_records_failed_concurrencies_separately(tmp_path: Path): + args_file = tmp_path / "lm_eval.args" + python_stub = _lm_eval_python_stub(tmp_path, args_file) + shell = r''' +set -e +source "$MAGPIE_COMPAT" +append_lm_eval_summary() { + python3 - <<'PY' +import json, os +from pathlib import Path + +def numbers(raw): + return [int(part) for part in raw.split() if part] + +Path("meta_env.json").write_text( + json.dumps( + { + "eval_concs": numbers(os.environ.get("EVAL_BATCHED_CONCS", "")), + "completed_eval_concs": numbers( + os.environ.get("EVAL_BATCHED_COMPLETED_CONCS", "") + ), + "failed_eval_concs": numbers( + os.environ.get("EVAL_BATCHED_FAILED_CONCS", "") + ), + } + ) + + "\n", + encoding="utf-8", +) +PY +} +magpie_run_eval_persisted --framework lm-eval --port 8888 +''' + source_dir = tmp_path / "source" + source_dir.mkdir() + env = { + **os.environ, + "MAGPIE_COMPAT": str(_compat_script()), + "RESULT_DIR": str(tmp_path), + "EVAL_RESULT_DIR": str(source_dir), + "MAGPIE_EVAL_PYTHON": str(python_stub), + "MAGPIE_ACCURACY_REPORT_PYTHON": sys.executable, + "MAGPIE_EVAL_TASKS": "gsm8k", + "MAGPIE_EVAL_CONCURRENCY": "8 64", + "LM_EVAL_ARGS_FILE": str(args_file), + "LM_EVAL_FAIL_CONC": "64", + "LM_EVAL_FAIL_RC": "17", + "MODEL": "test-model", + } + completed = subprocess.run(["bash", "-c", shell], check=False, env=env) + assert completed.returncode == 17 + meta = json.loads((source_dir / "meta_env.json").read_text()) + assert meta["eval_concs"] == [8, 64] + assert meta["completed_eval_concs"] == [8] + assert meta["failed_eval_concs"] == [64] + eval_dir = tmp_path / "lm_eval" + copied = json.loads((eval_dir / "meta_env.json").read_text()) + assert copied["completed_eval_concs"] == [8] + assert copied["failed_eval_concs"] == [64] + assert (source_dir / "results_conc8.json").is_file() + assert not (source_dir / "results_conc64.json").is_file() + + +def test_persisted_eval_fallback_meta_records_failed_concs(tmp_path: Path): + args_file = tmp_path / "lm_eval.args" + python_stub = _lm_eval_python_stub(tmp_path, args_file) + shell = r''' +source "$MAGPIE_COMPAT" +magpie_run_eval_persisted --framework lm-eval --port 8888 +''' + source_dir = tmp_path / "source" + source_dir.mkdir() + env = { + **os.environ, + "MAGPIE_COMPAT": str(_compat_script()), + "RESULT_DIR": str(tmp_path), + "EVAL_RESULT_DIR": str(source_dir), + "MAGPIE_EVAL_PYTHON": str(python_stub), + "MAGPIE_ACCURACY_REPORT_PYTHON": sys.executable, + "MAGPIE_EVAL_TASKS": "gsm8k", + "MAGPIE_EVAL_CONCURRENCY": "8 64", + "LM_EVAL_ARGS_FILE": str(args_file), + "LM_EVAL_FAIL_CONC": "64", + "LM_EVAL_FAIL_RC": "17", + "MODEL": "test-model", + } + completed = subprocess.run(["bash", "-c", shell], check=False, env=env) + assert completed.returncode == 17 + meta = json.loads((source_dir / "meta_env.json").read_text()) + assert meta["eval_concs"] == [8, 64] + assert meta["completed_eval_concs"] == [8] + assert meta["failed_eval_concs"] == [64] + + +def test_persisted_eval_absolutizes_relative_include_directory(tmp_path: Path): + args_file = tmp_path / "lm_eval.args" + python_stub = _lm_eval_python_stub(tmp_path, args_file) + work = tmp_path / "work" + include = work / "custom-tasks" + include.mkdir(parents=True) + source_dir = tmp_path / "source" + source_dir.mkdir() + shell = r''' +source "$MAGPIE_COMPAT" +_write_lm_eval_meta_json() { + printf '{"model":"test","conc":%s}\n' "$3" > "$1" +} +magpie_run_eval_persisted --framework lm-eval --port 8888 +''' + env = { + **os.environ, + "MAGPIE_COMPAT": str(_compat_script()), + "RESULT_DIR": str(tmp_path), + "EVAL_RESULT_DIR": str(source_dir), + "MAGPIE_EVAL_PYTHON": str(python_stub), + "MAGPIE_ACCURACY_REPORT_PYTHON": sys.executable, + "MAGPIE_EVAL_TASKS": "gsm8k", + "MAGPIE_EVAL_INCLUDE_PATH": "custom-tasks", + "EVAL_CONCURRENT_REQUESTS": "8", + "LM_EVAL_ARGS_FILE": str(args_file), + "MODEL": "test-model", + } + subprocess.run(["bash", "-c", shell], check=True, env=env, cwd=work) + args = args_file.read_text() + resolved = str(include.resolve()) + assert f"--include_path {resolved}" in args + assert "--include_path custom-tasks\n" not in args + assert "--include_path custom-tasks " not in args diff --git a/tests/test_eval_lm_eval_runtime.py b/tests/test_eval_lm_eval_runtime.py new file mode 100644 index 0000000..306e1ca --- /dev/null +++ b/tests/test_eval_lm_eval_runtime.py @@ -0,0 +1,280 @@ +"""Runtime coverage that actually starts `python -m lm_eval`. + +Magpie CI does not install lm-eval; these tests skip unless it is importable. +""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +import pytest + +lm_eval = pytest.importorskip("lm_eval") + +ROOT = Path(__file__).parents[1] +COMPAT = ROOT / "Magpie" / "scripts" / "benchmark" / "magpie_bench_remote_compat.sh" +TOKENIZER_ID = "hf-internal-testing/tiny-random-gpt2" + + +def _choice(n_tokens: int, *, text: str = " 2", index: int = 0) -> dict: + n = max(int(n_tokens) + 8, 64) + tokens = [f"t{i}" for i in range(n)] + token_logprobs = [-0.1] * n + top_logprobs = [{tokens[i]: -0.1} for i in range(n)] + return { + "index": index, + "text": text, + "logprobs": { + "tokens": tokens, + "token_logprobs": token_logprobs, + "top_logprobs": top_logprobs, + }, + } + + +def _prompt_widths(prompt) -> list[int]: + if isinstance(prompt, str): + return [max(len(prompt.split()), 1)] + if isinstance(prompt, list) and prompt and isinstance(prompt[0], int): + return [len(prompt)] + if isinstance(prompt, list) and prompt and isinstance(prompt[0], str): + return [max(len(item.split()), 1) for item in prompt] + if isinstance(prompt, list) and prompt and isinstance(prompt[0], list): + return [max(len(item), 1) for item in prompt] + return [8] + + +class CompletionsHandler(BaseHTTPRequestHandler): + def log_message(self, format, *args): # noqa: A003 + return + + def do_POST(self): # noqa: N802 + length = int(self.headers.get("Content-Length", "0")) + payload = json.loads(self.rfile.read(length) or b"{}") + widths = _prompt_widths(payload.get("prompt", "")) + echo = bool(payload.get("echo")) + choices = [ + _choice(width, text=" 2", index=index) + for index, width in enumerate(widths) + ] + if not echo: + for choice in choices: + choice["text"] = "2" + body = json.dumps({"id": "cmpl-magpie", "choices": choices}).encode("utf-8") + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + +@pytest.fixture +def completions_server(): + server = ThreadingHTTPServer(("127.0.0.1", 0), CompletionsHandler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield f"http://127.0.0.1:{server.server_address[1]}" + finally: + server.shutdown() + thread.join(timeout=5) + + +def _write_tiny_tasks(tmp_path: Path) -> Path: + tmp_path.mkdir(parents=True, exist_ok=True) + include = tmp_path / "tasks" + include.mkdir() + mc_samples = tmp_path / "tiny_mc.jsonl" + mc_samples.write_text( + json.dumps({"question": "1+1=", "choices": ["1", "2"], "answer": 1}) + "\n", + encoding="utf-8", + ) + gen_samples = tmp_path / "tiny_gen.jsonl" + gen_samples.write_text( + json.dumps({"question": "say two", "answer": "2"}) + "\n", + encoding="utf-8", + ) + (include / "magpie_tiny_mc.yaml").write_text( + "\n".join( + [ + "task: magpie_tiny_mc", + "dataset_path: json", + "dataset_kwargs:", + f" data_files: {{test: {mc_samples}}}", + "output_type: multiple_choice", + "test_split: test", + 'doc_to_text: "{{question}}"', + 'doc_to_choice: "{{choices}}"', + 'doc_to_target: "{{answer}}"', + "metric_list:", + " - metric: acc", + " aggregation: mean", + " higher_is_better: true", + ] + ) + + "\n", + encoding="utf-8", + ) + (include / "magpie_tiny_unsafe.yaml").write_text( + "\n".join( + [ + "task: magpie_tiny_unsafe", + "unsafe_code: true", + "dataset_path: json", + "dataset_kwargs:", + f" data_files: {{test: {gen_samples}}}", + "output_type: generate_until", + "test_split: test", + 'doc_to_text: "{{question}}"', + 'doc_to_target: "{{answer}}"', + "generation_kwargs:", + " until: ['\\n']", + " max_gen_toks: 8", + "metric_list:", + " - metric: exact_match", + " aggregation: mean", + " higher_is_better: true", + ] + ) + + "\n", + encoding="utf-8", + ) + return include + + +def _run_magpie_eval( + tmp_path: Path, + *, + base_url: str, + tasks: str, + extra_env: dict[str, str] | None = None, +) -> subprocess.CompletedProcess[str]: + include = _write_tiny_tasks(tmp_path) + env = { + **os.environ, + "MAGPIE_COMPAT": str(COMPAT), + "RESULT_DIR": str(tmp_path / "result"), + "BENCHMARK_BASE_URL": base_url, + "MAGPIE_EVAL_PYTHON": sys.executable, + "MAGPIE_ACCURACY_REPORT_PYTHON": sys.executable, + "MAGPIE_EVAL_TASKS": tasks, + "MAGPIE_EVAL_INCLUDE_PATH": str(include), + "MAGPIE_EVAL_LIMIT": "1", + "MAGPIE_EVAL_BATCH_SIZE": "1", + "MAGPIE_EVAL_CONCURRENCY": "1", + "MAGPIE_EVAL_TOKENIZED_REQUESTS": "false", + "MODEL": TOKENIZER_ID, + "HF_HOME": str(tmp_path / "hf"), + "HF_HUB_DISABLE_TELEMETRY": "1", + "OPENAI_API_KEY": "dummy", + "TOKENIZERS_PARALLELISM": "false", + } + if extra_env: + env.update(extra_env) + env.pop("HF_ALLOW_CODE_EVAL", None) + (tmp_path / "result").mkdir(parents=True, exist_ok=True) + return subprocess.run( + ["bash", "-c", 'source "$MAGPIE_COMPAT" && magpie_run_eval_remote_direct'], + env=env, + capture_output=True, + text=True, + check=False, + timeout=180, + ) + + +def test_chat_backend_cannot_score_multiple_choice(): + from lm_eval.models.openai_completions import LocalChatCompletion + + model = LocalChatCompletion( + model=TOKENIZER_ID, + base_url="http://127.0.0.1:9/v1/chat/completions", + tokenizer_backend=None, + tokenized_requests=False, + ) + with pytest.raises(NotImplementedError, match="Loglikelihood is not supported"): + model.loglikelihood([]) + + +def test_magpie_local_completions_runs_multiple_choice(tmp_path, completions_server): + completed = _run_magpie_eval(tmp_path, base_url=completions_server, tasks="magpie_tiny_mc") + assert completed.returncode == 0, completed.stderr[-4000:] + assert "--model local-completions" in completed.stderr + result = tmp_path / "result" / "lm_eval" / "results_conc1.json" + assert result.is_file(), completed.stderr[-4000:] + payload = json.loads(result.read_text(encoding="utf-8")) + assert "lm_eval_version" in payload + assert "magpie_tiny_mc" in payload["results"] + assert payload["results"]["magpie_tiny_mc"].get("acc,none") is not None + + +def test_magpie_passes_confirm_unsafe_to_real_lm_eval(tmp_path, completions_server): + blocked = _run_magpie_eval(tmp_path, base_url=completions_server, tasks="magpie_tiny_unsafe") + assert blocked.returncode != 0 + assert "unsafe" in (blocked.stderr + blocked.stdout).lower() + + allowed = _run_magpie_eval( + tmp_path / "ok", + base_url=completions_server, + tasks="magpie_tiny_unsafe", + extra_env={"MAGPIE_EVAL_CONFIRM_UNSAFE_CODE": "true"}, + ) + assert allowed.returncode == 0, allowed.stderr[-4000:] + assert "--confirm_run_unsafe_code" in allowed.stderr + payload = json.loads( + (tmp_path / "ok" / "result" / "lm_eval" / "results_conc1.json").read_text( + encoding="utf-8" + ) + ) + assert "magpie_tiny_unsafe" in payload["results"] + + +def test_magpie_sets_hf_allow_code_eval_for_code_eval_metric(tmp_path): + evaluate = pytest.importorskip("evaluate") + shell = r""" +source "$MAGPIE_COMPAT" +export MAGPIE_EVAL_TASKS=humaneval_instruct +unset HF_ALLOW_CODE_EVAL +magpie_eval_apply_code_eval_env +"$PYTHON" - <<'PY' +import os +from evaluate import load + +assert os.environ.get("HF_ALLOW_CODE_EVAL") == "1" +metric = load("code_eval") +os.environ.pop("HF_ALLOW_CODE_EVAL", None) +try: + metric.compute( + predictions=[["def add(a, b):\n return a + b\n"]], + references=["assert add(1, 2) == 3"], + k=[1], + ) +except ValueError as exc: + assert "HF_ALLOW_CODE_EVAL" in str(exc) +else: + raise AssertionError("code_eval must refuse to run without HF_ALLOW_CODE_EVAL") +os.environ["HF_ALLOW_CODE_EVAL"] = "1" +PY +""" + env = { + **os.environ, + "MAGPIE_COMPAT": str(COMPAT), + "PYTHON": sys.executable, + } + env.pop("HF_ALLOW_CODE_EVAL", None) + completed = subprocess.run( + ["bash", "-c", shell], + env=env, + capture_output=True, + text=True, + check=False, + timeout=120, + cwd=str(tmp_path), + ) + assert completed.returncode == 0, completed.stderr[-4000:]