diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-e0000/environment/Dockerfile b/tasks/inequalities/inequalities-abs_ineq-d1-e0000/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-e0000/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-e0000/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d1-e0000/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..5ba1f01431963bc2c823ba2fbfa1319b4a25c60f --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-e0000/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- An error bound for a linear combination. -/ +theorem abs_linear_bound (x y : ℝ) (hx : |x - 6| ≤ 2) (hy : |y - 7| ≤ 1) : + |x - 3 * y + 15| ≤ 5 := by + sorry diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-e0000/instruction.md b/tasks/inequalities/inequalities-abs_ineq-d1-e0000/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c94694ebf75064992a750cbc1739b37f059cd772 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-e0000/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Let \(x\) and \(y\) be real numbers with \(|x - 6| \le 2\) and \(|y - 7| \le 1\). Prove that \(|x - 3y + 15| \le 5\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-e0000/solution/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d1-e0000/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..7c5fd501d438b28f662996314477ade574fe39fa --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-e0000/solution/Solution.lean @@ -0,0 +1,9 @@ +import Mathlib + +/-- An error bound for a linear combination. -/ +theorem abs_linear_bound (x y : ℝ) (hx : |x - 6| ≤ 2) (hy : |y - 7| ≤ 1) : + |x - 3 * y + 15| ≤ 5 := by + rw [abs_le] at hx hy ⊢ + obtain ⟨h1, h2⟩ := hx + obtain ⟨h3, h4⟩ := hy + constructor <;> linarith diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-e0000/solution/solve.sh b/tasks/inequalities/inequalities-abs_ineq-d1-e0000/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-e0000/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-e0000/task.toml b/tasks/inequalities/inequalities-abs_ineq-d1-e0000/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..68a204d9b432a0d2581bea7223c5063fae10a3e5 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-e0000/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "inequalities" +tags = ["inequalities", "abs_ineq", "msc-26", "eval", "lean4"] +msc = "26" +family = "abs_ineq" +split = "eval" +seed = 10000 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-e0000/tests/Verify.lean b/tasks/inequalities/inequalities-abs_ineq-d1-e0000/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-e0000/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-e0000/tests/grade.py b/tasks/inequalities/inequalities-abs_ineq-d1-e0000/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-e0000/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-e0000/tests/spec.json b/tasks/inequalities/inequalities-abs_ineq-d1-e0000/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..a9b2fbf2191882d99373a58751c1750bb50486e8 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-e0000/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- An error bound for a linear combination. -/\ntheorem abs_linear_bound (x y : ℝ) (hx : |x - 6| ≤ 2) (hy : |y - 7| ≤ 1) :\n |x - 3 * y + 15| ≤ 5 := by\n sorry\n", + "targets": [ + { + "name": "abs_linear_bound", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-e0000/tests/test.sh b/tasks/inequalities/inequalities-abs_ineq-d1-e0000/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-e0000/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-e0012/environment/Dockerfile b/tasks/inequalities/inequalities-abs_ineq-d1-e0012/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-e0012/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-e0012/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d1-e0012/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..1eb49818416a2656fd63899e51c2ce33b3c47484 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-e0012/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- An error bound for a linear combination. -/ +theorem abs_linear_bound (x y : ℝ) (hx : |x + 1| ≤ 5) (hy : |y - 8| ≤ 1) : + |6 * x - y + 14| ≤ 31 := by + sorry diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-e0012/instruction.md b/tasks/inequalities/inequalities-abs_ineq-d1-e0012/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..77900fdf1017121961bdd500007d6e496c4a9001 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-e0012/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Let \(x\) and \(y\) be real numbers with \(|x + 1| \le 5\) and \(|y - 8| \le 1\). Prove that \(|6x - y + 14| \le 31\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-e0012/solution/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d1-e0012/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..01aabdb8e020434090fc04873c7874aa47b22dfa --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-e0012/solution/Solution.lean @@ -0,0 +1,9 @@ +import Mathlib + +/-- An error bound for a linear combination. -/ +theorem abs_linear_bound (x y : ℝ) (hx : |x + 1| ≤ 5) (hy : |y - 8| ≤ 1) : + |6 * x - y + 14| ≤ 31 := by + rw [abs_le] at hx hy ⊢ + obtain ⟨h1, h2⟩ := hx + obtain ⟨h3, h4⟩ := hy + constructor <;> linarith diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-e0012/solution/solve.sh b/tasks/inequalities/inequalities-abs_ineq-d1-e0012/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-e0012/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-e0012/task.toml b/tasks/inequalities/inequalities-abs_ineq-d1-e0012/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..24e6f3a96d671604e4c356563b46caef8cbfb277 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-e0012/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "inequalities" +tags = ["inequalities", "abs_ineq", "msc-26", "eval", "lean4"] +msc = "26" +family = "abs_ineq" +split = "eval" +seed = 10012 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-e0012/tests/Verify.lean b/tasks/inequalities/inequalities-abs_ineq-d1-e0012/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-e0012/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-e0012/tests/grade.py b/tasks/inequalities/inequalities-abs_ineq-d1-e0012/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-e0012/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-e0012/tests/spec.json b/tasks/inequalities/inequalities-abs_ineq-d1-e0012/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..ad44da619792ad013e66ae135878748b501dc4c7 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-e0012/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- An error bound for a linear combination. -/\ntheorem abs_linear_bound (x y : ℝ) (hx : |x + 1| ≤ 5) (hy : |y - 8| ≤ 1) :\n |6 * x - y + 14| ≤ 31 := by\n sorry\n", + "targets": [ + { + "name": "abs_linear_bound", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-e0012/tests/test.sh b/tasks/inequalities/inequalities-abs_ineq-d1-e0012/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-e0012/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0000/environment/Dockerfile b/tasks/inequalities/inequalities-abs_ineq-d1-t0000/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0000/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0000/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d1-t0000/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..37739d31496083cc128226baf383cd6f9538eb4a --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0000/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- An error bound for a linear combination. -/ +theorem abs_linear_bound (x y : ℝ) (hx : |x + 1| ≤ 2) (hy : |y - 9| ≤ 4) : + |5 * x - 9 * y + 86| ≤ 46 := by + sorry diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0000/instruction.md b/tasks/inequalities/inequalities-abs_ineq-d1-t0000/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6c69fbb8d770b636e82faf9e91d9641cdc177175 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0000/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Let \(x\) and \(y\) be real numbers with \(|x + 1| \le 2\) and \(|y - 9| \le 4\). Prove that \(|5x - 9y + 86| \le 46\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0000/solution/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d1-t0000/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..e2d52216015acd6144be24458003fdd776f20b0e --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0000/solution/Solution.lean @@ -0,0 +1,9 @@ +import Mathlib + +/-- An error bound for a linear combination. -/ +theorem abs_linear_bound (x y : ℝ) (hx : |x + 1| ≤ 2) (hy : |y - 9| ≤ 4) : + |5 * x - 9 * y + 86| ≤ 46 := by + rw [abs_le] at hx hy ⊢ + obtain ⟨h1, h2⟩ := hx + obtain ⟨h3, h4⟩ := hy + constructor <;> linarith diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0000/solution/solve.sh b/tasks/inequalities/inequalities-abs_ineq-d1-t0000/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0000/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0000/task.toml b/tasks/inequalities/inequalities-abs_ineq-d1-t0000/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4cd50ae2534f5d69a3c826429f113b6bb284ba30 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0000/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "inequalities" +tags = ["inequalities", "abs_ineq", "msc-26", "train", "lean4"] +msc = "26" +family = "abs_ineq" +split = "train" +seed = 0 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0000/tests/Verify.lean b/tasks/inequalities/inequalities-abs_ineq-d1-t0000/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0000/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0000/tests/grade.py b/tasks/inequalities/inequalities-abs_ineq-d1-t0000/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0000/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0000/tests/spec.json b/tasks/inequalities/inequalities-abs_ineq-d1-t0000/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..514df91d6beb1088da9112d555a29de73832a0a2 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0000/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- An error bound for a linear combination. -/\ntheorem abs_linear_bound (x y : ℝ) (hx : |x + 1| ≤ 2) (hy : |y - 9| ≤ 4) :\n |5 * x - 9 * y + 86| ≤ 46 := by\n sorry\n", + "targets": [ + { + "name": "abs_linear_bound", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0000/tests/test.sh b/tasks/inequalities/inequalities-abs_ineq-d1-t0000/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0000/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0012/environment/Dockerfile b/tasks/inequalities/inequalities-abs_ineq-d1-t0012/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0012/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0012/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d1-t0012/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..ecb4b39585f68aafa7cfbb070ce3d848c34acabe --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0012/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- An error bound for a linear combination. -/ +theorem abs_linear_bound (x y : ℝ) (hx : |x + 5| ≤ 2) (hy : |y + 4| ≤ 1) : + |9 * x - 9 * y + 9| ≤ 27 := by + sorry diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0012/instruction.md b/tasks/inequalities/inequalities-abs_ineq-d1-t0012/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ae2964b089ef6ec0e5afa120d7e23c3ba330bac7 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0012/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Let \(x\) and \(y\) be real numbers with \(|x + 5| \le 2\) and \(|y + 4| \le 1\). Prove that \(|9x - 9y + 9| \le 27\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0012/solution/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d1-t0012/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..5d39b9dad91876206fcff01b072c1eb4213090bd --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0012/solution/Solution.lean @@ -0,0 +1,9 @@ +import Mathlib + +/-- An error bound for a linear combination. -/ +theorem abs_linear_bound (x y : ℝ) (hx : |x + 5| ≤ 2) (hy : |y + 4| ≤ 1) : + |9 * x - 9 * y + 9| ≤ 27 := by + rw [abs_le] at hx hy ⊢ + obtain ⟨h1, h2⟩ := hx + obtain ⟨h3, h4⟩ := hy + constructor <;> linarith diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0012/solution/solve.sh b/tasks/inequalities/inequalities-abs_ineq-d1-t0012/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0012/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0012/task.toml b/tasks/inequalities/inequalities-abs_ineq-d1-t0012/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..230d8787aeb61edd7a849a7046bc4b55156878c0 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0012/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "inequalities" +tags = ["inequalities", "abs_ineq", "msc-26", "train", "lean4"] +msc = "26" +family = "abs_ineq" +split = "train" +seed = 12 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0012/tests/Verify.lean b/tasks/inequalities/inequalities-abs_ineq-d1-t0012/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0012/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0012/tests/grade.py b/tasks/inequalities/inequalities-abs_ineq-d1-t0012/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0012/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0012/tests/spec.json b/tasks/inequalities/inequalities-abs_ineq-d1-t0012/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..f217a0abc31692f56ec045d4221d55c3f19e5ae6 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0012/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- An error bound for a linear combination. -/\ntheorem abs_linear_bound (x y : ℝ) (hx : |x + 5| ≤ 2) (hy : |y + 4| ≤ 1) :\n |9 * x - 9 * y + 9| ≤ 27 := by\n sorry\n", + "targets": [ + { + "name": "abs_linear_bound", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0012/tests/test.sh b/tasks/inequalities/inequalities-abs_ineq-d1-t0012/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0012/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0024/environment/Dockerfile b/tasks/inequalities/inequalities-abs_ineq-d1-t0024/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0024/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0024/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d1-t0024/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..621b8254ce7337af5836e596814c197ed5d8bc14 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0024/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- An error bound for a linear combination. -/ +theorem abs_linear_bound (x y : ℝ) (hx : |x + 6| ≤ 7) (hy : |y + 6| ≤ 3) : + |2 * x - 7 * y - 30| ≤ 35 := by + sorry diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0024/instruction.md b/tasks/inequalities/inequalities-abs_ineq-d1-t0024/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4b8ebb4a32ed164a0b46e4abd01700b1a2f24933 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0024/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Let \(x\) and \(y\) be real numbers with \(|x + 6| \le 7\) and \(|y + 6| \le 3\). Prove that \(|2x - 7y - 30| \le 35\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0024/solution/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d1-t0024/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..6a89ff50e24d9a7c3fcbc2dc8c7ad89a4e1aa5f4 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0024/solution/Solution.lean @@ -0,0 +1,9 @@ +import Mathlib + +/-- An error bound for a linear combination. -/ +theorem abs_linear_bound (x y : ℝ) (hx : |x + 6| ≤ 7) (hy : |y + 6| ≤ 3) : + |2 * x - 7 * y - 30| ≤ 35 := by + rw [abs_le] at hx hy ⊢ + obtain ⟨h1, h2⟩ := hx + obtain ⟨h3, h4⟩ := hy + constructor <;> linarith diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0024/solution/solve.sh b/tasks/inequalities/inequalities-abs_ineq-d1-t0024/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0024/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0024/task.toml b/tasks/inequalities/inequalities-abs_ineq-d1-t0024/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8351d9f82be9a3ae5cab7cffb1bf89e51aba62a4 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0024/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "inequalities" +tags = ["inequalities", "abs_ineq", "msc-26", "train", "lean4"] +msc = "26" +family = "abs_ineq" +split = "train" +seed = 24 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0024/tests/Verify.lean b/tasks/inequalities/inequalities-abs_ineq-d1-t0024/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0024/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0024/tests/grade.py b/tasks/inequalities/inequalities-abs_ineq-d1-t0024/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0024/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0024/tests/spec.json b/tasks/inequalities/inequalities-abs_ineq-d1-t0024/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..7abdf4756b32f740735e4cad4d1ce7b4daf5d630 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0024/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- An error bound for a linear combination. -/\ntheorem abs_linear_bound (x y : ℝ) (hx : |x + 6| ≤ 7) (hy : |y + 6| ≤ 3) :\n |2 * x - 7 * y - 30| ≤ 35 := by\n sorry\n", + "targets": [ + { + "name": "abs_linear_bound", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0024/tests/test.sh b/tasks/inequalities/inequalities-abs_ineq-d1-t0024/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0024/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0036/environment/Dockerfile b/tasks/inequalities/inequalities-abs_ineq-d1-t0036/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0036/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0036/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d1-t0036/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..73937368d6a322619260eef72f5d5a61a98a78af --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0036/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- An error bound for a linear combination. -/ +theorem abs_linear_bound (x y : ℝ) (hx : |x - 8| ≤ 1) (hy : |y - 4| ≤ 3) : + |2 * x - 4 * y| ≤ 14 := by + sorry diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0036/instruction.md b/tasks/inequalities/inequalities-abs_ineq-d1-t0036/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8fcbac51b2772c4dff54bca0b6ea5f6c65a518ae --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0036/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Let \(x\) and \(y\) be real numbers with \(|x - 8| \le 1\) and \(|y - 4| \le 3\). Prove that \(|2x - 4y| \le 14\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0036/solution/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d1-t0036/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..8012e778783e1ac0d3eef1eb5b9198b86ac5c898 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0036/solution/Solution.lean @@ -0,0 +1,9 @@ +import Mathlib + +/-- An error bound for a linear combination. -/ +theorem abs_linear_bound (x y : ℝ) (hx : |x - 8| ≤ 1) (hy : |y - 4| ≤ 3) : + |2 * x - 4 * y| ≤ 14 := by + rw [abs_le] at hx hy ⊢ + obtain ⟨h1, h2⟩ := hx + obtain ⟨h3, h4⟩ := hy + constructor <;> linarith diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0036/solution/solve.sh b/tasks/inequalities/inequalities-abs_ineq-d1-t0036/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0036/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0036/task.toml b/tasks/inequalities/inequalities-abs_ineq-d1-t0036/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e4e8a6d341ced82625113c9238d055cff28dbb8e --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0036/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "inequalities" +tags = ["inequalities", "abs_ineq", "msc-26", "train", "lean4"] +msc = "26" +family = "abs_ineq" +split = "train" +seed = 36 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0036/tests/Verify.lean b/tasks/inequalities/inequalities-abs_ineq-d1-t0036/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0036/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0036/tests/grade.py b/tasks/inequalities/inequalities-abs_ineq-d1-t0036/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0036/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0036/tests/spec.json b/tasks/inequalities/inequalities-abs_ineq-d1-t0036/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..15378db39198a7f7db99484b7df04c933d33397f --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0036/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- An error bound for a linear combination. -/\ntheorem abs_linear_bound (x y : ℝ) (hx : |x - 8| ≤ 1) (hy : |y - 4| ≤ 3) :\n |2 * x - 4 * y| ≤ 14 := by\n sorry\n", + "targets": [ + { + "name": "abs_linear_bound", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0036/tests/test.sh b/tasks/inequalities/inequalities-abs_ineq-d1-t0036/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0036/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0048/environment/Dockerfile b/tasks/inequalities/inequalities-abs_ineq-d1-t0048/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0048/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0048/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d1-t0048/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..5f074393655afa3b6f73d5c72644e013243ad7b1 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0048/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- An error bound for a linear combination. -/ +theorem abs_linear_bound (x y : ℝ) (hx : |x - 2| ≤ 8) (hy : |y - 9| ≤ 3) : + |7 * x - 3 * y + 13| ≤ 65 := by + sorry diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0048/instruction.md b/tasks/inequalities/inequalities-abs_ineq-d1-t0048/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4c39fb734d7d915d426ca7c187b8842df5b9d91a --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0048/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Let \(x\) and \(y\) be real numbers with \(|x - 2| \le 8\) and \(|y - 9| \le 3\). Prove that \(|7x - 3y + 13| \le 65\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0048/solution/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d1-t0048/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..555f41ac5c1727ce6ae44a020cf5eb55faf6bf71 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0048/solution/Solution.lean @@ -0,0 +1,9 @@ +import Mathlib + +/-- An error bound for a linear combination. -/ +theorem abs_linear_bound (x y : ℝ) (hx : |x - 2| ≤ 8) (hy : |y - 9| ≤ 3) : + |7 * x - 3 * y + 13| ≤ 65 := by + rw [abs_le] at hx hy ⊢ + obtain ⟨h1, h2⟩ := hx + obtain ⟨h3, h4⟩ := hy + constructor <;> linarith diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0048/solution/solve.sh b/tasks/inequalities/inequalities-abs_ineq-d1-t0048/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0048/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0048/task.toml b/tasks/inequalities/inequalities-abs_ineq-d1-t0048/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6c5d26bd22c865cf86797c19964e5af1f01dcbc8 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0048/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "inequalities" +tags = ["inequalities", "abs_ineq", "msc-26", "train", "lean4"] +msc = "26" +family = "abs_ineq" +split = "train" +seed = 48 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0048/tests/Verify.lean b/tasks/inequalities/inequalities-abs_ineq-d1-t0048/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0048/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0048/tests/grade.py b/tasks/inequalities/inequalities-abs_ineq-d1-t0048/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0048/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0048/tests/spec.json b/tasks/inequalities/inequalities-abs_ineq-d1-t0048/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..68d7e2412ce84f9358efa7f619369b4bfeea3599 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0048/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- An error bound for a linear combination. -/\ntheorem abs_linear_bound (x y : ℝ) (hx : |x - 2| ≤ 8) (hy : |y - 9| ≤ 3) :\n |7 * x - 3 * y + 13| ≤ 65 := by\n sorry\n", + "targets": [ + { + "name": "abs_linear_bound", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-abs_ineq-d1-t0048/tests/test.sh b/tasks/inequalities/inequalities-abs_ineq-d1-t0048/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d1-t0048/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0016/environment/Dockerfile b/tasks/inequalities/inequalities-abs_ineq-d2-t0016/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0016/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0016/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d2-t0016/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..e83d8cdf230f7f6d1747a59d4f29d2298121c1f5 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0016/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A bound on a difference of squares near a point. -/ +theorem abs_square_bound (x : ℝ) (h : |x + 1| ≤ 1) : + |x ^ 2 - (-1) ^ 2| ≤ 1 * (1 + 2 * 1) := by + sorry diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0016/instruction.md b/tasks/inequalities/inequalities-abs_ineq-d2-t0016/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4def8d22ede744f1ce33c80c677a3485282731a0 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0016/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Let \(x\) be a real number with \(|x + 1| \le 1\). Prove that \(|x^2 - (-1)^2| \le 1(1 + 2)\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0016/solution/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d2-t0016/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..19f67f11e405a181aa63f98e6cbe4444f3a4e9a5 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0016/solution/Solution.lean @@ -0,0 +1,14 @@ +import Mathlib + +/-- A bound on a difference of squares near a point. -/ +theorem abs_square_bound (x : ℝ) (h : |x + 1| ≤ 1) : + |x ^ 2 - (-1) ^ 2| ≤ 1 * (1 + 2 * 1) := by + have h1 : |x - 1| ≤ 1 + 2 * 1 := by + rw [abs_le] at h ⊢ + constructor <;> linarith [h.1, h.2] + have h2 : |x ^ 2 - (-1) ^ 2| = |x + 1| * |x - 1| := by + rw [← abs_mul] + congr 1 + ring + rw [h2] + exact mul_le_mul h h1 (abs_nonneg _) (by norm_num) diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0016/solution/solve.sh b/tasks/inequalities/inequalities-abs_ineq-d2-t0016/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0016/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0016/task.toml b/tasks/inequalities/inequalities-abs_ineq-d2-t0016/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..02f2f5edd133515515c9e77eb2eb5f4c0f9be2f3 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0016/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "inequalities" +tags = ["inequalities", "abs_ineq", "msc-26", "train", "lean4"] +msc = "26" +family = "abs_ineq" +split = "train" +seed = 16 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0016/tests/Verify.lean b/tasks/inequalities/inequalities-abs_ineq-d2-t0016/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0016/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0016/tests/grade.py b/tasks/inequalities/inequalities-abs_ineq-d2-t0016/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0016/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0016/tests/spec.json b/tasks/inequalities/inequalities-abs_ineq-d2-t0016/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..db91e3c2c858b72b63bd93a0cdceaaf69c6fa3f0 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0016/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A bound on a difference of squares near a point. -/\ntheorem abs_square_bound (x : ℝ) (h : |x + 1| ≤ 1) :\n |x ^ 2 - (-1) ^ 2| ≤ 1 * (1 + 2 * 1) := by\n sorry\n", + "targets": [ + { + "name": "abs_square_bound", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0016/tests/test.sh b/tasks/inequalities/inequalities-abs_ineq-d2-t0016/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0016/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0028/environment/Dockerfile b/tasks/inequalities/inequalities-abs_ineq-d2-t0028/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0028/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0028/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d2-t0028/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..ac6edcf073d4e54067fb5601760e8f66c05a0e1d --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0028/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A bound on a difference of squares near a point. -/ +theorem abs_square_bound (x : ℝ) (h : |x + 6| ≤ 2) : + |x ^ 2 - (-6) ^ 2| ≤ 2 * (2 + 2 * 6) := by + sorry diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0028/instruction.md b/tasks/inequalities/inequalities-abs_ineq-d2-t0028/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c6959f822b5dccc9956c42255dd2cb317a67999a --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0028/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Let \(x\) be a real number with \(|x + 6| \le 2\). Prove that \(|x^2 - (-6)^2| \le 2(2 + 12)\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0028/solution/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d2-t0028/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..ae761660dec0e4a2de62c99eb6779e5ae68576df --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0028/solution/Solution.lean @@ -0,0 +1,14 @@ +import Mathlib + +/-- A bound on a difference of squares near a point. -/ +theorem abs_square_bound (x : ℝ) (h : |x + 6| ≤ 2) : + |x ^ 2 - (-6) ^ 2| ≤ 2 * (2 + 2 * 6) := by + have h1 : |x - 6| ≤ 2 + 2 * 6 := by + rw [abs_le] at h ⊢ + constructor <;> linarith [h.1, h.2] + have h2 : |x ^ 2 - (-6) ^ 2| = |x + 6| * |x - 6| := by + rw [← abs_mul] + congr 1 + ring + rw [h2] + exact mul_le_mul h h1 (abs_nonneg _) (by norm_num) diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0028/solution/solve.sh b/tasks/inequalities/inequalities-abs_ineq-d2-t0028/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0028/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0028/task.toml b/tasks/inequalities/inequalities-abs_ineq-d2-t0028/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bb7ff0e2ca45b7842f094b892d185826c09e4776 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0028/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "inequalities" +tags = ["inequalities", "abs_ineq", "msc-26", "train", "lean4"] +msc = "26" +family = "abs_ineq" +split = "train" +seed = 28 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0028/tests/Verify.lean b/tasks/inequalities/inequalities-abs_ineq-d2-t0028/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0028/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0028/tests/grade.py b/tasks/inequalities/inequalities-abs_ineq-d2-t0028/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0028/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0028/tests/spec.json b/tasks/inequalities/inequalities-abs_ineq-d2-t0028/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..b31e1791b1045167d7ae8849d2aa70f1ff618e2d --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0028/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A bound on a difference of squares near a point. -/\ntheorem abs_square_bound (x : ℝ) (h : |x + 6| ≤ 2) :\n |x ^ 2 - (-6) ^ 2| ≤ 2 * (2 + 2 * 6) := by\n sorry\n", + "targets": [ + { + "name": "abs_square_bound", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0028/tests/test.sh b/tasks/inequalities/inequalities-abs_ineq-d2-t0028/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0028/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0040/environment/Dockerfile b/tasks/inequalities/inequalities-abs_ineq-d2-t0040/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0040/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0040/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d2-t0040/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..181b2912cab401789eeef023d82483206277bbc2 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0040/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The sum of two distances is at least p times the gap. -/ +theorem abs_two_points (x : ℝ) : + 33 ≤ 3 * |x - 6| + 3 * |x - 17| := by + sorry diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0040/instruction.md b/tasks/inequalities/inequalities-abs_ineq-d2-t0040/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ffa0ea2cd4978074412a9d33bd23062fbcffe8b5 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0040/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that for every real number \(x\), \[33 \le 3|x - 6| + 3|x - 17|.\] + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0040/solution/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d2-t0040/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..58d2ee22da776895e66a99bf4e35934e76cbd740 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0040/solution/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The sum of two distances is at least p times the gap. -/ +theorem abs_two_points (x : ℝ) : + 33 ≤ 3 * |x - 6| + 3 * |x - 17| := by + rcases abs_cases (x - 6) with ⟨h1, _⟩ | ⟨h1, _⟩ <;> rcases abs_cases (x - 17) with ⟨h2, _⟩ | ⟨h2, _⟩ <;> linarith diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0040/solution/solve.sh b/tasks/inequalities/inequalities-abs_ineq-d2-t0040/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0040/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0040/task.toml b/tasks/inequalities/inequalities-abs_ineq-d2-t0040/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a9a11d13ad8c9e31857c174c1b1a78b91c5cd339 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0040/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "inequalities" +tags = ["inequalities", "abs_ineq", "msc-26", "train", "lean4"] +msc = "26" +family = "abs_ineq" +split = "train" +seed = 40 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0040/tests/Verify.lean b/tasks/inequalities/inequalities-abs_ineq-d2-t0040/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0040/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0040/tests/grade.py b/tasks/inequalities/inequalities-abs_ineq-d2-t0040/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0040/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0040/tests/spec.json b/tasks/inequalities/inequalities-abs_ineq-d2-t0040/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..dbd8ce49f5ded182f2e5e616aede3cdcf1b6ec1f --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0040/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The sum of two distances is at least p times the gap. -/\ntheorem abs_two_points (x : ℝ) :\n 33 ≤ 3 * |x - 6| + 3 * |x - 17| := by\n sorry\n", + "targets": [ + { + "name": "abs_two_points", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0040/tests/test.sh b/tasks/inequalities/inequalities-abs_ineq-d2-t0040/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0040/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0052/environment/Dockerfile b/tasks/inequalities/inequalities-abs_ineq-d2-t0052/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0052/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0052/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d2-t0052/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..2334c444561b152a204664599eda7ce7acebfd69 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0052/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The sum of two distances is at least p times the gap. -/ +theorem abs_two_points (x : ℝ) : + 54 ≤ 6 * |x - 3| + 6 * |x - 12| := by + sorry diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0052/instruction.md b/tasks/inequalities/inequalities-abs_ineq-d2-t0052/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e78c965dfa078cc31cef193bfbdb60bfd90cde59 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0052/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that for every real number \(x\), \[54 \le 6|x - 3| + 6|x - 12|.\] + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0052/solution/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d2-t0052/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..7efd76a7fae8434504d91dec07a95f042e836e92 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0052/solution/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The sum of two distances is at least p times the gap. -/ +theorem abs_two_points (x : ℝ) : + 54 ≤ 6 * |x - 3| + 6 * |x - 12| := by + rcases abs_cases (x - 3) with ⟨h1, _⟩ | ⟨h1, _⟩ <;> rcases abs_cases (x - 12) with ⟨h2, _⟩ | ⟨h2, _⟩ <;> linarith diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0052/solution/solve.sh b/tasks/inequalities/inequalities-abs_ineq-d2-t0052/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0052/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0052/task.toml b/tasks/inequalities/inequalities-abs_ineq-d2-t0052/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..35672ed5f10251dc278180df1c109dbdd74954b8 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0052/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "inequalities" +tags = ["inequalities", "abs_ineq", "msc-26", "train", "lean4"] +msc = "26" +family = "abs_ineq" +split = "train" +seed = 52 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0052/tests/Verify.lean b/tasks/inequalities/inequalities-abs_ineq-d2-t0052/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0052/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0052/tests/grade.py b/tasks/inequalities/inequalities-abs_ineq-d2-t0052/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0052/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0052/tests/spec.json b/tasks/inequalities/inequalities-abs_ineq-d2-t0052/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..1578060f245fa17c30b42c336af27e305b057922 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0052/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The sum of two distances is at least p times the gap. -/\ntheorem abs_two_points (x : ℝ) :\n 54 ≤ 6 * |x - 3| + 6 * |x - 12| := by\n sorry\n", + "targets": [ + { + "name": "abs_two_points", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0052/tests/test.sh b/tasks/inequalities/inequalities-abs_ineq-d2-t0052/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0052/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0064/environment/Dockerfile b/tasks/inequalities/inequalities-abs_ineq-d2-t0064/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0064/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0064/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d2-t0064/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..2b0955a5f8c49de1889f354c879d2d053d19d22a --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0064/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A bound on a difference of squares near a point. -/ +theorem abs_square_bound (x : ℝ) (h : |x - 5| ≤ 4) : + |x ^ 2 - 5 ^ 2| ≤ 4 * (4 + 2 * 5) := by + sorry diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0064/instruction.md b/tasks/inequalities/inequalities-abs_ineq-d2-t0064/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..242a0d760aa6d8d129db48f2d621b1544d6b2f74 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0064/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Let \(x\) be a real number with \(|x - 5| \le 4\). Prove that \(|x^2 - 5^2| \le 4(4 + 10)\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0064/solution/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d2-t0064/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..0dbdcbfeb097295d0be1f63ae3bdf279f4f2b7dd --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0064/solution/Solution.lean @@ -0,0 +1,14 @@ +import Mathlib + +/-- A bound on a difference of squares near a point. -/ +theorem abs_square_bound (x : ℝ) (h : |x - 5| ≤ 4) : + |x ^ 2 - 5 ^ 2| ≤ 4 * (4 + 2 * 5) := by + have h1 : |x + 5| ≤ 4 + 2 * 5 := by + rw [abs_le] at h ⊢ + constructor <;> linarith [h.1, h.2] + have h2 : |x ^ 2 - 5 ^ 2| = |x - 5| * |x + 5| := by + rw [← abs_mul] + congr 1 + ring + rw [h2] + exact mul_le_mul h h1 (abs_nonneg _) (by norm_num) diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0064/solution/solve.sh b/tasks/inequalities/inequalities-abs_ineq-d2-t0064/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0064/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0064/task.toml b/tasks/inequalities/inequalities-abs_ineq-d2-t0064/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e3f3bed5fe8e7de893a28cab79ac0577022b67fa --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0064/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "inequalities" +tags = ["inequalities", "abs_ineq", "msc-26", "train", "lean4"] +msc = "26" +family = "abs_ineq" +split = "train" +seed = 64 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0064/tests/Verify.lean b/tasks/inequalities/inequalities-abs_ineq-d2-t0064/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0064/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0064/tests/grade.py b/tasks/inequalities/inequalities-abs_ineq-d2-t0064/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0064/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0064/tests/spec.json b/tasks/inequalities/inequalities-abs_ineq-d2-t0064/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..bba9c3be4ed9ec414cf981d09413f4af642bb005 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0064/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A bound on a difference of squares near a point. -/\ntheorem abs_square_bound (x : ℝ) (h : |x - 5| ≤ 4) :\n |x ^ 2 - 5 ^ 2| ≤ 4 * (4 + 2 * 5) := by\n sorry\n", + "targets": [ + { + "name": "abs_square_bound", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0064/tests/test.sh b/tasks/inequalities/inequalities-abs_ineq-d2-t0064/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0064/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0076/environment/Dockerfile b/tasks/inequalities/inequalities-abs_ineq-d2-t0076/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0076/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0076/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d2-t0076/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..5cee3529d97b643e245ef79ce6683e5285b6dd2c --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0076/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A bound on a difference of squares near a point. -/ +theorem abs_square_bound (x : ℝ) (h : |x - 6| ≤ 4) : + |x ^ 2 - 6 ^ 2| ≤ 4 * (4 + 2 * 6) := by + sorry diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0076/instruction.md b/tasks/inequalities/inequalities-abs_ineq-d2-t0076/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bfec7c2449c558c4e92d1d944b348acb68304f25 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0076/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Let \(x\) be a real number with \(|x - 6| \le 4\). Prove that \(|x^2 - 6^2| \le 4(4 + 12)\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0076/solution/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d2-t0076/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..1f443d30b0a8a7213af88905b754cf40aa396fd7 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0076/solution/Solution.lean @@ -0,0 +1,14 @@ +import Mathlib + +/-- A bound on a difference of squares near a point. -/ +theorem abs_square_bound (x : ℝ) (h : |x - 6| ≤ 4) : + |x ^ 2 - 6 ^ 2| ≤ 4 * (4 + 2 * 6) := by + have h1 : |x + 6| ≤ 4 + 2 * 6 := by + rw [abs_le] at h ⊢ + constructor <;> linarith [h.1, h.2] + have h2 : |x ^ 2 - 6 ^ 2| = |x - 6| * |x + 6| := by + rw [← abs_mul] + congr 1 + ring + rw [h2] + exact mul_le_mul h h1 (abs_nonneg _) (by norm_num) diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0076/solution/solve.sh b/tasks/inequalities/inequalities-abs_ineq-d2-t0076/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0076/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0076/task.toml b/tasks/inequalities/inequalities-abs_ineq-d2-t0076/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9ca4eecf08f12940537884c0ceb025e4cfdb05f7 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0076/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "inequalities" +tags = ["inequalities", "abs_ineq", "msc-26", "train", "lean4"] +msc = "26" +family = "abs_ineq" +split = "train" +seed = 76 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0076/tests/Verify.lean b/tasks/inequalities/inequalities-abs_ineq-d2-t0076/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0076/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0076/tests/grade.py b/tasks/inequalities/inequalities-abs_ineq-d2-t0076/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0076/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0076/tests/spec.json b/tasks/inequalities/inequalities-abs_ineq-d2-t0076/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..04a0fa11056245e19d3aa47b4fa264b9dc300e79 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0076/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A bound on a difference of squares near a point. -/\ntheorem abs_square_bound (x : ℝ) (h : |x - 6| ≤ 4) :\n |x ^ 2 - 6 ^ 2| ≤ 4 * (4 + 2 * 6) := by\n sorry\n", + "targets": [ + { + "name": "abs_square_bound", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-abs_ineq-d2-t0076/tests/test.sh b/tasks/inequalities/inequalities-abs_ineq-d2-t0076/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d2-t0076/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-abs_ineq-d3-e0008/environment/Dockerfile b/tasks/inequalities/inequalities-abs_ineq-d3-e0008/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d3-e0008/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-abs_ineq-d3-e0008/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d3-e0008/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..64432700884955abb2b6e9912194334f81a6cf34 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d3-e0008/environment/workdir/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The sum of the distances to two points is at least their gap. -/ +theorem pair_abs_bound (x a c : ℝ) (h : a ≤ c) : + c - a ≤ |x - a| + |x - c| := by + sorry + +/-- The sum of four distances is bounded below. -/ +theorem four_points_abs (x : ℝ) : + 11 ≤ |x - 1| + |x - 6| + |x - 9| + |x - 9| := by + sorry diff --git a/tasks/inequalities/inequalities-abs_ineq-d3-e0008/instruction.md b/tasks/inequalities/inequalities-abs_ineq-d3-e0008/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bfca1f6713bb82223b4b2052cd33ee47272bcb26 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d3-e0008/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that for all real numbers \(a \le c\) and \(x\), \(c - a \le |x - a| + |x - c|\). Then prove that for every real \(x\), \[11 \le |x - 1| + |x - 6| + |x - 9| + |x - 9|.\] + +## What to do + +`Solution.lean` in the working directory states 2 theorems in Lean 4 with Mathlib, with `sorry` in place of each proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is the share of the 2 theorems that are proved. If the file does not compile the reward is 0, so leave `sorry` on a theorem you cannot finish rather than a broken proof. diff --git a/tasks/inequalities/inequalities-abs_ineq-d3-e0008/solution/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d3-e0008/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..ef02008783d23e0082169eeaf3911bb46e1312ac --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d3-e0008/solution/Solution.lean @@ -0,0 +1,13 @@ +import Mathlib + +/-- The sum of the distances to two points is at least their gap. -/ +theorem pair_abs_bound (x a c : ℝ) (h : a ≤ c) : + c - a ≤ |x - a| + |x - c| := by + rcases abs_cases (x - a) with ⟨h1, _⟩ | ⟨h1, _⟩ <;> rcases abs_cases (x - c) with ⟨h2, _⟩ | ⟨h2, _⟩ <;> linarith + +/-- The sum of four distances is bounded below. -/ +theorem four_points_abs (x : ℝ) : + 11 ≤ |x - 1| + |x - 6| + |x - 9| + |x - 9| := by + have h1 := pair_abs_bound x 1 9 (by norm_num) + have h2 := pair_abs_bound x 6 9 (by norm_num) + linarith diff --git a/tasks/inequalities/inequalities-abs_ineq-d3-e0008/solution/solve.sh b/tasks/inequalities/inequalities-abs_ineq-d3-e0008/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d3-e0008/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-abs_ineq-d3-e0008/task.toml b/tasks/inequalities/inequalities-abs_ineq-d3-e0008/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..050dc4387c7b2db19ff1356a39c2ff5c1e80aa6d --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d3-e0008/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "inequalities" +tags = ["inequalities", "abs_ineq", "msc-26", "eval", "lean4"] +msc = "26" +family = "abs_ineq" +split = "eval" +seed = 10008 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-abs_ineq-d3-e0008/tests/Verify.lean b/tasks/inequalities/inequalities-abs_ineq-d3-e0008/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d3-e0008/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-abs_ineq-d3-e0008/tests/grade.py b/tasks/inequalities/inequalities-abs_ineq-d3-e0008/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d3-e0008/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-abs_ineq-d3-e0008/tests/spec.json b/tasks/inequalities/inequalities-abs_ineq-d3-e0008/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..4d68bb70d312e59d4a79ca9d4de93e9e28a80bf4 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d3-e0008/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\n/-- The sum of the distances to two points is at least their gap. -/\ntheorem pair_abs_bound (x a c : ℝ) (h : a ≤ c) :\n c - a ≤ |x - a| + |x - c| := by\n sorry\n\n/-- The sum of four distances is bounded below. -/\ntheorem four_points_abs (x : ℝ) :\n 11 ≤ |x - 1| + |x - 6| + |x - 9| + |x - 9| := by\n sorry\n", + "targets": [ + { + "name": "pair_abs_bound", + "weight": 1.0 + }, + { + "name": "four_points_abs", + "weight": 2.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-abs_ineq-d3-e0008/tests/test.sh b/tasks/inequalities/inequalities-abs_ineq-d3-e0008/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d3-e0008/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-abs_ineq-d3-t0008/environment/Dockerfile b/tasks/inequalities/inequalities-abs_ineq-d3-t0008/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d3-t0008/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-abs_ineq-d3-t0008/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d3-t0008/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..630e56fd81e1151fac6c13517a26ca93a8eee634 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d3-t0008/environment/workdir/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The sum of the distances to two points is at least their gap. -/ +theorem pair_abs_bound (x a c : ℝ) (h : a ≤ c) : + c - a ≤ |x - a| + |x - c| := by + sorry + +/-- The sum of four distances is bounded below. -/ +theorem four_points_abs (x : ℝ) : + 4 ≤ |x - 1| + |x - 1| + |x - 2| + |x - 4| := by + sorry diff --git a/tasks/inequalities/inequalities-abs_ineq-d3-t0008/instruction.md b/tasks/inequalities/inequalities-abs_ineq-d3-t0008/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..790ee4822efb2551ab784f063483c32da2607308 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d3-t0008/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that for all real numbers \(a \le c\) and \(x\), \(c - a \le |x - a| + |x - c|\). Then prove that for every real \(x\), \[4 \le |x - 1| + |x - 1| + |x - 2| + |x - 4|.\] + +## What to do + +`Solution.lean` in the working directory states 2 theorems in Lean 4 with Mathlib, with `sorry` in place of each proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is the share of the 2 theorems that are proved. If the file does not compile the reward is 0, so leave `sorry` on a theorem you cannot finish rather than a broken proof. diff --git a/tasks/inequalities/inequalities-abs_ineq-d3-t0008/solution/Solution.lean b/tasks/inequalities/inequalities-abs_ineq-d3-t0008/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..0566a94493715cef937062e4685090cf5fde01fb --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d3-t0008/solution/Solution.lean @@ -0,0 +1,13 @@ +import Mathlib + +/-- The sum of the distances to two points is at least their gap. -/ +theorem pair_abs_bound (x a c : ℝ) (h : a ≤ c) : + c - a ≤ |x - a| + |x - c| := by + rcases abs_cases (x - a) with ⟨h1, _⟩ | ⟨h1, _⟩ <;> rcases abs_cases (x - c) with ⟨h2, _⟩ | ⟨h2, _⟩ <;> linarith + +/-- The sum of four distances is bounded below. -/ +theorem four_points_abs (x : ℝ) : + 4 ≤ |x - 1| + |x - 1| + |x - 2| + |x - 4| := by + have h1 := pair_abs_bound x 1 4 (by norm_num) + have h2 := pair_abs_bound x 1 2 (by norm_num) + linarith diff --git a/tasks/inequalities/inequalities-abs_ineq-d3-t0008/solution/solve.sh b/tasks/inequalities/inequalities-abs_ineq-d3-t0008/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d3-t0008/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-abs_ineq-d3-t0008/task.toml b/tasks/inequalities/inequalities-abs_ineq-d3-t0008/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..96b4c9e658925dae0c448db8dbf739f2c4914c72 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d3-t0008/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "inequalities" +tags = ["inequalities", "abs_ineq", "msc-26", "train", "lean4"] +msc = "26" +family = "abs_ineq" +split = "train" +seed = 8 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-abs_ineq-d3-t0008/tests/Verify.lean b/tasks/inequalities/inequalities-abs_ineq-d3-t0008/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d3-t0008/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-abs_ineq-d3-t0008/tests/grade.py b/tasks/inequalities/inequalities-abs_ineq-d3-t0008/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d3-t0008/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-abs_ineq-d3-t0008/tests/spec.json b/tasks/inequalities/inequalities-abs_ineq-d3-t0008/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..05d9701c9c84fd9b903c72ee7cfd97d3c71112b0 --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d3-t0008/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\n/-- The sum of the distances to two points is at least their gap. -/\ntheorem pair_abs_bound (x a c : ℝ) (h : a ≤ c) :\n c - a ≤ |x - a| + |x - c| := by\n sorry\n\n/-- The sum of four distances is bounded below. -/\ntheorem four_points_abs (x : ℝ) :\n 4 ≤ |x - 1| + |x - 1| + |x - 2| + |x - 4| := by\n sorry\n", + "targets": [ + { + "name": "pair_abs_bound", + "weight": 1.0 + }, + { + "name": "four_points_abs", + "weight": 2.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-abs_ineq-d3-t0008/tests/test.sh b/tasks/inequalities/inequalities-abs_ineq-d3-t0008/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-abs_ineq-d3-t0008/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-amgm-d1-e0001/environment/Dockerfile b/tasks/inequalities/inequalities-amgm-d1-e0001/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-e0001/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-amgm-d1-e0001/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-amgm-d1-e0001/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..05fd280c0130b8e6b30aa9bc679d89c91d84bc3c --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-e0001/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The product is at most a quarter of the squared sum. -/ +theorem amgm_constraint (a b : ℝ) (h : 4 * a + 6 * b = 12) : + 24 * a * b ≤ 12 ^ 2 / 4 := by + sorry diff --git a/tasks/inequalities/inequalities-amgm-d1-e0001/instruction.md b/tasks/inequalities/inequalities-amgm-d1-e0001/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5c574adb9ea143463033e78ac03d00105842652f --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-e0001/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Let \(a\) and \(b\) be real numbers with \(4a + 6b = 12\). Prove that \[24ab \le \frac{12^2}{4}.\] + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-amgm-d1-e0001/solution/Solution.lean b/tasks/inequalities/inequalities-amgm-d1-e0001/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..f9945a146092b3b13046c0bbac2a8ae8ea5c85fd --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-e0001/solution/Solution.lean @@ -0,0 +1,7 @@ +import Mathlib + +/-- The product is at most a quarter of the squared sum. -/ +theorem amgm_constraint (a b : ℝ) (h : 4 * a + 6 * b = 12) : + 24 * a * b ≤ 12 ^ 2 / 4 := by + have h2 : (4 * a + 6 * b) ^ 2 = 12 ^ 2 := by rw [h] + nlinarith [sq_nonneg (4 * a - 6 * b), h2] diff --git a/tasks/inequalities/inequalities-amgm-d1-e0001/solution/solve.sh b/tasks/inequalities/inequalities-amgm-d1-e0001/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-e0001/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-amgm-d1-e0001/task.toml b/tasks/inequalities/inequalities-amgm-d1-e0001/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a4fca477adebfc9eadc76d4963308b457bb21dbe --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-e0001/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "inequalities" +tags = ["inequalities", "amgm", "msc-26", "eval", "lean4"] +msc = "26" +family = "amgm" +split = "eval" +seed = 10001 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-amgm-d1-e0001/tests/Verify.lean b/tasks/inequalities/inequalities-amgm-d1-e0001/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-e0001/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-amgm-d1-e0001/tests/grade.py b/tasks/inequalities/inequalities-amgm-d1-e0001/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-e0001/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-amgm-d1-e0001/tests/spec.json b/tasks/inequalities/inequalities-amgm-d1-e0001/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..8cd0192c53a43feb9b8ed1d72c8473c49838931e --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-e0001/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The product is at most a quarter of the squared sum. -/\ntheorem amgm_constraint (a b : ℝ) (h : 4 * a + 6 * b = 12) :\n 24 * a * b ≤ 12 ^ 2 / 4 := by\n sorry\n", + "targets": [ + { + "name": "amgm_constraint", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-amgm-d1-e0001/tests/test.sh b/tasks/inequalities/inequalities-amgm-d1-e0001/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-e0001/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-amgm-d1-e0013/environment/Dockerfile b/tasks/inequalities/inequalities-amgm-d1-e0013/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-e0013/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-amgm-d1-e0013/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-amgm-d1-e0013/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..e7a54d5faea62b02e5466906c6d85196afb84a2c --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-e0013/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A square-completion bound for two real numbers. -/ +theorem two_var_amgm (a b : ℝ) : + 108 * a * b ≤ (9 * a + 3 * b) ^ 2 := by + sorry diff --git a/tasks/inequalities/inequalities-amgm-d1-e0013/instruction.md b/tasks/inequalities/inequalities-amgm-d1-e0013/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..96bebc015637ddfed681f8bf89b3ac754ca30a65 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-e0013/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that for all real numbers \(a\) and \(b\), \[108\,ab \le (9a + 3b)^2.\] + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-amgm-d1-e0013/solution/Solution.lean b/tasks/inequalities/inequalities-amgm-d1-e0013/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..eb97408b250662c3f0dd210bf43b8b0e2eaf74eb --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-e0013/solution/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A square-completion bound for two real numbers. -/ +theorem two_var_amgm (a b : ℝ) : + 108 * a * b ≤ (9 * a + 3 * b) ^ 2 := by + nlinarith [sq_nonneg (9 * a - 3 * b)] diff --git a/tasks/inequalities/inequalities-amgm-d1-e0013/solution/solve.sh b/tasks/inequalities/inequalities-amgm-d1-e0013/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-e0013/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-amgm-d1-e0013/task.toml b/tasks/inequalities/inequalities-amgm-d1-e0013/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..87b14d9369f6f782e9b8dd9c99194992c0d65c92 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-e0013/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "inequalities" +tags = ["inequalities", "amgm", "msc-26", "eval", "lean4"] +msc = "26" +family = "amgm" +split = "eval" +seed = 10013 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-amgm-d1-e0013/tests/Verify.lean b/tasks/inequalities/inequalities-amgm-d1-e0013/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-e0013/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-amgm-d1-e0013/tests/grade.py b/tasks/inequalities/inequalities-amgm-d1-e0013/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-e0013/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-amgm-d1-e0013/tests/spec.json b/tasks/inequalities/inequalities-amgm-d1-e0013/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..686da643a5ba1e5181586c23133d5bb244a0ca68 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-e0013/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A square-completion bound for two real numbers. -/\ntheorem two_var_amgm (a b : ℝ) :\n 108 * a * b ≤ (9 * a + 3 * b) ^ 2 := by\n sorry\n", + "targets": [ + { + "name": "two_var_amgm", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-amgm-d1-e0013/tests/test.sh b/tasks/inequalities/inequalities-amgm-d1-e0013/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-e0013/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-amgm-d1-t0001/environment/Dockerfile b/tasks/inequalities/inequalities-amgm-d1-t0001/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0001/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-amgm-d1-t0001/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-amgm-d1-t0001/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..2303fd761bc83ab8a91f2ae802700f4d9bc2147a --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0001/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The product is at most a quarter of the squared sum. -/ +theorem amgm_constraint (a b : ℝ) (h : a + 4 * b = 23) : + 4 * a * b ≤ 23 ^ 2 / 4 := by + sorry diff --git a/tasks/inequalities/inequalities-amgm-d1-t0001/instruction.md b/tasks/inequalities/inequalities-amgm-d1-t0001/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fb1b2c4642613bd056a2df9bff0c6a79644ed097 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0001/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Let \(a\) and \(b\) be real numbers with \(a + 4b = 23\). Prove that \[4ab \le \frac{23^2}{4}.\] + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-amgm-d1-t0001/solution/Solution.lean b/tasks/inequalities/inequalities-amgm-d1-t0001/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..2ff5d5a21474a3aadc2c824d7794268835e8e251 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0001/solution/Solution.lean @@ -0,0 +1,7 @@ +import Mathlib + +/-- The product is at most a quarter of the squared sum. -/ +theorem amgm_constraint (a b : ℝ) (h : a + 4 * b = 23) : + 4 * a * b ≤ 23 ^ 2 / 4 := by + have h2 : (a + 4 * b) ^ 2 = 23 ^ 2 := by rw [h] + nlinarith [sq_nonneg (a - 4 * b), h2] diff --git a/tasks/inequalities/inequalities-amgm-d1-t0001/solution/solve.sh b/tasks/inequalities/inequalities-amgm-d1-t0001/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0001/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-amgm-d1-t0001/task.toml b/tasks/inequalities/inequalities-amgm-d1-t0001/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..58f86396542f344c75c77cc8f91692fbb4922d1e --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0001/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "inequalities" +tags = ["inequalities", "amgm", "msc-26", "train", "lean4"] +msc = "26" +family = "amgm" +split = "train" +seed = 1 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-amgm-d1-t0001/tests/Verify.lean b/tasks/inequalities/inequalities-amgm-d1-t0001/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0001/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-amgm-d1-t0001/tests/grade.py b/tasks/inequalities/inequalities-amgm-d1-t0001/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0001/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-amgm-d1-t0001/tests/spec.json b/tasks/inequalities/inequalities-amgm-d1-t0001/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..b65eefce917482de5816f3c8600ba35930dac4e8 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0001/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The product is at most a quarter of the squared sum. -/\ntheorem amgm_constraint (a b : ℝ) (h : a + 4 * b = 23) :\n 4 * a * b ≤ 23 ^ 2 / 4 := by\n sorry\n", + "targets": [ + { + "name": "amgm_constraint", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-amgm-d1-t0001/tests/test.sh b/tasks/inequalities/inequalities-amgm-d1-t0001/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0001/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-amgm-d1-t0013/environment/Dockerfile b/tasks/inequalities/inequalities-amgm-d1-t0013/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0013/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-amgm-d1-t0013/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-amgm-d1-t0013/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..a56287d8a7caa47701ba7279cfeb6ff0c51ac16f --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0013/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The product is at most a quarter of the squared sum. -/ +theorem amgm_constraint (a b : ℝ) (h : a + 6 * b = 33) : + 6 * a * b ≤ 33 ^ 2 / 4 := by + sorry diff --git a/tasks/inequalities/inequalities-amgm-d1-t0013/instruction.md b/tasks/inequalities/inequalities-amgm-d1-t0013/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e35027487521b22ccd6ea089b2d2973f6c58a6bf --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0013/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Let \(a\) and \(b\) be real numbers with \(a + 6b = 33\). Prove that \[6ab \le \frac{33^2}{4}.\] + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-amgm-d1-t0013/solution/Solution.lean b/tasks/inequalities/inequalities-amgm-d1-t0013/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..9b377402681891010533562900ca51032393269d --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0013/solution/Solution.lean @@ -0,0 +1,7 @@ +import Mathlib + +/-- The product is at most a quarter of the squared sum. -/ +theorem amgm_constraint (a b : ℝ) (h : a + 6 * b = 33) : + 6 * a * b ≤ 33 ^ 2 / 4 := by + have h2 : (a + 6 * b) ^ 2 = 33 ^ 2 := by rw [h] + nlinarith [sq_nonneg (a - 6 * b), h2] diff --git a/tasks/inequalities/inequalities-amgm-d1-t0013/solution/solve.sh b/tasks/inequalities/inequalities-amgm-d1-t0013/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0013/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-amgm-d1-t0013/task.toml b/tasks/inequalities/inequalities-amgm-d1-t0013/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fe8cb95d8d8d5115962d0116ee554f7e78dcdf88 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0013/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "inequalities" +tags = ["inequalities", "amgm", "msc-26", "train", "lean4"] +msc = "26" +family = "amgm" +split = "train" +seed = 13 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-amgm-d1-t0013/tests/Verify.lean b/tasks/inequalities/inequalities-amgm-d1-t0013/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0013/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-amgm-d1-t0013/tests/grade.py b/tasks/inequalities/inequalities-amgm-d1-t0013/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0013/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-amgm-d1-t0013/tests/spec.json b/tasks/inequalities/inequalities-amgm-d1-t0013/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..c63f2f49b43c06bd163e226f67d25b0e0b887474 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0013/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The product is at most a quarter of the squared sum. -/\ntheorem amgm_constraint (a b : ℝ) (h : a + 6 * b = 33) :\n 6 * a * b ≤ 33 ^ 2 / 4 := by\n sorry\n", + "targets": [ + { + "name": "amgm_constraint", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-amgm-d1-t0013/tests/test.sh b/tasks/inequalities/inequalities-amgm-d1-t0013/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0013/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-amgm-d1-t0025/environment/Dockerfile b/tasks/inequalities/inequalities-amgm-d1-t0025/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0025/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-amgm-d1-t0025/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-amgm-d1-t0025/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..cfded2164e962bce45f685f96f74ead4b7c5b98f --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0025/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The product is at most a quarter of the squared sum. -/ +theorem amgm_constraint (a b : ℝ) (h : 2 * a + 2 * b = 1) : + 4 * a * b ≤ 1 ^ 2 / 4 := by + sorry diff --git a/tasks/inequalities/inequalities-amgm-d1-t0025/instruction.md b/tasks/inequalities/inequalities-amgm-d1-t0025/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..27fd0177a2984b7a7d988b745ff870d98f558b37 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0025/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Let \(a\) and \(b\) be real numbers with \(2a + 2b = 1\). Prove that \[4ab \le \frac{1^2}{4}.\] + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-amgm-d1-t0025/solution/Solution.lean b/tasks/inequalities/inequalities-amgm-d1-t0025/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..2bba3ce2657e11f6a4ce922ba0b092673e501d92 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0025/solution/Solution.lean @@ -0,0 +1,7 @@ +import Mathlib + +/-- The product is at most a quarter of the squared sum. -/ +theorem amgm_constraint (a b : ℝ) (h : 2 * a + 2 * b = 1) : + 4 * a * b ≤ 1 ^ 2 / 4 := by + have h2 : (2 * a + 2 * b) ^ 2 = 1 ^ 2 := by rw [h] + nlinarith [sq_nonneg (2 * a - 2 * b), h2] diff --git a/tasks/inequalities/inequalities-amgm-d1-t0025/solution/solve.sh b/tasks/inequalities/inequalities-amgm-d1-t0025/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0025/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-amgm-d1-t0025/task.toml b/tasks/inequalities/inequalities-amgm-d1-t0025/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..402bdb741eb47d75c87c6f15bf6dcf40426a189a --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0025/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "inequalities" +tags = ["inequalities", "amgm", "msc-26", "train", "lean4"] +msc = "26" +family = "amgm" +split = "train" +seed = 25 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-amgm-d1-t0025/tests/Verify.lean b/tasks/inequalities/inequalities-amgm-d1-t0025/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0025/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-amgm-d1-t0025/tests/grade.py b/tasks/inequalities/inequalities-amgm-d1-t0025/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0025/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-amgm-d1-t0025/tests/spec.json b/tasks/inequalities/inequalities-amgm-d1-t0025/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..3c762a465e1b9bf3c35751ff7fbf1fe1244d4bc9 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0025/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The product is at most a quarter of the squared sum. -/\ntheorem amgm_constraint (a b : ℝ) (h : 2 * a + 2 * b = 1) :\n 4 * a * b ≤ 1 ^ 2 / 4 := by\n sorry\n", + "targets": [ + { + "name": "amgm_constraint", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-amgm-d1-t0025/tests/test.sh b/tasks/inequalities/inequalities-amgm-d1-t0025/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0025/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-amgm-d1-t0037/environment/Dockerfile b/tasks/inequalities/inequalities-amgm-d1-t0037/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0037/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-amgm-d1-t0037/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-amgm-d1-t0037/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..1382803b48fae7f621fa1bad1a95e181dbf57b9b --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0037/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A square-completion bound for two real numbers. -/ +theorem two_var_amgm (a b : ℝ) : + 168 * a * b ≤ (7 * a + 6 * b) ^ 2 := by + sorry diff --git a/tasks/inequalities/inequalities-amgm-d1-t0037/instruction.md b/tasks/inequalities/inequalities-amgm-d1-t0037/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0a3833b6bc0fd2c9f416f0ed8b26f6d7eec0a247 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0037/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that for all real numbers \(a\) and \(b\), \[168\,ab \le (7a + 6b)^2.\] + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-amgm-d1-t0037/solution/Solution.lean b/tasks/inequalities/inequalities-amgm-d1-t0037/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..c3b960626cf0093ce065d44ceb4c654c67d0d487 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0037/solution/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A square-completion bound for two real numbers. -/ +theorem two_var_amgm (a b : ℝ) : + 168 * a * b ≤ (7 * a + 6 * b) ^ 2 := by + nlinarith [sq_nonneg (7 * a - 6 * b)] diff --git a/tasks/inequalities/inequalities-amgm-d1-t0037/solution/solve.sh b/tasks/inequalities/inequalities-amgm-d1-t0037/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0037/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-amgm-d1-t0037/task.toml b/tasks/inequalities/inequalities-amgm-d1-t0037/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c9260e532266fafafa345d2ae3b41c71bda74e8c --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0037/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "inequalities" +tags = ["inequalities", "amgm", "msc-26", "train", "lean4"] +msc = "26" +family = "amgm" +split = "train" +seed = 37 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-amgm-d1-t0037/tests/Verify.lean b/tasks/inequalities/inequalities-amgm-d1-t0037/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0037/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-amgm-d1-t0037/tests/grade.py b/tasks/inequalities/inequalities-amgm-d1-t0037/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0037/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-amgm-d1-t0037/tests/spec.json b/tasks/inequalities/inequalities-amgm-d1-t0037/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..a16a83d0847f4613f0e313b713abb1257e8feee7 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0037/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A square-completion bound for two real numbers. -/\ntheorem two_var_amgm (a b : ℝ) :\n 168 * a * b ≤ (7 * a + 6 * b) ^ 2 := by\n sorry\n", + "targets": [ + { + "name": "two_var_amgm", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-amgm-d1-t0037/tests/test.sh b/tasks/inequalities/inequalities-amgm-d1-t0037/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0037/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-amgm-d1-t0049/environment/Dockerfile b/tasks/inequalities/inequalities-amgm-d1-t0049/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0049/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-amgm-d1-t0049/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-amgm-d1-t0049/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..fd950b548c12136d405eeef18f60945802af43cc --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0049/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A square-completion bound for two real numbers. -/ +theorem two_var_amgm (a b : ℝ) : + 144 * a * b ≤ (4 * a + 9 * b) ^ 2 := by + sorry diff --git a/tasks/inequalities/inequalities-amgm-d1-t0049/instruction.md b/tasks/inequalities/inequalities-amgm-d1-t0049/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..17ba125f5e77253630fae328d2364edfc4d765cd --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0049/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that for all real numbers \(a\) and \(b\), \[144\,ab \le (4a + 9b)^2.\] + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-amgm-d1-t0049/solution/Solution.lean b/tasks/inequalities/inequalities-amgm-d1-t0049/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..229d98fec07fa598736ccb8cc795e2c3708c7c31 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0049/solution/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A square-completion bound for two real numbers. -/ +theorem two_var_amgm (a b : ℝ) : + 144 * a * b ≤ (4 * a + 9 * b) ^ 2 := by + nlinarith [sq_nonneg (4 * a - 9 * b)] diff --git a/tasks/inequalities/inequalities-amgm-d1-t0049/solution/solve.sh b/tasks/inequalities/inequalities-amgm-d1-t0049/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0049/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-amgm-d1-t0049/task.toml b/tasks/inequalities/inequalities-amgm-d1-t0049/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e4e38aa33eb1c96da85fa88ced2347607180b331 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0049/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "inequalities" +tags = ["inequalities", "amgm", "msc-26", "train", "lean4"] +msc = "26" +family = "amgm" +split = "train" +seed = 49 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-amgm-d1-t0049/tests/Verify.lean b/tasks/inequalities/inequalities-amgm-d1-t0049/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0049/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-amgm-d1-t0049/tests/grade.py b/tasks/inequalities/inequalities-amgm-d1-t0049/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0049/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-amgm-d1-t0049/tests/spec.json b/tasks/inequalities/inequalities-amgm-d1-t0049/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..592a21cc80ad4d4db1a74fb26875c71cb8a20c0c --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0049/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A square-completion bound for two real numbers. -/\ntheorem two_var_amgm (a b : ℝ) :\n 144 * a * b ≤ (4 * a + 9 * b) ^ 2 := by\n sorry\n", + "targets": [ + { + "name": "two_var_amgm", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-amgm-d1-t0049/tests/test.sh b/tasks/inequalities/inequalities-amgm-d1-t0049/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d1-t0049/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-amgm-d2-t0005/environment/Dockerfile b/tasks/inequalities/inequalities-amgm-d2-t0005/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0005/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-amgm-d2-t0005/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-amgm-d2-t0005/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..1fcc549f769069a682a2ce48492bb957a228efd7 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0005/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A weighted sum of a ratio and its reciprocal is bounded below. -/ +theorem amgm_ratio (a b : ℝ) (ha : 0 < a) (hb : 0 < b) : + 48 ≤ 16 * (a / b) + 36 * (b / a) := by + sorry diff --git a/tasks/inequalities/inequalities-amgm-d2-t0005/instruction.md b/tasks/inequalities/inequalities-amgm-d2-t0005/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c0a955e61fd544879565b0f7493b33146e6656dc --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0005/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Let \(a\) and \(b\) be positive real numbers. Prove that \[48 \le 16\frac{a}{b} + 36\frac{b}{a}.\] + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-amgm-d2-t0005/solution/Solution.lean b/tasks/inequalities/inequalities-amgm-d2-t0005/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..0a3dc0bf83bf149e7ea86ce9e3b7717dd7a866b2 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0005/solution/Solution.lean @@ -0,0 +1,12 @@ +import Mathlib + +/-- A weighted sum of a ratio and its reciprocal is bounded below. -/ +theorem amgm_ratio (a b : ℝ) (ha : 0 < a) (hb : 0 < b) : + 48 ≤ 16 * (a / b) + 36 * (b / a) := by + have ha' := ha.ne' + have hb' := hb.ne' + have key : 16 * (a / b) + 36 * (b / a) - 48 = 4 * (2 * a - 3 * b) ^ 2 / (a * b) := by + field_simp + ring + have h : 0 ≤ 4 * (2 * a - 3 * b) ^ 2 / (a * b) := by positivity + linarith diff --git a/tasks/inequalities/inequalities-amgm-d2-t0005/solution/solve.sh b/tasks/inequalities/inequalities-amgm-d2-t0005/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0005/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-amgm-d2-t0005/task.toml b/tasks/inequalities/inequalities-amgm-d2-t0005/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f149930e053f9bcf27ca8fa4d1fb6a42d66040a8 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0005/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "inequalities" +tags = ["inequalities", "amgm", "msc-26", "train", "lean4"] +msc = "26" +family = "amgm" +split = "train" +seed = 5 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-amgm-d2-t0005/tests/Verify.lean b/tasks/inequalities/inequalities-amgm-d2-t0005/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0005/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-amgm-d2-t0005/tests/grade.py b/tasks/inequalities/inequalities-amgm-d2-t0005/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0005/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-amgm-d2-t0005/tests/spec.json b/tasks/inequalities/inequalities-amgm-d2-t0005/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..e0e70932ae78ff7df93050de84720fb174d16184 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0005/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A weighted sum of a ratio and its reciprocal is bounded below. -/\ntheorem amgm_ratio (a b : ℝ) (ha : 0 < a) (hb : 0 < b) :\n 48 ≤ 16 * (a / b) + 36 * (b / a) := by\n sorry\n", + "targets": [ + { + "name": "amgm_ratio", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-amgm-d2-t0005/tests/test.sh b/tasks/inequalities/inequalities-amgm-d2-t0005/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0005/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-amgm-d2-t0041/environment/Dockerfile b/tasks/inequalities/inequalities-amgm-d2-t0041/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0041/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-amgm-d2-t0041/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-amgm-d2-t0041/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..08912fc739d0c28620bdb19f26f723ee5877d59a --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0041/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A weighted sum of a ratio and its reciprocal is bounded below. -/ +theorem amgm_ratio (a b : ℝ) (ha : 0 < a) (hb : 0 < b) : + 72 ≤ 36 * (a / b) + 36 * (b / a) := by + sorry diff --git a/tasks/inequalities/inequalities-amgm-d2-t0041/instruction.md b/tasks/inequalities/inequalities-amgm-d2-t0041/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a18e0622f531233207850d4e7680aefc631915fc --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0041/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Let \(a\) and \(b\) be positive real numbers. Prove that \[72 \le 36\frac{a}{b} + 36\frac{b}{a}.\] + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-amgm-d2-t0041/solution/Solution.lean b/tasks/inequalities/inequalities-amgm-d2-t0041/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..9ffef727532abd66d17b354febe5aaadfcd9fb19 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0041/solution/Solution.lean @@ -0,0 +1,12 @@ +import Mathlib + +/-- A weighted sum of a ratio and its reciprocal is bounded below. -/ +theorem amgm_ratio (a b : ℝ) (ha : 0 < a) (hb : 0 < b) : + 72 ≤ 36 * (a / b) + 36 * (b / a) := by + have ha' := ha.ne' + have hb' := hb.ne' + have key : 36 * (a / b) + 36 * (b / a) - 72 = 4 * (3 * a - 3 * b) ^ 2 / (a * b) := by + field_simp + ring + have h : 0 ≤ 4 * (3 * a - 3 * b) ^ 2 / (a * b) := by positivity + linarith diff --git a/tasks/inequalities/inequalities-amgm-d2-t0041/solution/solve.sh b/tasks/inequalities/inequalities-amgm-d2-t0041/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0041/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-amgm-d2-t0041/task.toml b/tasks/inequalities/inequalities-amgm-d2-t0041/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8b015a50ba850ad1934fae7696f50657662dfd2c --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0041/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "inequalities" +tags = ["inequalities", "amgm", "msc-26", "train", "lean4"] +msc = "26" +family = "amgm" +split = "train" +seed = 41 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-amgm-d2-t0041/tests/Verify.lean b/tasks/inequalities/inequalities-amgm-d2-t0041/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0041/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-amgm-d2-t0041/tests/grade.py b/tasks/inequalities/inequalities-amgm-d2-t0041/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0041/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-amgm-d2-t0041/tests/spec.json b/tasks/inequalities/inequalities-amgm-d2-t0041/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..6eabaa6fb43c57d07d0f93436db212129fdd36ac --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0041/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A weighted sum of a ratio and its reciprocal is bounded below. -/\ntheorem amgm_ratio (a b : ℝ) (ha : 0 < a) (hb : 0 < b) :\n 72 ≤ 36 * (a / b) + 36 * (b / a) := by\n sorry\n", + "targets": [ + { + "name": "amgm_ratio", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-amgm-d2-t0041/tests/test.sh b/tasks/inequalities/inequalities-amgm-d2-t0041/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0041/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-amgm-d2-t0053/environment/Dockerfile b/tasks/inequalities/inequalities-amgm-d2-t0053/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0053/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-amgm-d2-t0053/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-amgm-d2-t0053/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fbb422ecb23d59f23ac73e3eddb955ff860a47b --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0053/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A weighted sum of a ratio and its reciprocal is bounded below. -/ +theorem amgm_ratio (a b : ℝ) (ha : 0 < a) (hb : 0 < b) : + 96 ≤ 64 * (a / b) + 36 * (b / a) := by + sorry diff --git a/tasks/inequalities/inequalities-amgm-d2-t0053/instruction.md b/tasks/inequalities/inequalities-amgm-d2-t0053/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8c2248b814b6ac15464f7b6e7436517c65b2402b --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0053/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Let \(a\) and \(b\) be positive real numbers. Prove that \[96 \le 64\frac{a}{b} + 36\frac{b}{a}.\] + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-amgm-d2-t0053/solution/Solution.lean b/tasks/inequalities/inequalities-amgm-d2-t0053/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..c653621b268af7ee4f7de1113c72e5fa7c902ba7 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0053/solution/Solution.lean @@ -0,0 +1,12 @@ +import Mathlib + +/-- A weighted sum of a ratio and its reciprocal is bounded below. -/ +theorem amgm_ratio (a b : ℝ) (ha : 0 < a) (hb : 0 < b) : + 96 ≤ 64 * (a / b) + 36 * (b / a) := by + have ha' := ha.ne' + have hb' := hb.ne' + have key : 64 * (a / b) + 36 * (b / a) - 96 = 4 * (4 * a - 3 * b) ^ 2 / (a * b) := by + field_simp + ring + have h : 0 ≤ 4 * (4 * a - 3 * b) ^ 2 / (a * b) := by positivity + linarith diff --git a/tasks/inequalities/inequalities-amgm-d2-t0053/solution/solve.sh b/tasks/inequalities/inequalities-amgm-d2-t0053/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0053/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-amgm-d2-t0053/task.toml b/tasks/inequalities/inequalities-amgm-d2-t0053/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7d2df63a343ed08cbf96332ed6d64388c2a7b4e0 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0053/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "inequalities" +tags = ["inequalities", "amgm", "msc-26", "train", "lean4"] +msc = "26" +family = "amgm" +split = "train" +seed = 53 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-amgm-d2-t0053/tests/Verify.lean b/tasks/inequalities/inequalities-amgm-d2-t0053/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0053/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-amgm-d2-t0053/tests/grade.py b/tasks/inequalities/inequalities-amgm-d2-t0053/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0053/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-amgm-d2-t0053/tests/spec.json b/tasks/inequalities/inequalities-amgm-d2-t0053/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..dc1720844db20d3e8c19678943af0e0bce7a9cc5 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0053/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A weighted sum of a ratio and its reciprocal is bounded below. -/\ntheorem amgm_ratio (a b : ℝ) (ha : 0 < a) (hb : 0 < b) :\n 96 ≤ 64 * (a / b) + 36 * (b / a) := by\n sorry\n", + "targets": [ + { + "name": "amgm_ratio", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-amgm-d2-t0053/tests/test.sh b/tasks/inequalities/inequalities-amgm-d2-t0053/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0053/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-amgm-d2-t0065/environment/Dockerfile b/tasks/inequalities/inequalities-amgm-d2-t0065/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0065/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-amgm-d2-t0065/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-amgm-d2-t0065/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..b9ded9978334d9a4f37a4475073195a516f053dd --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0065/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A weighted sum of a ratio and its reciprocal is bounded below. -/ +theorem amgm_ratio (a b : ℝ) (ha : 0 < a) (hb : 0 < b) : + 10 ≤ (a / b) + 25 * (b / a) := by + sorry diff --git a/tasks/inequalities/inequalities-amgm-d2-t0065/instruction.md b/tasks/inequalities/inequalities-amgm-d2-t0065/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b0b83f53fac22f204e970b61e52aa3bb3685d8ec --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0065/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Let \(a\) and \(b\) be positive real numbers. Prove that \[10 \le \frac{a}{b} + 25\frac{b}{a}.\] + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-amgm-d2-t0065/solution/Solution.lean b/tasks/inequalities/inequalities-amgm-d2-t0065/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..c12599753bb423fa56eff0c071a15ff9ada16033 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0065/solution/Solution.lean @@ -0,0 +1,12 @@ +import Mathlib + +/-- A weighted sum of a ratio and its reciprocal is bounded below. -/ +theorem amgm_ratio (a b : ℝ) (ha : 0 < a) (hb : 0 < b) : + 10 ≤ (a / b) + 25 * (b / a) := by + have ha' := ha.ne' + have hb' := hb.ne' + have key : (a / b) + 25 * (b / a) - 10 = 1 * (a - 5 * b) ^ 2 / (a * b) := by + field_simp + ring + have h : 0 ≤ 1 * (a - 5 * b) ^ 2 / (a * b) := by positivity + linarith diff --git a/tasks/inequalities/inequalities-amgm-d2-t0065/solution/solve.sh b/tasks/inequalities/inequalities-amgm-d2-t0065/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0065/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-amgm-d2-t0065/task.toml b/tasks/inequalities/inequalities-amgm-d2-t0065/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..03f8fa16bce19572e970002d127fba0c2d53ee62 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0065/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "inequalities" +tags = ["inequalities", "amgm", "msc-26", "train", "lean4"] +msc = "26" +family = "amgm" +split = "train" +seed = 65 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-amgm-d2-t0065/tests/Verify.lean b/tasks/inequalities/inequalities-amgm-d2-t0065/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0065/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-amgm-d2-t0065/tests/grade.py b/tasks/inequalities/inequalities-amgm-d2-t0065/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0065/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-amgm-d2-t0065/tests/spec.json b/tasks/inequalities/inequalities-amgm-d2-t0065/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..69ac77c9d9bbe416d947178b8235bb9fb0668c2a --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0065/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A weighted sum of a ratio and its reciprocal is bounded below. -/\ntheorem amgm_ratio (a b : ℝ) (ha : 0 < a) (hb : 0 < b) :\n 10 ≤ (a / b) + 25 * (b / a) := by\n sorry\n", + "targets": [ + { + "name": "amgm_ratio", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-amgm-d2-t0065/tests/test.sh b/tasks/inequalities/inequalities-amgm-d2-t0065/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0065/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-amgm-d2-t0077/environment/Dockerfile b/tasks/inequalities/inequalities-amgm-d2-t0077/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0077/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-amgm-d2-t0077/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-amgm-d2-t0077/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..1f86ecaaca325d7c21aea87281865259692023f9 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0077/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The sum of a linear term and an inverse term is bounded below. -/ +theorem amgm_linear_plus_inverse (x : ℝ) (hx : 0 < x) : + 8 ≤ 4 * x + 4 / x := by + sorry diff --git a/tasks/inequalities/inequalities-amgm-d2-t0077/instruction.md b/tasks/inequalities/inequalities-amgm-d2-t0077/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4a8161283d77012909fd031d005534a2a7dbcac5 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0077/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Let \(x\) be a positive real number. Prove that \[8 \le 4x + \frac{4}{x}.\] + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-amgm-d2-t0077/solution/Solution.lean b/tasks/inequalities/inequalities-amgm-d2-t0077/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..b5006ad1bf9e48270b19c271fffd6dc913798fbf --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0077/solution/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The sum of a linear term and an inverse term is bounded below. -/ +theorem amgm_linear_plus_inverse (x : ℝ) (hx : 0 < x) : + 8 ≤ 4 * x + 4 / x := by + have hx' := hx.ne' + have key : 4 * x + 4 / x - 8 = 1 * (2 * x - 2) ^ 2 / x := by + field_simp + ring + have h : 0 ≤ 1 * (2 * x - 2) ^ 2 / x := by positivity + linarith diff --git a/tasks/inequalities/inequalities-amgm-d2-t0077/solution/solve.sh b/tasks/inequalities/inequalities-amgm-d2-t0077/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0077/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-amgm-d2-t0077/task.toml b/tasks/inequalities/inequalities-amgm-d2-t0077/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..af8dcedb697fa7da4b56fbcbecc2e627ee338413 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0077/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "inequalities" +tags = ["inequalities", "amgm", "msc-26", "train", "lean4"] +msc = "26" +family = "amgm" +split = "train" +seed = 77 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-amgm-d2-t0077/tests/Verify.lean b/tasks/inequalities/inequalities-amgm-d2-t0077/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0077/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-amgm-d2-t0077/tests/grade.py b/tasks/inequalities/inequalities-amgm-d2-t0077/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0077/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-amgm-d2-t0077/tests/spec.json b/tasks/inequalities/inequalities-amgm-d2-t0077/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..6888ce4f5a8f0975cdb5dfc1ef29caacaf6a427e --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0077/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The sum of a linear term and an inverse term is bounded below. -/\ntheorem amgm_linear_plus_inverse (x : ℝ) (hx : 0 < x) :\n 8 ≤ 4 * x + 4 / x := by\n sorry\n", + "targets": [ + { + "name": "amgm_linear_plus_inverse", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-amgm-d2-t0077/tests/test.sh b/tasks/inequalities/inequalities-amgm-d2-t0077/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d2-t0077/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-amgm-d3-e0009/environment/Dockerfile b/tasks/inequalities/inequalities-amgm-d3-e0009/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d3-e0009/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-amgm-d3-e0009/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-amgm-d3-e0009/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..c72febf95237a661312c503fcb9fd841b515dcc1 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d3-e0009/environment/workdir/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The three-variable AM-GM inequality in cubic form. -/ +theorem amgm_three (x y z : ℝ) (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 ≤ z) : + 27 * x * y * z ≤ (x + y + z) ^ 3 := by + sorry + +/-- The scaled three-variable inequality. -/ +theorem amgm_three_scaled (a b c : ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) : + 486 * a * b * c ≤ (a + 3 * b + 6 * c) ^ 3 := by + sorry diff --git a/tasks/inequalities/inequalities-amgm-d3-e0009/instruction.md b/tasks/inequalities/inequalities-amgm-d3-e0009/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..871988b05a7fe5e294a81bc92300394d2d66de65 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d3-e0009/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that \(27xyz \le (x+y+z)^3\) for all non-negative real numbers \(x, y, z\). Then prove that for all non-negative real numbers \(a, b, c\), \[486\,abc \le (a + 3b + 6c)^3.\] + +## What to do + +`Solution.lean` in the working directory states 2 theorems in Lean 4 with Mathlib, with `sorry` in place of each proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is the share of the 2 theorems that are proved. If the file does not compile the reward is 0, so leave `sorry` on a theorem you cannot finish rather than a broken proof. diff --git a/tasks/inequalities/inequalities-amgm-d3-e0009/solution/Solution.lean b/tasks/inequalities/inequalities-amgm-d3-e0009/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..cc122d3256adabbb45234cc81fad1b35f3b72aaa --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d3-e0009/solution/Solution.lean @@ -0,0 +1,12 @@ +import Mathlib + +/-- The three-variable AM-GM inequality in cubic form. -/ +theorem amgm_three (x y z : ℝ) (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 ≤ z) : + 27 * x * y * z ≤ (x + y + z) ^ 3 := by + nlinarith [mul_nonneg hx (sq_nonneg (y - z)), mul_nonneg hy (sq_nonneg (z - x)), mul_nonneg hz (sq_nonneg (x - y)), mul_nonneg hx (sq_nonneg (x - y)), mul_nonneg hx (sq_nonneg (x - z)), mul_nonneg hy (sq_nonneg (y - x)), mul_nonneg hy (sq_nonneg (y - z)), mul_nonneg hz (sq_nonneg (z - x)), mul_nonneg hz (sq_nonneg (z - y))] + +/-- The scaled three-variable inequality. -/ +theorem amgm_three_scaled (a b c : ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) : + 486 * a * b * c ≤ (a + 3 * b + 6 * c) ^ 3 := by + have h := amgm_three (a) (3 * b) (6 * c) (by linarith) (by linarith) (by linarith) + nlinarith [h] diff --git a/tasks/inequalities/inequalities-amgm-d3-e0009/solution/solve.sh b/tasks/inequalities/inequalities-amgm-d3-e0009/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d3-e0009/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-amgm-d3-e0009/task.toml b/tasks/inequalities/inequalities-amgm-d3-e0009/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..458bef6bd29fe72f28626b94fe52f6b5c863cc65 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d3-e0009/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "inequalities" +tags = ["inequalities", "amgm", "msc-26", "eval", "lean4"] +msc = "26" +family = "amgm" +split = "eval" +seed = 10009 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-amgm-d3-e0009/tests/Verify.lean b/tasks/inequalities/inequalities-amgm-d3-e0009/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d3-e0009/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-amgm-d3-e0009/tests/grade.py b/tasks/inequalities/inequalities-amgm-d3-e0009/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d3-e0009/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-amgm-d3-e0009/tests/spec.json b/tasks/inequalities/inequalities-amgm-d3-e0009/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..5d6aef64e77ff3e4ac62eafe09fac5407cd2de39 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d3-e0009/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\n/-- The three-variable AM-GM inequality in cubic form. -/\ntheorem amgm_three (x y z : ℝ) (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 ≤ z) :\n 27 * x * y * z ≤ (x + y + z) ^ 3 := by\n sorry\n\n/-- The scaled three-variable inequality. -/\ntheorem amgm_three_scaled (a b c : ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) :\n 486 * a * b * c ≤ (a + 3 * b + 6 * c) ^ 3 := by\n sorry\n", + "targets": [ + { + "name": "amgm_three", + "weight": 1.0 + }, + { + "name": "amgm_three_scaled", + "weight": 2.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-amgm-d3-e0009/tests/test.sh b/tasks/inequalities/inequalities-amgm-d3-e0009/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d3-e0009/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-amgm-d3-t0009/environment/Dockerfile b/tasks/inequalities/inequalities-amgm-d3-t0009/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d3-t0009/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-amgm-d3-t0009/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-amgm-d3-t0009/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..6da7ee67188b625f0b729c66d9873132b9f871ec --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d3-t0009/environment/workdir/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The three-variable AM-GM inequality in cubic form. -/ +theorem amgm_three (x y z : ℝ) (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 ≤ z) : + 27 * x * y * z ≤ (x + y + z) ^ 3 := by + sorry + +/-- The scaled three-variable inequality. -/ +theorem amgm_three_scaled (a b c : ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) : + 6615 * a * b * c ≤ (5 * a + 7 * b + 7 * c) ^ 3 := by + sorry diff --git a/tasks/inequalities/inequalities-amgm-d3-t0009/instruction.md b/tasks/inequalities/inequalities-amgm-d3-t0009/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e18c7f7aaf9e5454a2129fb6f385e5dc186cbd1c --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d3-t0009/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that \(27xyz \le (x+y+z)^3\) for all non-negative real numbers \(x, y, z\). Then prove that for all non-negative real numbers \(a, b, c\), \[6615\,abc \le (5a + 7b + 7c)^3.\] + +## What to do + +`Solution.lean` in the working directory states 2 theorems in Lean 4 with Mathlib, with `sorry` in place of each proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is the share of the 2 theorems that are proved. If the file does not compile the reward is 0, so leave `sorry` on a theorem you cannot finish rather than a broken proof. diff --git a/tasks/inequalities/inequalities-amgm-d3-t0009/solution/Solution.lean b/tasks/inequalities/inequalities-amgm-d3-t0009/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..a0830b1d889b7ea04a34b3501cd63fa3111aec75 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d3-t0009/solution/Solution.lean @@ -0,0 +1,12 @@ +import Mathlib + +/-- The three-variable AM-GM inequality in cubic form. -/ +theorem amgm_three (x y z : ℝ) (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 ≤ z) : + 27 * x * y * z ≤ (x + y + z) ^ 3 := by + nlinarith [mul_nonneg hx (sq_nonneg (y - z)), mul_nonneg hy (sq_nonneg (z - x)), mul_nonneg hz (sq_nonneg (x - y)), mul_nonneg hx (sq_nonneg (x - y)), mul_nonneg hx (sq_nonneg (x - z)), mul_nonneg hy (sq_nonneg (y - x)), mul_nonneg hy (sq_nonneg (y - z)), mul_nonneg hz (sq_nonneg (z - x)), mul_nonneg hz (sq_nonneg (z - y))] + +/-- The scaled three-variable inequality. -/ +theorem amgm_three_scaled (a b c : ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) : + 6615 * a * b * c ≤ (5 * a + 7 * b + 7 * c) ^ 3 := by + have h := amgm_three (5 * a) (7 * b) (7 * c) (by linarith) (by linarith) (by linarith) + nlinarith [h] diff --git a/tasks/inequalities/inequalities-amgm-d3-t0009/solution/solve.sh b/tasks/inequalities/inequalities-amgm-d3-t0009/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d3-t0009/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-amgm-d3-t0009/task.toml b/tasks/inequalities/inequalities-amgm-d3-t0009/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..69084a924d99747c4c2e0fafabed557ade203d34 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d3-t0009/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "inequalities" +tags = ["inequalities", "amgm", "msc-26", "train", "lean4"] +msc = "26" +family = "amgm" +split = "train" +seed = 9 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-amgm-d3-t0009/tests/Verify.lean b/tasks/inequalities/inequalities-amgm-d3-t0009/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d3-t0009/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-amgm-d3-t0009/tests/grade.py b/tasks/inequalities/inequalities-amgm-d3-t0009/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d3-t0009/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-amgm-d3-t0009/tests/spec.json b/tasks/inequalities/inequalities-amgm-d3-t0009/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..17805830e57ae200714b24d1805d4f6a25085576 --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d3-t0009/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\n/-- The three-variable AM-GM inequality in cubic form. -/\ntheorem amgm_three (x y z : ℝ) (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 ≤ z) :\n 27 * x * y * z ≤ (x + y + z) ^ 3 := by\n sorry\n\n/-- The scaled three-variable inequality. -/\ntheorem amgm_three_scaled (a b c : ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) (hc : 0 ≤ c) :\n 6615 * a * b * c ≤ (5 * a + 7 * b + 7 * c) ^ 3 := by\n sorry\n", + "targets": [ + { + "name": "amgm_three", + "weight": 1.0 + }, + { + "name": "amgm_three_scaled", + "weight": 2.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-amgm-d3-t0009/tests/test.sh b/tasks/inequalities/inequalities-amgm-d3-t0009/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-amgm-d3-t0009/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-cauchy-d1-e0014/environment/Dockerfile b/tasks/inequalities/inequalities-cauchy-d1-e0014/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-e0014/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-cauchy-d1-e0014/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-cauchy-d1-e0014/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..8a02dd204bad03f8c1bad8b2ab1f4e55c907c33f --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-e0014/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A two-term Cauchy-Schwarz bound. -/ +theorem cauchy_two (x y : ℝ) : + (9 * x + 4 * y) ^ 2 ≤ 97 * (x ^ 2 + y ^ 2) := by + sorry diff --git a/tasks/inequalities/inequalities-cauchy-d1-e0014/instruction.md b/tasks/inequalities/inequalities-cauchy-d1-e0014/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..526cc4e192707ab965fbc9b28f9236707d4a6881 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-e0014/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that for all real numbers \(x\) and \(y\), \[(9x + 4y)^2 \le 97\,(x^2 + y^2).\] + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-cauchy-d1-e0014/solution/Solution.lean b/tasks/inequalities/inequalities-cauchy-d1-e0014/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..524a9506576218cc2fb8fae80cd29b08429bc95c --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-e0014/solution/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A two-term Cauchy-Schwarz bound. -/ +theorem cauchy_two (x y : ℝ) : + (9 * x + 4 * y) ^ 2 ≤ 97 * (x ^ 2 + y ^ 2) := by + nlinarith [sq_nonneg (4 * x - 9 * y)] diff --git a/tasks/inequalities/inequalities-cauchy-d1-e0014/solution/solve.sh b/tasks/inequalities/inequalities-cauchy-d1-e0014/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-e0014/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-cauchy-d1-e0014/task.toml b/tasks/inequalities/inequalities-cauchy-d1-e0014/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7f85f341fe7ae779dfcc7d29f6bd9be626042e3d --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-e0014/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "inequalities" +tags = ["inequalities", "cauchy", "msc-26", "eval", "lean4"] +msc = "26" +family = "cauchy" +split = "eval" +seed = 10014 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-cauchy-d1-e0014/tests/Verify.lean b/tasks/inequalities/inequalities-cauchy-d1-e0014/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-e0014/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-cauchy-d1-e0014/tests/grade.py b/tasks/inequalities/inequalities-cauchy-d1-e0014/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-e0014/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-cauchy-d1-e0014/tests/spec.json b/tasks/inequalities/inequalities-cauchy-d1-e0014/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..5c1416e15ea9455c64aa47d51006339b15200d2a --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-e0014/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A two-term Cauchy-Schwarz bound. -/\ntheorem cauchy_two (x y : ℝ) :\n (9 * x + 4 * y) ^ 2 ≤ 97 * (x ^ 2 + y ^ 2) := by\n sorry\n", + "targets": [ + { + "name": "cauchy_two", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-cauchy-d1-e0014/tests/test.sh b/tasks/inequalities/inequalities-cauchy-d1-e0014/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-e0014/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0014/environment/Dockerfile b/tasks/inequalities/inequalities-cauchy-d1-t0014/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0014/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0014/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-cauchy-d1-t0014/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..c01de9aa76f4f4c8daa0461707fac6bf97c41302 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0014/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Cauchy-Schwarz with positive weights for two pairs. -/ +theorem weighted_cauchy (a b c d : ℝ) : + (5 * a * c + 4 * b * d) ^ 2 ≤ (5 * a ^ 2 + 4 * b ^ 2) * (5 * c ^ 2 + 4 * d ^ 2) := by + sorry diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0014/instruction.md b/tasks/inequalities/inequalities-cauchy-d1-t0014/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9a69252a3a50b5d7078deaa26858ad702190a2cf --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0014/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that for all real numbers \(a, b, c, d\), \[(5ac + 4bd)^2 \le (5a^2 + 4b^2)(5c^2 + 4d^2).\] + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0014/solution/Solution.lean b/tasks/inequalities/inequalities-cauchy-d1-t0014/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..c76c1c064e8dc71255b86ea137cdf5390a175024 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0014/solution/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Cauchy-Schwarz with positive weights for two pairs. -/ +theorem weighted_cauchy (a b c d : ℝ) : + (5 * a * c + 4 * b * d) ^ 2 ≤ (5 * a ^ 2 + 4 * b ^ 2) * (5 * c ^ 2 + 4 * d ^ 2) := by + nlinarith [mul_nonneg (show (0 : ℝ) ≤ 20 by norm_num) (sq_nonneg (a * d - b * c))] diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0014/solution/solve.sh b/tasks/inequalities/inequalities-cauchy-d1-t0014/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0014/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0014/task.toml b/tasks/inequalities/inequalities-cauchy-d1-t0014/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bbca5f6bb163d133ab9ec8d6e22d54fb030b54d7 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0014/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "inequalities" +tags = ["inequalities", "cauchy", "msc-26", "train", "lean4"] +msc = "26" +family = "cauchy" +split = "train" +seed = 14 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0014/tests/Verify.lean b/tasks/inequalities/inequalities-cauchy-d1-t0014/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0014/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0014/tests/grade.py b/tasks/inequalities/inequalities-cauchy-d1-t0014/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0014/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0014/tests/spec.json b/tasks/inequalities/inequalities-cauchy-d1-t0014/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..435570b179d9ae88a5d680a04bf8a3d89b404c4a --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0014/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- Cauchy-Schwarz with positive weights for two pairs. -/\ntheorem weighted_cauchy (a b c d : ℝ) :\n (5 * a * c + 4 * b * d) ^ 2 ≤ (5 * a ^ 2 + 4 * b ^ 2) * (5 * c ^ 2 + 4 * d ^ 2) := by\n sorry\n", + "targets": [ + { + "name": "weighted_cauchy", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0014/tests/test.sh b/tasks/inequalities/inequalities-cauchy-d1-t0014/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0014/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0038/environment/Dockerfile b/tasks/inequalities/inequalities-cauchy-d1-t0038/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0038/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0038/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-cauchy-d1-t0038/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..8a8d768c153728a2ab59aeda444cbfa82f372cdf --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0038/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Cauchy-Schwarz with positive weights for two pairs. -/ +theorem weighted_cauchy (a b c d : ℝ) : + (7 * a * c + 3 * b * d) ^ 2 ≤ (7 * a ^ 2 + 3 * b ^ 2) * (7 * c ^ 2 + 3 * d ^ 2) := by + sorry diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0038/instruction.md b/tasks/inequalities/inequalities-cauchy-d1-t0038/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..aa7b1fbe42402f9ad0afef49933c0592d40d073f --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0038/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that for all real numbers \(a, b, c, d\), \[(7ac + 3bd)^2 \le (7a^2 + 3b^2)(7c^2 + 3d^2).\] + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0038/solution/Solution.lean b/tasks/inequalities/inequalities-cauchy-d1-t0038/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..29daab04d8615800040d78e186fcc50bedc642de --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0038/solution/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Cauchy-Schwarz with positive weights for two pairs. -/ +theorem weighted_cauchy (a b c d : ℝ) : + (7 * a * c + 3 * b * d) ^ 2 ≤ (7 * a ^ 2 + 3 * b ^ 2) * (7 * c ^ 2 + 3 * d ^ 2) := by + nlinarith [mul_nonneg (show (0 : ℝ) ≤ 21 by norm_num) (sq_nonneg (a * d - b * c))] diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0038/solution/solve.sh b/tasks/inequalities/inequalities-cauchy-d1-t0038/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0038/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0038/task.toml b/tasks/inequalities/inequalities-cauchy-d1-t0038/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..600a7ffdfdc95bbfcf2a0885dccf96a813c3b69c --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0038/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "inequalities" +tags = ["inequalities", "cauchy", "msc-26", "train", "lean4"] +msc = "26" +family = "cauchy" +split = "train" +seed = 38 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0038/tests/Verify.lean b/tasks/inequalities/inequalities-cauchy-d1-t0038/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0038/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0038/tests/grade.py b/tasks/inequalities/inequalities-cauchy-d1-t0038/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0038/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0038/tests/spec.json b/tasks/inequalities/inequalities-cauchy-d1-t0038/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..ac352bdd39949d3509ced8fd4bbb6f262b7e07c8 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0038/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- Cauchy-Schwarz with positive weights for two pairs. -/\ntheorem weighted_cauchy (a b c d : ℝ) :\n (7 * a * c + 3 * b * d) ^ 2 ≤ (7 * a ^ 2 + 3 * b ^ 2) * (7 * c ^ 2 + 3 * d ^ 2) := by\n sorry\n", + "targets": [ + { + "name": "weighted_cauchy", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0038/tests/test.sh b/tasks/inequalities/inequalities-cauchy-d1-t0038/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0038/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0062/environment/Dockerfile b/tasks/inequalities/inequalities-cauchy-d1-t0062/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0062/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0062/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-cauchy-d1-t0062/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..dd1f498c3b4c454a3cd50efe129c19e542e717c5 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0062/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Cauchy-Schwarz with positive weights for two pairs. -/ +theorem weighted_cauchy (a b c d : ℝ) : + (3 * a * c + 2 * b * d) ^ 2 ≤ (3 * a ^ 2 + 2 * b ^ 2) * (3 * c ^ 2 + 2 * d ^ 2) := by + sorry diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0062/instruction.md b/tasks/inequalities/inequalities-cauchy-d1-t0062/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b10a48d52584314f9b50c3beaf6ba8352e53f65c --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0062/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that for all real numbers \(a, b, c, d\), \[(3ac + 2bd)^2 \le (3a^2 + 2b^2)(3c^2 + 2d^2).\] + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0062/solution/Solution.lean b/tasks/inequalities/inequalities-cauchy-d1-t0062/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..fe48ba5d5a7f34a28ce49a69b3bf7a7b419b6bf1 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0062/solution/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Cauchy-Schwarz with positive weights for two pairs. -/ +theorem weighted_cauchy (a b c d : ℝ) : + (3 * a * c + 2 * b * d) ^ 2 ≤ (3 * a ^ 2 + 2 * b ^ 2) * (3 * c ^ 2 + 2 * d ^ 2) := by + nlinarith [mul_nonneg (show (0 : ℝ) ≤ 6 by norm_num) (sq_nonneg (a * d - b * c))] diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0062/solution/solve.sh b/tasks/inequalities/inequalities-cauchy-d1-t0062/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0062/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0062/task.toml b/tasks/inequalities/inequalities-cauchy-d1-t0062/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9d0c052bf7b1ddb5f814fdb5eff1980e8ef294ef --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0062/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "inequalities" +tags = ["inequalities", "cauchy", "msc-26", "train", "lean4"] +msc = "26" +family = "cauchy" +split = "train" +seed = 62 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0062/tests/Verify.lean b/tasks/inequalities/inequalities-cauchy-d1-t0062/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0062/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0062/tests/grade.py b/tasks/inequalities/inequalities-cauchy-d1-t0062/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0062/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0062/tests/spec.json b/tasks/inequalities/inequalities-cauchy-d1-t0062/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..e4d2dabe04fce8f53a09046315e8cfab59c87e77 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0062/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- Cauchy-Schwarz with positive weights for two pairs. -/\ntheorem weighted_cauchy (a b c d : ℝ) :\n (3 * a * c + 2 * b * d) ^ 2 ≤ (3 * a ^ 2 + 2 * b ^ 2) * (3 * c ^ 2 + 2 * d ^ 2) := by\n sorry\n", + "targets": [ + { + "name": "weighted_cauchy", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-cauchy-d1-t0062/tests/test.sh b/tasks/inequalities/inequalities-cauchy-d1-t0062/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d1-t0062/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-cauchy-d2-e0006/environment/Dockerfile b/tasks/inequalities/inequalities-cauchy-d2-e0006/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-e0006/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-cauchy-d2-e0006/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-cauchy-d2-e0006/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..3013f0d40fa36bedbf75eac86349afceb608a767 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-e0006/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A linear form is bounded on a disc by the Cauchy-Schwarz inequality. -/ +theorem cauchy_bound_circle (x y : ℝ) (h : x ^ 2 + y ^ 2 ≤ 16) : + 8 * x + 15 * y ≤ 68 := by + sorry diff --git a/tasks/inequalities/inequalities-cauchy-d2-e0006/instruction.md b/tasks/inequalities/inequalities-cauchy-d2-e0006/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..46b8d4c5f83c2866177ba5237f9404935237fcb3 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-e0006/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Let \(x\) and \(y\) be real numbers with \(x^2 + y^2 \le 16\). Prove that \(8x + 15y \le 68\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-cauchy-d2-e0006/solution/Solution.lean b/tasks/inequalities/inequalities-cauchy-d2-e0006/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..4e57bdc52f81393c3a11f853478c2e01fc82cf85 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-e0006/solution/Solution.lean @@ -0,0 +1,10 @@ +import Mathlib + +/-- A linear form is bounded on a disc by the Cauchy-Schwarz inequality. -/ +theorem cauchy_bound_circle (x y : ℝ) (h : x ^ 2 + y ^ 2 ≤ 16) : + 8 * x + 15 * y ≤ 68 := by + have h1 : (8 * x + 15 * y) ^ 2 ≤ 68 ^ 2 := by + nlinarith [sq_nonneg (15 * x - (8) * y)] + by_contra hc + push_neg at hc + nlinarith [h1, hc] diff --git a/tasks/inequalities/inequalities-cauchy-d2-e0006/solution/solve.sh b/tasks/inequalities/inequalities-cauchy-d2-e0006/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-e0006/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-cauchy-d2-e0006/task.toml b/tasks/inequalities/inequalities-cauchy-d2-e0006/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9c409cce8fe437ce0a7b121262633a405d82e621 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-e0006/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "inequalities" +tags = ["inequalities", "cauchy", "msc-26", "eval", "lean4"] +msc = "26" +family = "cauchy" +split = "eval" +seed = 10006 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-cauchy-d2-e0006/tests/Verify.lean b/tasks/inequalities/inequalities-cauchy-d2-e0006/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-e0006/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-cauchy-d2-e0006/tests/grade.py b/tasks/inequalities/inequalities-cauchy-d2-e0006/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-e0006/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-cauchy-d2-e0006/tests/spec.json b/tasks/inequalities/inequalities-cauchy-d2-e0006/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..12c12c68af80ef26ea16bc504db7119dd629403f --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-e0006/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A linear form is bounded on a disc by the Cauchy-Schwarz inequality. -/\ntheorem cauchy_bound_circle (x y : ℝ) (h : x ^ 2 + y ^ 2 ≤ 16) :\n 8 * x + 15 * y ≤ 68 := by\n sorry\n", + "targets": [ + { + "name": "cauchy_bound_circle", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-cauchy-d2-e0006/tests/test.sh b/tasks/inequalities/inequalities-cauchy-d2-e0006/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-e0006/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0006/environment/Dockerfile b/tasks/inequalities/inequalities-cauchy-d2-t0006/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0006/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0006/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-cauchy-d2-t0006/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..13e6990a7a9445f5a7bd528cc96583ee00c920c3 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0006/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A linear form is bounded on a disc by the Cauchy-Schwarz inequality. -/ +theorem cauchy_bound_circle (x y : ℝ) (h : x ^ 2 + y ^ 2 ≤ 9) : + 12 * x - 16 * y ≤ 60 := by + sorry diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0006/instruction.md b/tasks/inequalities/inequalities-cauchy-d2-t0006/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c8485c81c64db95352334a19153068170c6a8242 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0006/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Let \(x\) and \(y\) be real numbers with \(x^2 + y^2 \le 9\). Prove that \(12x - 16y \le 60\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0006/solution/Solution.lean b/tasks/inequalities/inequalities-cauchy-d2-t0006/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..c5ff74ad2f98c5ce9825702ff8ae3afc2e3fb275 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0006/solution/Solution.lean @@ -0,0 +1,10 @@ +import Mathlib + +/-- A linear form is bounded on a disc by the Cauchy-Schwarz inequality. -/ +theorem cauchy_bound_circle (x y : ℝ) (h : x ^ 2 + y ^ 2 ≤ 9) : + 12 * x - 16 * y ≤ 60 := by + have h1 : (12 * x - 16 * y) ^ 2 ≤ 60 ^ 2 := by + nlinarith [sq_nonneg (16 * x - (-12) * y)] + by_contra hc + push_neg at hc + nlinarith [h1, hc] diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0006/solution/solve.sh b/tasks/inequalities/inequalities-cauchy-d2-t0006/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0006/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0006/task.toml b/tasks/inequalities/inequalities-cauchy-d2-t0006/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..dfe0fd6ea83fb92b2deb7d929cb03ab34cd0b454 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0006/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "inequalities" +tags = ["inequalities", "cauchy", "msc-26", "train", "lean4"] +msc = "26" +family = "cauchy" +split = "train" +seed = 6 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0006/tests/Verify.lean b/tasks/inequalities/inequalities-cauchy-d2-t0006/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0006/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0006/tests/grade.py b/tasks/inequalities/inequalities-cauchy-d2-t0006/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0006/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0006/tests/spec.json b/tasks/inequalities/inequalities-cauchy-d2-t0006/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..b5b6f6be8097cd5c560055516d8535cc1d51f1b0 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0006/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A linear form is bounded on a disc by the Cauchy-Schwarz inequality. -/\ntheorem cauchy_bound_circle (x y : ℝ) (h : x ^ 2 + y ^ 2 ≤ 9) :\n 12 * x - 16 * y ≤ 60 := by\n sorry\n", + "targets": [ + { + "name": "cauchy_bound_circle", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0006/tests/test.sh b/tasks/inequalities/inequalities-cauchy-d2-t0006/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0006/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0030/environment/Dockerfile b/tasks/inequalities/inequalities-cauchy-d2-t0030/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0030/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0030/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-cauchy-d2-t0030/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..fc49d30e379bf5a60561479d145577756399078f --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0030/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A linear form is bounded on a disc by the Cauchy-Schwarz inequality. -/ +theorem cauchy_bound_circle (x y : ℝ) (h : x ^ 2 + y ^ 2 ≤ 25) : + 5 * x - 12 * y ≤ 65 := by + sorry diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0030/instruction.md b/tasks/inequalities/inequalities-cauchy-d2-t0030/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5e838c422566a886669292587c4843714a9f14eb --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0030/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Let \(x\) and \(y\) be real numbers with \(x^2 + y^2 \le 25\). Prove that \(5x - 12y \le 65\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0030/solution/Solution.lean b/tasks/inequalities/inequalities-cauchy-d2-t0030/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..0685b79a2cf5610fea188a2bcc7579052574ef67 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0030/solution/Solution.lean @@ -0,0 +1,10 @@ +import Mathlib + +/-- A linear form is bounded on a disc by the Cauchy-Schwarz inequality. -/ +theorem cauchy_bound_circle (x y : ℝ) (h : x ^ 2 + y ^ 2 ≤ 25) : + 5 * x - 12 * y ≤ 65 := by + have h1 : (5 * x - 12 * y) ^ 2 ≤ 65 ^ 2 := by + nlinarith [sq_nonneg (12 * x - (-5) * y)] + by_contra hc + push_neg at hc + nlinarith [h1, hc] diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0030/solution/solve.sh b/tasks/inequalities/inequalities-cauchy-d2-t0030/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0030/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0030/task.toml b/tasks/inequalities/inequalities-cauchy-d2-t0030/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ea9d434c46fe1e9d90551af3bd34dcf49e373914 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0030/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "inequalities" +tags = ["inequalities", "cauchy", "msc-26", "train", "lean4"] +msc = "26" +family = "cauchy" +split = "train" +seed = 30 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0030/tests/Verify.lean b/tasks/inequalities/inequalities-cauchy-d2-t0030/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0030/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0030/tests/grade.py b/tasks/inequalities/inequalities-cauchy-d2-t0030/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0030/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0030/tests/spec.json b/tasks/inequalities/inequalities-cauchy-d2-t0030/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..2965b0648624af0696a624508ffe76491d250eea --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0030/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A linear form is bounded on a disc by the Cauchy-Schwarz inequality. -/\ntheorem cauchy_bound_circle (x y : ℝ) (h : x ^ 2 + y ^ 2 ≤ 25) :\n 5 * x - 12 * y ≤ 65 := by\n sorry\n", + "targets": [ + { + "name": "cauchy_bound_circle", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0030/tests/test.sh b/tasks/inequalities/inequalities-cauchy-d2-t0030/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0030/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0054/environment/Dockerfile b/tasks/inequalities/inequalities-cauchy-d2-t0054/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0054/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0054/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-cauchy-d2-t0054/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..61e4785c3de184c73042ed527a438afd3b374714 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0054/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A linear form is bounded on a disc by the Cauchy-Schwarz inequality. -/ +theorem cauchy_bound_circle (x y : ℝ) (h : x ^ 2 + y ^ 2 ≤ 9) : + 4 * x - 3 * y ≤ 15 := by + sorry diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0054/instruction.md b/tasks/inequalities/inequalities-cauchy-d2-t0054/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0d415fc0d847da5add56186b712aa81f45687a5a --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0054/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Let \(x\) and \(y\) be real numbers with \(x^2 + y^2 \le 9\). Prove that \(4x - 3y \le 15\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0054/solution/Solution.lean b/tasks/inequalities/inequalities-cauchy-d2-t0054/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..692c2fadf297e9ee16a85142959e4e0ba4df7196 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0054/solution/Solution.lean @@ -0,0 +1,10 @@ +import Mathlib + +/-- A linear form is bounded on a disc by the Cauchy-Schwarz inequality. -/ +theorem cauchy_bound_circle (x y : ℝ) (h : x ^ 2 + y ^ 2 ≤ 9) : + 4 * x - 3 * y ≤ 15 := by + have h1 : (4 * x - 3 * y) ^ 2 ≤ 15 ^ 2 := by + nlinarith [sq_nonneg (3 * x - (-4) * y)] + by_contra hc + push_neg at hc + nlinarith [h1, hc] diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0054/solution/solve.sh b/tasks/inequalities/inequalities-cauchy-d2-t0054/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0054/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0054/task.toml b/tasks/inequalities/inequalities-cauchy-d2-t0054/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..daac2c3360f9071f4a74053eecba40e5bb278481 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0054/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "inequalities" +tags = ["inequalities", "cauchy", "msc-26", "train", "lean4"] +msc = "26" +family = "cauchy" +split = "train" +seed = 54 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0054/tests/Verify.lean b/tasks/inequalities/inequalities-cauchy-d2-t0054/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0054/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0054/tests/grade.py b/tasks/inequalities/inequalities-cauchy-d2-t0054/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0054/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0054/tests/spec.json b/tasks/inequalities/inequalities-cauchy-d2-t0054/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..ae765cb8bddc040955accd002fd433d5369fe99f --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0054/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A linear form is bounded on a disc by the Cauchy-Schwarz inequality. -/\ntheorem cauchy_bound_circle (x y : ℝ) (h : x ^ 2 + y ^ 2 ≤ 9) :\n 4 * x - 3 * y ≤ 15 := by\n sorry\n", + "targets": [ + { + "name": "cauchy_bound_circle", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0054/tests/test.sh b/tasks/inequalities/inequalities-cauchy-d2-t0054/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0054/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0066/environment/Dockerfile b/tasks/inequalities/inequalities-cauchy-d2-t0066/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0066/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0066/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-cauchy-d2-t0066/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..31f633fa3c69cec764736a16f15c7604f31d0b52 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0066/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A linear form is bounded on a disc by the Cauchy-Schwarz inequality. -/ +theorem cauchy_bound_circle (x y : ℝ) (h : x ^ 2 + y ^ 2 ≤ 25) : + 9 * x + 12 * y ≤ 75 := by + sorry diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0066/instruction.md b/tasks/inequalities/inequalities-cauchy-d2-t0066/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d0743880fbdd9cf4a477337067c26ab6419157f5 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0066/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Let \(x\) and \(y\) be real numbers with \(x^2 + y^2 \le 25\). Prove that \(9x + 12y \le 75\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0066/solution/Solution.lean b/tasks/inequalities/inequalities-cauchy-d2-t0066/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..f35c031b5dda4f668c99e9e63fdc77cf855f75be --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0066/solution/Solution.lean @@ -0,0 +1,10 @@ +import Mathlib + +/-- A linear form is bounded on a disc by the Cauchy-Schwarz inequality. -/ +theorem cauchy_bound_circle (x y : ℝ) (h : x ^ 2 + y ^ 2 ≤ 25) : + 9 * x + 12 * y ≤ 75 := by + have h1 : (9 * x + 12 * y) ^ 2 ≤ 75 ^ 2 := by + nlinarith [sq_nonneg (12 * x - (9) * y)] + by_contra hc + push_neg at hc + nlinarith [h1, hc] diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0066/solution/solve.sh b/tasks/inequalities/inequalities-cauchy-d2-t0066/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0066/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0066/task.toml b/tasks/inequalities/inequalities-cauchy-d2-t0066/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..03e01aa2127cd5b77632ebc5e46cce16c7316612 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0066/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "inequalities" +tags = ["inequalities", "cauchy", "msc-26", "train", "lean4"] +msc = "26" +family = "cauchy" +split = "train" +seed = 66 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0066/tests/Verify.lean b/tasks/inequalities/inequalities-cauchy-d2-t0066/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0066/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0066/tests/grade.py b/tasks/inequalities/inequalities-cauchy-d2-t0066/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0066/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0066/tests/spec.json b/tasks/inequalities/inequalities-cauchy-d2-t0066/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..d13100a8bf43bfaf9a522230218bde380d2b8b27 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0066/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A linear form is bounded on a disc by the Cauchy-Schwarz inequality. -/\ntheorem cauchy_bound_circle (x y : ℝ) (h : x ^ 2 + y ^ 2 ≤ 25) :\n 9 * x + 12 * y ≤ 75 := by\n sorry\n", + "targets": [ + { + "name": "cauchy_bound_circle", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0066/tests/test.sh b/tasks/inequalities/inequalities-cauchy-d2-t0066/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0066/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0078/environment/Dockerfile b/tasks/inequalities/inequalities-cauchy-d2-t0078/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0078/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0078/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-cauchy-d2-t0078/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..515563215e6c0a8e1b069f78f6086ec1ea2119bc --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0078/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A linear form is bounded on a disc by the Cauchy-Schwarz inequality. -/ +theorem cauchy_bound_circle (x y : ℝ) (h : x ^ 2 + y ^ 2 ≤ 4) : + 8 * x - 6 * y ≤ 20 := by + sorry diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0078/instruction.md b/tasks/inequalities/inequalities-cauchy-d2-t0078/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..36c040425761210a6944735b1ede1bf485efdbb5 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0078/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Let \(x\) and \(y\) be real numbers with \(x^2 + y^2 \le 4\). Prove that \(8x - 6y \le 20\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0078/solution/Solution.lean b/tasks/inequalities/inequalities-cauchy-d2-t0078/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..f3d18dd357137520a49705459e107b5d70c62188 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0078/solution/Solution.lean @@ -0,0 +1,10 @@ +import Mathlib + +/-- A linear form is bounded on a disc by the Cauchy-Schwarz inequality. -/ +theorem cauchy_bound_circle (x y : ℝ) (h : x ^ 2 + y ^ 2 ≤ 4) : + 8 * x - 6 * y ≤ 20 := by + have h1 : (8 * x - 6 * y) ^ 2 ≤ 20 ^ 2 := by + nlinarith [sq_nonneg (6 * x - (-8) * y)] + by_contra hc + push_neg at hc + nlinarith [h1, hc] diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0078/solution/solve.sh b/tasks/inequalities/inequalities-cauchy-d2-t0078/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0078/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0078/task.toml b/tasks/inequalities/inequalities-cauchy-d2-t0078/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fadbed05a202ada335eb81ea0eca3fd08fd75e43 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0078/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "inequalities" +tags = ["inequalities", "cauchy", "msc-26", "train", "lean4"] +msc = "26" +family = "cauchy" +split = "train" +seed = 78 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0078/tests/Verify.lean b/tasks/inequalities/inequalities-cauchy-d2-t0078/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0078/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0078/tests/grade.py b/tasks/inequalities/inequalities-cauchy-d2-t0078/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0078/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0078/tests/spec.json b/tasks/inequalities/inequalities-cauchy-d2-t0078/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..b146a47373af7cc867f04e74663bf62ff8ae32c9 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0078/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A linear form is bounded on a disc by the Cauchy-Schwarz inequality. -/\ntheorem cauchy_bound_circle (x y : ℝ) (h : x ^ 2 + y ^ 2 ≤ 4) :\n 8 * x - 6 * y ≤ 20 := by\n sorry\n", + "targets": [ + { + "name": "cauchy_bound_circle", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-cauchy-d2-t0078/tests/test.sh b/tasks/inequalities/inequalities-cauchy-d2-t0078/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d2-t0078/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-cauchy-d3-e0022/environment/Dockerfile b/tasks/inequalities/inequalities-cauchy-d3-e0022/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-e0022/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-cauchy-d3-e0022/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-cauchy-d3-e0022/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..d65604e8793478976a27d5f2a7fbf7ac7977c4ee --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-e0022/environment/workdir/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- Cauchy-Schwarz for three-term sums. -/ +theorem cauchy_three (u v w x y z : ℝ) : + (u * x + v * y + w * z) ^ 2 ≤ (u ^ 2 + v ^ 2 + w ^ 2) * (x ^ 2 + y ^ 2 + z ^ 2) := by + sorry + +/-- A linear form is bounded on a ball. -/ +theorem cauchy_bound_ball (x y z : ℝ) (h : x ^ 2 + y ^ 2 + z ^ 2 ≤ 9) : + -4 * x - 3 * y - 12 * z ≤ 39 := by + sorry diff --git a/tasks/inequalities/inequalities-cauchy-d3-e0022/instruction.md b/tasks/inequalities/inequalities-cauchy-d3-e0022/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b92cfc865e6c169afef2e16d1bfbb9cf05d8200f --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-e0022/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that for all real numbers \(u, v, w, x, y, z\), \[(ux + vy + wz)^2 \le (u^2 + v^2 + w^2)(x^2 + y^2 + z^2).\] Then let \(x, y, z\) be real numbers with \(x^2 + y^2 + z^2 \le 9\) and prove that \(-4x - 3y - 12z \le 39\). + +## What to do + +`Solution.lean` in the working directory states 2 theorems in Lean 4 with Mathlib, with `sorry` in place of each proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is the share of the 2 theorems that are proved. If the file does not compile the reward is 0, so leave `sorry` on a theorem you cannot finish rather than a broken proof. diff --git a/tasks/inequalities/inequalities-cauchy-d3-e0022/solution/Solution.lean b/tasks/inequalities/inequalities-cauchy-d3-e0022/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..0396fe664cee7cd1e027f361d6c5b86c1a32b912 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-e0022/solution/Solution.lean @@ -0,0 +1,14 @@ +import Mathlib + +/-- Cauchy-Schwarz for three-term sums. -/ +theorem cauchy_three (u v w x y z : ℝ) : + (u * x + v * y + w * z) ^ 2 ≤ (u ^ 2 + v ^ 2 + w ^ 2) * (x ^ 2 + y ^ 2 + z ^ 2) := by + nlinarith [sq_nonneg (u * y - v * x), sq_nonneg (u * z - w * x), sq_nonneg (v * z - w * y)] + +/-- A linear form is bounded on a ball. -/ +theorem cauchy_bound_ball (x y z : ℝ) (h : x ^ 2 + y ^ 2 + z ^ 2 ≤ 9) : + -4 * x - 3 * y - 12 * z ≤ 39 := by + have h1 := cauchy_three (-4) (-3) (-12) x y z + by_contra hc + push_neg at hc + nlinarith [h1, hc] diff --git a/tasks/inequalities/inequalities-cauchy-d3-e0022/solution/solve.sh b/tasks/inequalities/inequalities-cauchy-d3-e0022/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-e0022/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-cauchy-d3-e0022/task.toml b/tasks/inequalities/inequalities-cauchy-d3-e0022/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9803da174a374ec59e987a65e22ad5ad5c5ef2cf --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-e0022/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "inequalities" +tags = ["inequalities", "cauchy", "msc-26", "eval", "lean4"] +msc = "26" +family = "cauchy" +split = "eval" +seed = 10022 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-cauchy-d3-e0022/tests/Verify.lean b/tasks/inequalities/inequalities-cauchy-d3-e0022/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-e0022/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-cauchy-d3-e0022/tests/grade.py b/tasks/inequalities/inequalities-cauchy-d3-e0022/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-e0022/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-cauchy-d3-e0022/tests/spec.json b/tasks/inequalities/inequalities-cauchy-d3-e0022/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..ae7f835bb250ebfdc36b79bee330fb9b54fcfc77 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-e0022/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\n/-- Cauchy-Schwarz for three-term sums. -/\ntheorem cauchy_three (u v w x y z : ℝ) :\n (u * x + v * y + w * z) ^ 2 ≤ (u ^ 2 + v ^ 2 + w ^ 2) * (x ^ 2 + y ^ 2 + z ^ 2) := by\n sorry\n\n/-- A linear form is bounded on a ball. -/\ntheorem cauchy_bound_ball (x y z : ℝ) (h : x ^ 2 + y ^ 2 + z ^ 2 ≤ 9) :\n -4 * x - 3 * y - 12 * z ≤ 39 := by\n sorry\n", + "targets": [ + { + "name": "cauchy_three", + "weight": 1.0 + }, + { + "name": "cauchy_bound_ball", + "weight": 2.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-cauchy-d3-e0022/tests/test.sh b/tasks/inequalities/inequalities-cauchy-d3-e0022/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-e0022/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0022/environment/Dockerfile b/tasks/inequalities/inequalities-cauchy-d3-t0022/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0022/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0022/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-cauchy-d3-t0022/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..210543edfaafff0b12af07e8e2f4996b558e9657 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0022/environment/workdir/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- Cauchy-Schwarz for three-term sums. -/ +theorem cauchy_three (u v w x y z : ℝ) : + (u * x + v * y + w * z) ^ 2 ≤ (u ^ 2 + v ^ 2 + w ^ 2) * (x ^ 2 + y ^ 2 + z ^ 2) := by + sorry + +/-- A linear form is bounded on a ball. -/ +theorem cauchy_bound_ball (x y z : ℝ) (h : x ^ 2 + y ^ 2 + z ^ 2 ≤ 16) : + -3 * x - 4 * y + 12 * z ≤ 52 := by + sorry diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0022/instruction.md b/tasks/inequalities/inequalities-cauchy-d3-t0022/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8e9d13e2f284669645fb53486582a137862aed06 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0022/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that for all real numbers \(u, v, w, x, y, z\), \[(ux + vy + wz)^2 \le (u^2 + v^2 + w^2)(x^2 + y^2 + z^2).\] Then let \(x, y, z\) be real numbers with \(x^2 + y^2 + z^2 \le 16\) and prove that \(-3x - 4y + 12z \le 52\). + +## What to do + +`Solution.lean` in the working directory states 2 theorems in Lean 4 with Mathlib, with `sorry` in place of each proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is the share of the 2 theorems that are proved. If the file does not compile the reward is 0, so leave `sorry` on a theorem you cannot finish rather than a broken proof. diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0022/solution/Solution.lean b/tasks/inequalities/inequalities-cauchy-d3-t0022/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..a89fccc5f4a8ccf1ea67bff5a327b8838076e2e9 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0022/solution/Solution.lean @@ -0,0 +1,14 @@ +import Mathlib + +/-- Cauchy-Schwarz for three-term sums. -/ +theorem cauchy_three (u v w x y z : ℝ) : + (u * x + v * y + w * z) ^ 2 ≤ (u ^ 2 + v ^ 2 + w ^ 2) * (x ^ 2 + y ^ 2 + z ^ 2) := by + nlinarith [sq_nonneg (u * y - v * x), sq_nonneg (u * z - w * x), sq_nonneg (v * z - w * y)] + +/-- A linear form is bounded on a ball. -/ +theorem cauchy_bound_ball (x y z : ℝ) (h : x ^ 2 + y ^ 2 + z ^ 2 ≤ 16) : + -3 * x - 4 * y + 12 * z ≤ 52 := by + have h1 := cauchy_three (-3) (-4) 12 x y z + by_contra hc + push_neg at hc + nlinarith [h1, hc] diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0022/solution/solve.sh b/tasks/inequalities/inequalities-cauchy-d3-t0022/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0022/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0022/task.toml b/tasks/inequalities/inequalities-cauchy-d3-t0022/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2f1bb631595d538b8694ade8a15609821077f312 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0022/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "inequalities" +tags = ["inequalities", "cauchy", "msc-26", "train", "lean4"] +msc = "26" +family = "cauchy" +split = "train" +seed = 22 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0022/tests/Verify.lean b/tasks/inequalities/inequalities-cauchy-d3-t0022/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0022/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0022/tests/grade.py b/tasks/inequalities/inequalities-cauchy-d3-t0022/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0022/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0022/tests/spec.json b/tasks/inequalities/inequalities-cauchy-d3-t0022/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..5a268cd69fd12f69541858418e1723789266f714 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0022/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\n/-- Cauchy-Schwarz for three-term sums. -/\ntheorem cauchy_three (u v w x y z : ℝ) :\n (u * x + v * y + w * z) ^ 2 ≤ (u ^ 2 + v ^ 2 + w ^ 2) * (x ^ 2 + y ^ 2 + z ^ 2) := by\n sorry\n\n/-- A linear form is bounded on a ball. -/\ntheorem cauchy_bound_ball (x y z : ℝ) (h : x ^ 2 + y ^ 2 + z ^ 2 ≤ 16) :\n -3 * x - 4 * y + 12 * z ≤ 52 := by\n sorry\n", + "targets": [ + { + "name": "cauchy_three", + "weight": 1.0 + }, + { + "name": "cauchy_bound_ball", + "weight": 2.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0022/tests/test.sh b/tasks/inequalities/inequalities-cauchy-d3-t0022/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0022/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0046/environment/Dockerfile b/tasks/inequalities/inequalities-cauchy-d3-t0046/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0046/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0046/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-cauchy-d3-t0046/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..bb3e829b4a2e55a9e1b365c0227d23c161e6d59a --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0046/environment/workdir/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- Cauchy-Schwarz for three-term sums. -/ +theorem cauchy_three (u v w x y z : ℝ) : + (u * x + v * y + w * z) ^ 2 ≤ (u ^ 2 + v ^ 2 + w ^ 2) * (x ^ 2 + y ^ 2 + z ^ 2) := by + sorry + +/-- A linear form is bounded on a ball. -/ +theorem cauchy_bound_ball (x y z : ℝ) (h : x ^ 2 + y ^ 2 + z ^ 2 ≤ 9) : + 2 * x - 10 * y - 11 * z ≤ 45 := by + sorry diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0046/instruction.md b/tasks/inequalities/inequalities-cauchy-d3-t0046/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..291d9b82262acfd6fd5f28508807811ca37eb5c8 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0046/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that for all real numbers \(u, v, w, x, y, z\), \[(ux + vy + wz)^2 \le (u^2 + v^2 + w^2)(x^2 + y^2 + z^2).\] Then let \(x, y, z\) be real numbers with \(x^2 + y^2 + z^2 \le 9\) and prove that \(2x - 10y - 11z \le 45\). + +## What to do + +`Solution.lean` in the working directory states 2 theorems in Lean 4 with Mathlib, with `sorry` in place of each proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is the share of the 2 theorems that are proved. If the file does not compile the reward is 0, so leave `sorry` on a theorem you cannot finish rather than a broken proof. diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0046/solution/Solution.lean b/tasks/inequalities/inequalities-cauchy-d3-t0046/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..e4788530edf51b9d5ec624d701474e514d43e3b1 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0046/solution/Solution.lean @@ -0,0 +1,14 @@ +import Mathlib + +/-- Cauchy-Schwarz for three-term sums. -/ +theorem cauchy_three (u v w x y z : ℝ) : + (u * x + v * y + w * z) ^ 2 ≤ (u ^ 2 + v ^ 2 + w ^ 2) * (x ^ 2 + y ^ 2 + z ^ 2) := by + nlinarith [sq_nonneg (u * y - v * x), sq_nonneg (u * z - w * x), sq_nonneg (v * z - w * y)] + +/-- A linear form is bounded on a ball. -/ +theorem cauchy_bound_ball (x y z : ℝ) (h : x ^ 2 + y ^ 2 + z ^ 2 ≤ 9) : + 2 * x - 10 * y - 11 * z ≤ 45 := by + have h1 := cauchy_three 2 (-10) (-11) x y z + by_contra hc + push_neg at hc + nlinarith [h1, hc] diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0046/solution/solve.sh b/tasks/inequalities/inequalities-cauchy-d3-t0046/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0046/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0046/task.toml b/tasks/inequalities/inequalities-cauchy-d3-t0046/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..599be4ca11f67449d57e425003b60756138b31b4 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0046/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "inequalities" +tags = ["inequalities", "cauchy", "msc-26", "train", "lean4"] +msc = "26" +family = "cauchy" +split = "train" +seed = 46 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0046/tests/Verify.lean b/tasks/inequalities/inequalities-cauchy-d3-t0046/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0046/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0046/tests/grade.py b/tasks/inequalities/inequalities-cauchy-d3-t0046/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0046/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0046/tests/spec.json b/tasks/inequalities/inequalities-cauchy-d3-t0046/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..c32694b0435ab84fcd8e2c7ee0ee4f218eb09549 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0046/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\n/-- Cauchy-Schwarz for three-term sums. -/\ntheorem cauchy_three (u v w x y z : ℝ) :\n (u * x + v * y + w * z) ^ 2 ≤ (u ^ 2 + v ^ 2 + w ^ 2) * (x ^ 2 + y ^ 2 + z ^ 2) := by\n sorry\n\n/-- A linear form is bounded on a ball. -/\ntheorem cauchy_bound_ball (x y z : ℝ) (h : x ^ 2 + y ^ 2 + z ^ 2 ≤ 9) :\n 2 * x - 10 * y - 11 * z ≤ 45 := by\n sorry\n", + "targets": [ + { + "name": "cauchy_three", + "weight": 1.0 + }, + { + "name": "cauchy_bound_ball", + "weight": 2.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0046/tests/test.sh b/tasks/inequalities/inequalities-cauchy-d3-t0046/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0046/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0070/environment/Dockerfile b/tasks/inequalities/inequalities-cauchy-d3-t0070/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0070/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0070/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-cauchy-d3-t0070/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..4cf192233681066bde07061b136b71975f08c0c5 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0070/environment/workdir/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- Cauchy-Schwarz for three-term sums. -/ +theorem cauchy_three (u v w x y z : ℝ) : + (u * x + v * y + w * z) ^ 2 ≤ (u ^ 2 + v ^ 2 + w ^ 2) * (x ^ 2 + y ^ 2 + z ^ 2) := by + sorry + +/-- A linear form is bounded on a ball. -/ +theorem cauchy_bound_ball (x y z : ℝ) (h : x ^ 2 + y ^ 2 + z ^ 2 ≤ 4) : + -6 * x + 2 * y + 3 * z ≤ 14 := by + sorry diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0070/instruction.md b/tasks/inequalities/inequalities-cauchy-d3-t0070/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5b67f60f74e0903143660d88c3cd4325e9e43927 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0070/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that for all real numbers \(u, v, w, x, y, z\), \[(ux + vy + wz)^2 \le (u^2 + v^2 + w^2)(x^2 + y^2 + z^2).\] Then let \(x, y, z\) be real numbers with \(x^2 + y^2 + z^2 \le 4\) and prove that \(-6x + 2y + 3z \le 14\). + +## What to do + +`Solution.lean` in the working directory states 2 theorems in Lean 4 with Mathlib, with `sorry` in place of each proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is the share of the 2 theorems that are proved. If the file does not compile the reward is 0, so leave `sorry` on a theorem you cannot finish rather than a broken proof. diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0070/solution/Solution.lean b/tasks/inequalities/inequalities-cauchy-d3-t0070/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..1c9edbdd9225e9af2cd42430cc8d4b06f4f5096a --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0070/solution/Solution.lean @@ -0,0 +1,14 @@ +import Mathlib + +/-- Cauchy-Schwarz for three-term sums. -/ +theorem cauchy_three (u v w x y z : ℝ) : + (u * x + v * y + w * z) ^ 2 ≤ (u ^ 2 + v ^ 2 + w ^ 2) * (x ^ 2 + y ^ 2 + z ^ 2) := by + nlinarith [sq_nonneg (u * y - v * x), sq_nonneg (u * z - w * x), sq_nonneg (v * z - w * y)] + +/-- A linear form is bounded on a ball. -/ +theorem cauchy_bound_ball (x y z : ℝ) (h : x ^ 2 + y ^ 2 + z ^ 2 ≤ 4) : + -6 * x + 2 * y + 3 * z ≤ 14 := by + have h1 := cauchy_three (-6) 2 3 x y z + by_contra hc + push_neg at hc + nlinarith [h1, hc] diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0070/solution/solve.sh b/tasks/inequalities/inequalities-cauchy-d3-t0070/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0070/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0070/task.toml b/tasks/inequalities/inequalities-cauchy-d3-t0070/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fd48ec89f83dfe4ebf93d1761c6df51fe4c25faa --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0070/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "inequalities" +tags = ["inequalities", "cauchy", "msc-26", "train", "lean4"] +msc = "26" +family = "cauchy" +split = "train" +seed = 70 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0070/tests/Verify.lean b/tasks/inequalities/inequalities-cauchy-d3-t0070/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0070/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0070/tests/grade.py b/tasks/inequalities/inequalities-cauchy-d3-t0070/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0070/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0070/tests/spec.json b/tasks/inequalities/inequalities-cauchy-d3-t0070/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..b5128307eb03fde30d0fbe0fe6bd836bc807444b --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0070/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\n/-- Cauchy-Schwarz for three-term sums. -/\ntheorem cauchy_three (u v w x y z : ℝ) :\n (u * x + v * y + w * z) ^ 2 ≤ (u ^ 2 + v ^ 2 + w ^ 2) * (x ^ 2 + y ^ 2 + z ^ 2) := by\n sorry\n\n/-- A linear form is bounded on a ball. -/\ntheorem cauchy_bound_ball (x y z : ℝ) (h : x ^ 2 + y ^ 2 + z ^ 2 ≤ 4) :\n -6 * x + 2 * y + 3 * z ≤ 14 := by\n sorry\n", + "targets": [ + { + "name": "cauchy_three", + "weight": 1.0 + }, + { + "name": "cauchy_bound_ball", + "weight": 2.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0070/tests/test.sh b/tasks/inequalities/inequalities-cauchy-d3-t0070/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0070/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0082/environment/Dockerfile b/tasks/inequalities/inequalities-cauchy-d3-t0082/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0082/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0082/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-cauchy-d3-t0082/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..0bbb5c853bc96755bacb8df322e4d61b4bf6a230 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0082/environment/workdir/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- Cauchy-Schwarz for three-term sums. -/ +theorem cauchy_three (u v w x y z : ℝ) : + (u * x + v * y + w * z) ^ 2 ≤ (u ^ 2 + v ^ 2 + w ^ 2) * (x ^ 2 + y ^ 2 + z ^ 2) := by + sorry + +/-- A linear form is bounded on a ball. -/ +theorem cauchy_bound_ball (x y z : ℝ) (h : x ^ 2 + y ^ 2 + z ^ 2 ≤ 1) : + x - 4 * y - 8 * z ≤ 9 := by + sorry diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0082/instruction.md b/tasks/inequalities/inequalities-cauchy-d3-t0082/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..521308b8030d781041c111a6c9ab5719e0862629 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0082/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that for all real numbers \(u, v, w, x, y, z\), \[(ux + vy + wz)^2 \le (u^2 + v^2 + w^2)(x^2 + y^2 + z^2).\] Then let \(x, y, z\) be real numbers with \(x^2 + y^2 + z^2 \le 1\) and prove that \(x - 4y - 8z \le 9\). + +## What to do + +`Solution.lean` in the working directory states 2 theorems in Lean 4 with Mathlib, with `sorry` in place of each proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is the share of the 2 theorems that are proved. If the file does not compile the reward is 0, so leave `sorry` on a theorem you cannot finish rather than a broken proof. diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0082/solution/Solution.lean b/tasks/inequalities/inequalities-cauchy-d3-t0082/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..077afb288c27124189c69dcfb66274095739e8fb --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0082/solution/Solution.lean @@ -0,0 +1,14 @@ +import Mathlib + +/-- Cauchy-Schwarz for three-term sums. -/ +theorem cauchy_three (u v w x y z : ℝ) : + (u * x + v * y + w * z) ^ 2 ≤ (u ^ 2 + v ^ 2 + w ^ 2) * (x ^ 2 + y ^ 2 + z ^ 2) := by + nlinarith [sq_nonneg (u * y - v * x), sq_nonneg (u * z - w * x), sq_nonneg (v * z - w * y)] + +/-- A linear form is bounded on a ball. -/ +theorem cauchy_bound_ball (x y z : ℝ) (h : x ^ 2 + y ^ 2 + z ^ 2 ≤ 1) : + x - 4 * y - 8 * z ≤ 9 := by + have h1 := cauchy_three 1 (-4) (-8) x y z + by_contra hc + push_neg at hc + nlinarith [h1, hc] diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0082/solution/solve.sh b/tasks/inequalities/inequalities-cauchy-d3-t0082/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0082/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0082/task.toml b/tasks/inequalities/inequalities-cauchy-d3-t0082/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e58074d966526f498f3af5a9ebef31a84821f078 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0082/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "inequalities" +tags = ["inequalities", "cauchy", "msc-26", "train", "lean4"] +msc = "26" +family = "cauchy" +split = "train" +seed = 82 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0082/tests/Verify.lean b/tasks/inequalities/inequalities-cauchy-d3-t0082/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0082/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0082/tests/grade.py b/tasks/inequalities/inequalities-cauchy-d3-t0082/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0082/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0082/tests/spec.json b/tasks/inequalities/inequalities-cauchy-d3-t0082/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..9acdf2000f299675ed52a03903cedc512c60f2f7 --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0082/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\n/-- Cauchy-Schwarz for three-term sums. -/\ntheorem cauchy_three (u v w x y z : ℝ) :\n (u * x + v * y + w * z) ^ 2 ≤ (u ^ 2 + v ^ 2 + w ^ 2) * (x ^ 2 + y ^ 2 + z ^ 2) := by\n sorry\n\n/-- A linear form is bounded on a ball. -/\ntheorem cauchy_bound_ball (x y z : ℝ) (h : x ^ 2 + y ^ 2 + z ^ 2 ≤ 1) :\n x - 4 * y - 8 * z ≤ 9 := by\n sorry\n", + "targets": [ + { + "name": "cauchy_three", + "weight": 1.0 + }, + { + "name": "cauchy_bound_ball", + "weight": 2.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-cauchy-d3-t0082/tests/test.sh b/tasks/inequalities/inequalities-cauchy-d3-t0082/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-cauchy-d3-t0082/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-monotone-d1-e0015/environment/Dockerfile b/tasks/inequalities/inequalities-monotone-d1-e0015/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-e0015/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-monotone-d1-e0015/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-monotone-d1-e0015/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..d102b28819c6732b2fd4d67f0a6c1d3500b57c9e --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-e0015/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The function is non-decreasing. -/ +theorem monotone_sum (x y : ℝ) (h : x ≤ y) : + 2 * Real.exp x ≤ 2 * Real.exp y := by + sorry diff --git a/tasks/inequalities/inequalities-monotone-d1-e0015/instruction.md b/tasks/inequalities/inequalities-monotone-d1-e0015/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6c18c6824074812d65cec293c7ca6493a8569381 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-e0015/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that for all real numbers \(x \le y\), \[2\,e^{x} \le 2\,e^{y}.\] + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-monotone-d1-e0015/solution/Solution.lean b/tasks/inequalities/inequalities-monotone-d1-e0015/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..f2e50bcf32273e3e281e758db506c94f7e037675 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-e0015/solution/Solution.lean @@ -0,0 +1,7 @@ +import Mathlib + +/-- The function is non-decreasing. -/ +theorem monotone_sum (x y : ℝ) (h : x ≤ y) : + 2 * Real.exp x ≤ 2 * Real.exp y := by + have h1 : Real.exp x ≤ Real.exp y := Real.exp_le_exp.2 h + linarith diff --git a/tasks/inequalities/inequalities-monotone-d1-e0015/solution/solve.sh b/tasks/inequalities/inequalities-monotone-d1-e0015/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-e0015/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-monotone-d1-e0015/task.toml b/tasks/inequalities/inequalities-monotone-d1-e0015/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..14858136f3277948e8fb926d007e887306fec940 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-e0015/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "inequalities" +tags = ["inequalities", "monotone", "msc-26", "eval", "lean4"] +msc = "26" +family = "monotone" +split = "eval" +seed = 10015 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-monotone-d1-e0015/tests/Verify.lean b/tasks/inequalities/inequalities-monotone-d1-e0015/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-e0015/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-monotone-d1-e0015/tests/grade.py b/tasks/inequalities/inequalities-monotone-d1-e0015/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-e0015/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-monotone-d1-e0015/tests/spec.json b/tasks/inequalities/inequalities-monotone-d1-e0015/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..944c9609639b23e089b8947a3462013d42790926 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-e0015/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The function is non-decreasing. -/\ntheorem monotone_sum (x y : ℝ) (h : x ≤ y) :\n 2 * Real.exp x ≤ 2 * Real.exp y := by\n sorry\n", + "targets": [ + { + "name": "monotone_sum", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-monotone-d1-e0015/tests/test.sh b/tasks/inequalities/inequalities-monotone-d1-e0015/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-e0015/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-monotone-d1-t0003/environment/Dockerfile b/tasks/inequalities/inequalities-monotone-d1-t0003/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0003/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-monotone-d1-t0003/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-monotone-d1-t0003/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..31461ee792d74d4c8bec10c1a0e386ce514c95e3 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0003/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The function is non-decreasing. -/ +theorem monotone_sum (x y : ℝ) (h : x ≤ y) : + 9 * x ^ 3 + 7 * x ≤ 9 * y ^ 3 + 7 * y := by + sorry diff --git a/tasks/inequalities/inequalities-monotone-d1-t0003/instruction.md b/tasks/inequalities/inequalities-monotone-d1-t0003/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..db749488cce8d1ba5d1e3dfa039a97460f5e4d2e --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0003/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that for all real numbers \(x \le y\), \[9\,x^3 + 7\,x \le 9\,y^3 + 7\,y.\] + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-monotone-d1-t0003/solution/Solution.lean b/tasks/inequalities/inequalities-monotone-d1-t0003/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..4a6ba1fd509e3a19dc47b9fb5e1d5da8e9605078 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0003/solution/Solution.lean @@ -0,0 +1,7 @@ +import Mathlib + +/-- The function is non-decreasing. -/ +theorem monotone_sum (x y : ℝ) (h : x ≤ y) : + 9 * x ^ 3 + 7 * x ≤ 9 * y ^ 3 + 7 * y := by + have h1 : x ^ 3 ≤ y ^ 3 := (Odd.strictMono_pow (by decide : Odd 3)).monotone h + linarith diff --git a/tasks/inequalities/inequalities-monotone-d1-t0003/solution/solve.sh b/tasks/inequalities/inequalities-monotone-d1-t0003/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0003/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-monotone-d1-t0003/task.toml b/tasks/inequalities/inequalities-monotone-d1-t0003/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..650ff5b9602f15e4c4deecdb66ce4b4da33f58a9 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0003/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "inequalities" +tags = ["inequalities", "monotone", "msc-26", "train", "lean4"] +msc = "26" +family = "monotone" +split = "train" +seed = 3 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-monotone-d1-t0003/tests/Verify.lean b/tasks/inequalities/inequalities-monotone-d1-t0003/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0003/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-monotone-d1-t0003/tests/grade.py b/tasks/inequalities/inequalities-monotone-d1-t0003/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0003/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-monotone-d1-t0003/tests/spec.json b/tasks/inequalities/inequalities-monotone-d1-t0003/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..ca850ce77e2afbc13d5f5f6019c7ddae1814fcdc --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0003/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The function is non-decreasing. -/\ntheorem monotone_sum (x y : ℝ) (h : x ≤ y) :\n 9 * x ^ 3 + 7 * x ≤ 9 * y ^ 3 + 7 * y := by\n sorry\n", + "targets": [ + { + "name": "monotone_sum", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-monotone-d1-t0003/tests/test.sh b/tasks/inequalities/inequalities-monotone-d1-t0003/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0003/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-monotone-d1-t0015/environment/Dockerfile b/tasks/inequalities/inequalities-monotone-d1-t0015/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0015/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-monotone-d1-t0015/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-monotone-d1-t0015/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..08108d1c7e58e3d2a0d54110d6405207450052bc --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0015/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The function is non-decreasing. -/ +theorem monotone_sum (x y : ℝ) (h : x ≤ y) : + 8 * x ^ 5 + 4 * x ≤ 8 * y ^ 5 + 4 * y := by + sorry diff --git a/tasks/inequalities/inequalities-monotone-d1-t0015/instruction.md b/tasks/inequalities/inequalities-monotone-d1-t0015/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f16e59da14a0137a787119b740cd20cf452b4466 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0015/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that for all real numbers \(x \le y\), \[8\,x^5 + 4\,x \le 8\,y^5 + 4\,y.\] + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-monotone-d1-t0015/solution/Solution.lean b/tasks/inequalities/inequalities-monotone-d1-t0015/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..596faabbf4a42896f31a87f0fd9a4261a66ce424 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0015/solution/Solution.lean @@ -0,0 +1,7 @@ +import Mathlib + +/-- The function is non-decreasing. -/ +theorem monotone_sum (x y : ℝ) (h : x ≤ y) : + 8 * x ^ 5 + 4 * x ≤ 8 * y ^ 5 + 4 * y := by + have h1 : x ^ 5 ≤ y ^ 5 := (Odd.strictMono_pow (by decide : Odd 5)).monotone h + linarith diff --git a/tasks/inequalities/inequalities-monotone-d1-t0015/solution/solve.sh b/tasks/inequalities/inequalities-monotone-d1-t0015/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0015/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-monotone-d1-t0015/task.toml b/tasks/inequalities/inequalities-monotone-d1-t0015/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..18a6ccf0d71e6ff23c9529946880878360d1e1ac --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0015/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "inequalities" +tags = ["inequalities", "monotone", "msc-26", "train", "lean4"] +msc = "26" +family = "monotone" +split = "train" +seed = 15 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-monotone-d1-t0015/tests/Verify.lean b/tasks/inequalities/inequalities-monotone-d1-t0015/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0015/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-monotone-d1-t0015/tests/grade.py b/tasks/inequalities/inequalities-monotone-d1-t0015/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0015/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-monotone-d1-t0015/tests/spec.json b/tasks/inequalities/inequalities-monotone-d1-t0015/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..288385ac77d8b574605f72df6d51328363c3938c --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0015/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The function is non-decreasing. -/\ntheorem monotone_sum (x y : ℝ) (h : x ≤ y) :\n 8 * x ^ 5 + 4 * x ≤ 8 * y ^ 5 + 4 * y := by\n sorry\n", + "targets": [ + { + "name": "monotone_sum", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-monotone-d1-t0015/tests/test.sh b/tasks/inequalities/inequalities-monotone-d1-t0015/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0015/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-monotone-d1-t0039/environment/Dockerfile b/tasks/inequalities/inequalities-monotone-d1-t0039/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0039/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-monotone-d1-t0039/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-monotone-d1-t0039/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..052802ceb7bc96c3f7f356fd68fa426270ab5e58 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0039/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The function is non-decreasing. -/ +theorem monotone_sum (x y : ℝ) (h : x ≤ y) : + 6 * Real.sinh x + 3 * x ≤ 6 * Real.sinh y + 3 * y := by + sorry diff --git a/tasks/inequalities/inequalities-monotone-d1-t0039/instruction.md b/tasks/inequalities/inequalities-monotone-d1-t0039/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9256991084deee430a1c0ddefa87dadb355dab52 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0039/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that for all real numbers \(x \le y\), \[6\,\sinh x + 3\,x \le 6\,\sinh y + 3\,y.\] + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-monotone-d1-t0039/solution/Solution.lean b/tasks/inequalities/inequalities-monotone-d1-t0039/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..0c5a323c43da9577d57a10699420d2f498b9ec8e --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0039/solution/Solution.lean @@ -0,0 +1,7 @@ +import Mathlib + +/-- The function is non-decreasing. -/ +theorem monotone_sum (x y : ℝ) (h : x ≤ y) : + 6 * Real.sinh x + 3 * x ≤ 6 * Real.sinh y + 3 * y := by + have h1 : Real.sinh x ≤ Real.sinh y := Real.sinh_strictMono.monotone h + linarith diff --git a/tasks/inequalities/inequalities-monotone-d1-t0039/solution/solve.sh b/tasks/inequalities/inequalities-monotone-d1-t0039/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0039/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-monotone-d1-t0039/task.toml b/tasks/inequalities/inequalities-monotone-d1-t0039/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..10e70e44dabf7b89d24fd7874b8d5425ac7f214a --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0039/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "inequalities" +tags = ["inequalities", "monotone", "msc-26", "train", "lean4"] +msc = "26" +family = "monotone" +split = "train" +seed = 39 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-monotone-d1-t0039/tests/Verify.lean b/tasks/inequalities/inequalities-monotone-d1-t0039/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0039/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-monotone-d1-t0039/tests/grade.py b/tasks/inequalities/inequalities-monotone-d1-t0039/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0039/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-monotone-d1-t0039/tests/spec.json b/tasks/inequalities/inequalities-monotone-d1-t0039/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..0f9f12a9d0ae6c07f7e3b728c5cae706d8f35db1 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0039/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The function is non-decreasing. -/\ntheorem monotone_sum (x y : ℝ) (h : x ≤ y) :\n 6 * Real.sinh x + 3 * x ≤ 6 * Real.sinh y + 3 * y := by\n sorry\n", + "targets": [ + { + "name": "monotone_sum", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-monotone-d1-t0039/tests/test.sh b/tasks/inequalities/inequalities-monotone-d1-t0039/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0039/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-monotone-d1-t0051/environment/Dockerfile b/tasks/inequalities/inequalities-monotone-d1-t0051/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0051/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-monotone-d1-t0051/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-monotone-d1-t0051/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..3ba1c75d9989a3825d38e1fdee5b71adab1ed6c5 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0051/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The function is non-decreasing. -/ +theorem monotone_sum (x y : ℝ) (h : x ≤ y) : + 4 * Real.sinh x + 7 * x ≤ 4 * Real.sinh y + 7 * y := by + sorry diff --git a/tasks/inequalities/inequalities-monotone-d1-t0051/instruction.md b/tasks/inequalities/inequalities-monotone-d1-t0051/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b972cf6469e35af4484595718a490c13ef05d692 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0051/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that for all real numbers \(x \le y\), \[4\,\sinh x + 7\,x \le 4\,\sinh y + 7\,y.\] + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-monotone-d1-t0051/solution/Solution.lean b/tasks/inequalities/inequalities-monotone-d1-t0051/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..a2bba1d0e0e98045d9e85590e2e2ba4883d42168 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0051/solution/Solution.lean @@ -0,0 +1,7 @@ +import Mathlib + +/-- The function is non-decreasing. -/ +theorem monotone_sum (x y : ℝ) (h : x ≤ y) : + 4 * Real.sinh x + 7 * x ≤ 4 * Real.sinh y + 7 * y := by + have h1 : Real.sinh x ≤ Real.sinh y := Real.sinh_strictMono.monotone h + linarith diff --git a/tasks/inequalities/inequalities-monotone-d1-t0051/solution/solve.sh b/tasks/inequalities/inequalities-monotone-d1-t0051/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0051/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-monotone-d1-t0051/task.toml b/tasks/inequalities/inequalities-monotone-d1-t0051/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..07a25d667309c7ef20c5a7c517fb0312cf67f823 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0051/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "inequalities" +tags = ["inequalities", "monotone", "msc-26", "train", "lean4"] +msc = "26" +family = "monotone" +split = "train" +seed = 51 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-monotone-d1-t0051/tests/Verify.lean b/tasks/inequalities/inequalities-monotone-d1-t0051/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0051/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-monotone-d1-t0051/tests/grade.py b/tasks/inequalities/inequalities-monotone-d1-t0051/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0051/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-monotone-d1-t0051/tests/spec.json b/tasks/inequalities/inequalities-monotone-d1-t0051/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..6b6da210021a2cdc309cf87251e70cd7077881f4 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0051/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The function is non-decreasing. -/\ntheorem monotone_sum (x y : ℝ) (h : x ≤ y) :\n 4 * Real.sinh x + 7 * x ≤ 4 * Real.sinh y + 7 * y := by\n sorry\n", + "targets": [ + { + "name": "monotone_sum", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-monotone-d1-t0051/tests/test.sh b/tasks/inequalities/inequalities-monotone-d1-t0051/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0051/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-monotone-d1-t0063/environment/Dockerfile b/tasks/inequalities/inequalities-monotone-d1-t0063/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0063/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-monotone-d1-t0063/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-monotone-d1-t0063/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..a9e70379176dd4984341942847afa3433ce35b34 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0063/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The function is non-decreasing. -/ +theorem monotone_sum (x y : ℝ) (h : x ≤ y) : + 4 * Real.exp x + 9 * x ≤ 4 * Real.exp y + 9 * y := by + sorry diff --git a/tasks/inequalities/inequalities-monotone-d1-t0063/instruction.md b/tasks/inequalities/inequalities-monotone-d1-t0063/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..904de119d47ea719bdc3667d417d3fb210947067 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0063/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that for all real numbers \(x \le y\), \[4\,e^{x} + 9\,x \le 4\,e^{y} + 9\,y.\] + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-monotone-d1-t0063/solution/Solution.lean b/tasks/inequalities/inequalities-monotone-d1-t0063/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..6bd3be4d4b5b17ccbaa9e136f2010d7ac716015f --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0063/solution/Solution.lean @@ -0,0 +1,7 @@ +import Mathlib + +/-- The function is non-decreasing. -/ +theorem monotone_sum (x y : ℝ) (h : x ≤ y) : + 4 * Real.exp x + 9 * x ≤ 4 * Real.exp y + 9 * y := by + have h1 : Real.exp x ≤ Real.exp y := Real.exp_le_exp.2 h + linarith diff --git a/tasks/inequalities/inequalities-monotone-d1-t0063/solution/solve.sh b/tasks/inequalities/inequalities-monotone-d1-t0063/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0063/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-monotone-d1-t0063/task.toml b/tasks/inequalities/inequalities-monotone-d1-t0063/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cf9913c7b914796c1431b1fc2eda710947d44ab6 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0063/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "inequalities" +tags = ["inequalities", "monotone", "msc-26", "train", "lean4"] +msc = "26" +family = "monotone" +split = "train" +seed = 63 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-monotone-d1-t0063/tests/Verify.lean b/tasks/inequalities/inequalities-monotone-d1-t0063/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0063/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-monotone-d1-t0063/tests/grade.py b/tasks/inequalities/inequalities-monotone-d1-t0063/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0063/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-monotone-d1-t0063/tests/spec.json b/tasks/inequalities/inequalities-monotone-d1-t0063/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..5478a09e86337adeceb1229630191a2d60e95ae9 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0063/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The function is non-decreasing. -/\ntheorem monotone_sum (x y : ℝ) (h : x ≤ y) :\n 4 * Real.exp x + 9 * x ≤ 4 * Real.exp y + 9 * y := by\n sorry\n", + "targets": [ + { + "name": "monotone_sum", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-monotone-d1-t0063/tests/test.sh b/tasks/inequalities/inequalities-monotone-d1-t0063/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d1-t0063/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-monotone-d2-e0007/environment/Dockerfile b/tasks/inequalities/inequalities-monotone-d2-e0007/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-e0007/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-monotone-d2-e0007/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-monotone-d2-e0007/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..c708fadd20018a50b5228233718e431bd2afc11e --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-e0007/environment/workdir/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The function is monotone. -/ +theorem monotone_function : Monotone (fun x : ℝ => 5 * Real.exp x + 4 * x ^ 5) := by + sorry diff --git a/tasks/inequalities/inequalities-monotone-d2-e0007/instruction.md b/tasks/inequalities/inequalities-monotone-d2-e0007/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..95e7b962fec816d6ce3c6372f2c2d04e372f5de5 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-e0007/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that the function \(f(x) = 5\,e^{x} + 4\,x^5\) is monotone on the real numbers: \(x \le y\) implies \(f(x) \le f(y)\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-monotone-d2-e0007/solution/Solution.lean b/tasks/inequalities/inequalities-monotone-d2-e0007/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..1fcfbcb12709bf04c340a7db04b52f9e1454d68a --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-e0007/solution/Solution.lean @@ -0,0 +1,9 @@ +import Mathlib + +/-- The function is monotone. -/ +theorem monotone_function : Monotone (fun x : ℝ => 5 * Real.exp x + 4 * x ^ 5) := by + intro x y h + have h1 : Real.exp x ≤ Real.exp y := Real.exp_le_exp.2 h + have h2 : x ^ 5 ≤ y ^ 5 := (Odd.strictMono_pow (by decide : Odd 5)).monotone h + show 5 * Real.exp x + 4 * x ^ 5 ≤ 5 * Real.exp y + 4 * y ^ 5 + linarith diff --git a/tasks/inequalities/inequalities-monotone-d2-e0007/solution/solve.sh b/tasks/inequalities/inequalities-monotone-d2-e0007/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-e0007/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-monotone-d2-e0007/task.toml b/tasks/inequalities/inequalities-monotone-d2-e0007/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2d1f4103ee9c248dd9b281033d190021dc2a2127 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-e0007/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "inequalities" +tags = ["inequalities", "monotone", "msc-26", "eval", "lean4"] +msc = "26" +family = "monotone" +split = "eval" +seed = 10007 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-monotone-d2-e0007/tests/Verify.lean b/tasks/inequalities/inequalities-monotone-d2-e0007/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-e0007/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-monotone-d2-e0007/tests/grade.py b/tasks/inequalities/inequalities-monotone-d2-e0007/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-e0007/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-monotone-d2-e0007/tests/spec.json b/tasks/inequalities/inequalities-monotone-d2-e0007/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..87b91a3f67328737edcf46bd97eadb2f2d5d4f48 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-e0007/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The function is monotone. -/\ntheorem monotone_function : Monotone (fun x : ℝ => 5 * Real.exp x + 4 * x ^ 5) := by\n sorry\n", + "targets": [ + { + "name": "monotone_function", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-monotone-d2-e0007/tests/test.sh b/tasks/inequalities/inequalities-monotone-d2-e0007/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-e0007/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-monotone-d2-e0019/environment/Dockerfile b/tasks/inequalities/inequalities-monotone-d2-e0019/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-e0019/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-monotone-d2-e0019/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-monotone-d2-e0019/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..d0a3cd857fe119e2ebeec38a103789701f9a9deb --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-e0019/environment/workdir/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The function is monotone. -/ +theorem monotone_function : Monotone (fun x : ℝ => 2 * Real.arctan x + x ^ 5) := by + sorry diff --git a/tasks/inequalities/inequalities-monotone-d2-e0019/instruction.md b/tasks/inequalities/inequalities-monotone-d2-e0019/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d87747cc826e2622084e0ac6aa759b7ed2270a11 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-e0019/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that the function \(f(x) = 2\,\arctan x + x^5\) is monotone on the real numbers: \(x \le y\) implies \(f(x) \le f(y)\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-monotone-d2-e0019/solution/Solution.lean b/tasks/inequalities/inequalities-monotone-d2-e0019/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..7fee899d21a1baa6778d3635c39b19f77a1e24d9 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-e0019/solution/Solution.lean @@ -0,0 +1,9 @@ +import Mathlib + +/-- The function is monotone. -/ +theorem monotone_function : Monotone (fun x : ℝ => 2 * Real.arctan x + x ^ 5) := by + intro x y h + have h1 : Real.arctan x ≤ Real.arctan y := Real.arctan_strictMono.monotone h + have h2 : x ^ 5 ≤ y ^ 5 := (Odd.strictMono_pow (by decide : Odd 5)).monotone h + show 2 * Real.arctan x + x ^ 5 ≤ 2 * Real.arctan y + y ^ 5 + linarith diff --git a/tasks/inequalities/inequalities-monotone-d2-e0019/solution/solve.sh b/tasks/inequalities/inequalities-monotone-d2-e0019/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-e0019/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-monotone-d2-e0019/task.toml b/tasks/inequalities/inequalities-monotone-d2-e0019/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4b413502472061e451f422bed8275ae1d1171914 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-e0019/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "inequalities" +tags = ["inequalities", "monotone", "msc-26", "eval", "lean4"] +msc = "26" +family = "monotone" +split = "eval" +seed = 10019 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-monotone-d2-e0019/tests/Verify.lean b/tasks/inequalities/inequalities-monotone-d2-e0019/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-e0019/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-monotone-d2-e0019/tests/grade.py b/tasks/inequalities/inequalities-monotone-d2-e0019/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-e0019/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-monotone-d2-e0019/tests/spec.json b/tasks/inequalities/inequalities-monotone-d2-e0019/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..04a4880da24d2db4aa04cf01693f246cd2917aa8 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-e0019/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The function is monotone. -/\ntheorem monotone_function : Monotone (fun x : ℝ => 2 * Real.arctan x + x ^ 5) := by\n sorry\n", + "targets": [ + { + "name": "monotone_function", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-monotone-d2-e0019/tests/test.sh b/tasks/inequalities/inequalities-monotone-d2-e0019/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-e0019/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-monotone-d2-t0007/environment/Dockerfile b/tasks/inequalities/inequalities-monotone-d2-t0007/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0007/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-monotone-d2-t0007/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-monotone-d2-t0007/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..d777ebb5f0201a303a0a24f084e3c6cb56e21272 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0007/environment/workdir/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The function is monotone. -/ +theorem monotone_function : Monotone (fun x : ℝ => 3 * Real.exp x + 5 * x ^ 5 + x ^ 3) := by + sorry diff --git a/tasks/inequalities/inequalities-monotone-d2-t0007/instruction.md b/tasks/inequalities/inequalities-monotone-d2-t0007/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..75e0f5f3052edeba8898919fc3c245c8cfc52257 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0007/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that the function \(f(x) = 3\,e^{x} + 5\,x^5 + x^3\) is monotone on the real numbers: \(x \le y\) implies \(f(x) \le f(y)\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-monotone-d2-t0007/solution/Solution.lean b/tasks/inequalities/inequalities-monotone-d2-t0007/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..fe5c7c7ae60ecec615526144933f83df31c53cec --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0007/solution/Solution.lean @@ -0,0 +1,10 @@ +import Mathlib + +/-- The function is monotone. -/ +theorem monotone_function : Monotone (fun x : ℝ => 3 * Real.exp x + 5 * x ^ 5 + x ^ 3) := by + intro x y h + have h1 : Real.exp x ≤ Real.exp y := Real.exp_le_exp.2 h + have h2 : x ^ 5 ≤ y ^ 5 := (Odd.strictMono_pow (by decide : Odd 5)).monotone h + have h3 : x ^ 3 ≤ y ^ 3 := (Odd.strictMono_pow (by decide : Odd 3)).monotone h + show 3 * Real.exp x + 5 * x ^ 5 + x ^ 3 ≤ 3 * Real.exp y + 5 * y ^ 5 + y ^ 3 + linarith diff --git a/tasks/inequalities/inequalities-monotone-d2-t0007/solution/solve.sh b/tasks/inequalities/inequalities-monotone-d2-t0007/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0007/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-monotone-d2-t0007/task.toml b/tasks/inequalities/inequalities-monotone-d2-t0007/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6a94b8e159a6582937b1ce0e169f655840212af9 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0007/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "inequalities" +tags = ["inequalities", "monotone", "msc-26", "train", "lean4"] +msc = "26" +family = "monotone" +split = "train" +seed = 7 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-monotone-d2-t0007/tests/Verify.lean b/tasks/inequalities/inequalities-monotone-d2-t0007/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0007/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-monotone-d2-t0007/tests/grade.py b/tasks/inequalities/inequalities-monotone-d2-t0007/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0007/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-monotone-d2-t0007/tests/spec.json b/tasks/inequalities/inequalities-monotone-d2-t0007/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..b6a4aaa5a227c44055f060597635d17270009d75 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0007/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The function is monotone. -/\ntheorem monotone_function : Monotone (fun x : ℝ => 3 * Real.exp x + 5 * x ^ 5 + x ^ 3) := by\n sorry\n", + "targets": [ + { + "name": "monotone_function", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-monotone-d2-t0007/tests/test.sh b/tasks/inequalities/inequalities-monotone-d2-t0007/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0007/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-monotone-d2-t0031/environment/Dockerfile b/tasks/inequalities/inequalities-monotone-d2-t0031/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0031/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-monotone-d2-t0031/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-monotone-d2-t0031/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..5a1af15b028b2a3d0ebaa37b655bc51affcc72e3 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0031/environment/workdir/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The function is monotone. -/ +theorem monotone_function : Monotone (fun x : ℝ => 4 * x ^ 3 + 6 * Real.arctan x + 6 * Real.sinh x) := by + sorry diff --git a/tasks/inequalities/inequalities-monotone-d2-t0031/instruction.md b/tasks/inequalities/inequalities-monotone-d2-t0031/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..499594a80fc0c5e9bf15a8c3665effe66368f351 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0031/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that the function \(f(x) = 4\,x^3 + 6\,\arctan x + 6\,\sinh x\) is monotone on the real numbers: \(x \le y\) implies \(f(x) \le f(y)\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-monotone-d2-t0031/solution/Solution.lean b/tasks/inequalities/inequalities-monotone-d2-t0031/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..37455cb0a4db700f8244500876ea22e73550a138 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0031/solution/Solution.lean @@ -0,0 +1,10 @@ +import Mathlib + +/-- The function is monotone. -/ +theorem monotone_function : Monotone (fun x : ℝ => 4 * x ^ 3 + 6 * Real.arctan x + 6 * Real.sinh x) := by + intro x y h + have h1 : x ^ 3 ≤ y ^ 3 := (Odd.strictMono_pow (by decide : Odd 3)).monotone h + have h2 : Real.arctan x ≤ Real.arctan y := Real.arctan_strictMono.monotone h + have h3 : Real.sinh x ≤ Real.sinh y := Real.sinh_strictMono.monotone h + show 4 * x ^ 3 + 6 * Real.arctan x + 6 * Real.sinh x ≤ 4 * y ^ 3 + 6 * Real.arctan y + 6 * Real.sinh y + linarith diff --git a/tasks/inequalities/inequalities-monotone-d2-t0031/solution/solve.sh b/tasks/inequalities/inequalities-monotone-d2-t0031/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0031/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-monotone-d2-t0031/task.toml b/tasks/inequalities/inequalities-monotone-d2-t0031/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cae7fd239460124b16f7f1a63e34356f1c55959e --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0031/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "inequalities" +tags = ["inequalities", "monotone", "msc-26", "train", "lean4"] +msc = "26" +family = "monotone" +split = "train" +seed = 31 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-monotone-d2-t0031/tests/Verify.lean b/tasks/inequalities/inequalities-monotone-d2-t0031/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0031/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-monotone-d2-t0031/tests/grade.py b/tasks/inequalities/inequalities-monotone-d2-t0031/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0031/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-monotone-d2-t0031/tests/spec.json b/tasks/inequalities/inequalities-monotone-d2-t0031/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..1cacf81039e35c129f6e707fe22f6f344eba8d37 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0031/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The function is monotone. -/\ntheorem monotone_function : Monotone (fun x : ℝ => 4 * x ^ 3 + 6 * Real.arctan x + 6 * Real.sinh x) := by\n sorry\n", + "targets": [ + { + "name": "monotone_function", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-monotone-d2-t0031/tests/test.sh b/tasks/inequalities/inequalities-monotone-d2-t0031/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0031/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-monotone-d2-t0055/environment/Dockerfile b/tasks/inequalities/inequalities-monotone-d2-t0055/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0055/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-monotone-d2-t0055/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-monotone-d2-t0055/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..23e9da0566a2184cf8ebc54bc8b907eeee26912c --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0055/environment/workdir/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The function is monotone. -/ +theorem monotone_function : Monotone (fun x : ℝ => 3 * Real.arctan x + 2 * Real.sinh x) := by + sorry diff --git a/tasks/inequalities/inequalities-monotone-d2-t0055/instruction.md b/tasks/inequalities/inequalities-monotone-d2-t0055/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6a6804ab49298b2b94a239398f9a2fe627860f72 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0055/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that the function \(f(x) = 3\,\arctan x + 2\,\sinh x\) is monotone on the real numbers: \(x \le y\) implies \(f(x) \le f(y)\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-monotone-d2-t0055/solution/Solution.lean b/tasks/inequalities/inequalities-monotone-d2-t0055/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..fc9f79b57ee8496780e9b1a93bd6bb05d58a7426 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0055/solution/Solution.lean @@ -0,0 +1,9 @@ +import Mathlib + +/-- The function is monotone. -/ +theorem monotone_function : Monotone (fun x : ℝ => 3 * Real.arctan x + 2 * Real.sinh x) := by + intro x y h + have h1 : Real.arctan x ≤ Real.arctan y := Real.arctan_strictMono.monotone h + have h2 : Real.sinh x ≤ Real.sinh y := Real.sinh_strictMono.monotone h + show 3 * Real.arctan x + 2 * Real.sinh x ≤ 3 * Real.arctan y + 2 * Real.sinh y + linarith diff --git a/tasks/inequalities/inequalities-monotone-d2-t0055/solution/solve.sh b/tasks/inequalities/inequalities-monotone-d2-t0055/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0055/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-monotone-d2-t0055/task.toml b/tasks/inequalities/inequalities-monotone-d2-t0055/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ee1843db34c509f4d29b904244b4226b178a64b2 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0055/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "inequalities" +tags = ["inequalities", "monotone", "msc-26", "train", "lean4"] +msc = "26" +family = "monotone" +split = "train" +seed = 55 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-monotone-d2-t0055/tests/Verify.lean b/tasks/inequalities/inequalities-monotone-d2-t0055/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0055/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-monotone-d2-t0055/tests/grade.py b/tasks/inequalities/inequalities-monotone-d2-t0055/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0055/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-monotone-d2-t0055/tests/spec.json b/tasks/inequalities/inequalities-monotone-d2-t0055/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..ca154a7e8c18c6bbab946dd4012b00bb3722411f --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0055/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The function is monotone. -/\ntheorem monotone_function : Monotone (fun x : ℝ => 3 * Real.arctan x + 2 * Real.sinh x) := by\n sorry\n", + "targets": [ + { + "name": "monotone_function", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-monotone-d2-t0055/tests/test.sh b/tasks/inequalities/inequalities-monotone-d2-t0055/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0055/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-monotone-d2-t0079/environment/Dockerfile b/tasks/inequalities/inequalities-monotone-d2-t0079/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0079/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-monotone-d2-t0079/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-monotone-d2-t0079/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..ee2a0261f05e7004d202ec1149612bfbcea669ed --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0079/environment/workdir/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The function is monotone. -/ +theorem monotone_function : Monotone (fun x : ℝ => 6 * Real.sinh x + 2 * x ^ 3) := by + sorry diff --git a/tasks/inequalities/inequalities-monotone-d2-t0079/instruction.md b/tasks/inequalities/inequalities-monotone-d2-t0079/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8c74328351e09603f664ae7c38387f4ffd593ea3 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0079/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that the function \(f(x) = 6\,\sinh x + 2\,x^3\) is monotone on the real numbers: \(x \le y\) implies \(f(x) \le f(y)\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/inequalities/inequalities-monotone-d2-t0079/solution/Solution.lean b/tasks/inequalities/inequalities-monotone-d2-t0079/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..09e3174cd575006c19df2e5999da2f1f7401f2ef --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0079/solution/Solution.lean @@ -0,0 +1,9 @@ +import Mathlib + +/-- The function is monotone. -/ +theorem monotone_function : Monotone (fun x : ℝ => 6 * Real.sinh x + 2 * x ^ 3) := by + intro x y h + have h1 : Real.sinh x ≤ Real.sinh y := Real.sinh_strictMono.monotone h + have h2 : x ^ 3 ≤ y ^ 3 := (Odd.strictMono_pow (by decide : Odd 3)).monotone h + show 6 * Real.sinh x + 2 * x ^ 3 ≤ 6 * Real.sinh y + 2 * y ^ 3 + linarith diff --git a/tasks/inequalities/inequalities-monotone-d2-t0079/solution/solve.sh b/tasks/inequalities/inequalities-monotone-d2-t0079/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0079/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-monotone-d2-t0079/task.toml b/tasks/inequalities/inequalities-monotone-d2-t0079/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..33e04de23dabba232a56ff89a5a14eb891098de2 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0079/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "inequalities" +tags = ["inequalities", "monotone", "msc-26", "train", "lean4"] +msc = "26" +family = "monotone" +split = "train" +seed = 79 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-monotone-d2-t0079/tests/Verify.lean b/tasks/inequalities/inequalities-monotone-d2-t0079/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0079/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-monotone-d2-t0079/tests/grade.py b/tasks/inequalities/inequalities-monotone-d2-t0079/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0079/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-monotone-d2-t0079/tests/spec.json b/tasks/inequalities/inequalities-monotone-d2-t0079/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..5c8bd8ac63d0bbdd45522bf24a5aa82917f24eed --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0079/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The function is monotone. -/\ntheorem monotone_function : Monotone (fun x : ℝ => 6 * Real.sinh x + 2 * x ^ 3) := by\n sorry\n", + "targets": [ + { + "name": "monotone_function", + "weight": 1.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-monotone-d2-t0079/tests/test.sh b/tasks/inequalities/inequalities-monotone-d2-t0079/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d2-t0079/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-monotone-d3-e0023/environment/Dockerfile b/tasks/inequalities/inequalities-monotone-d3-e0023/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-e0023/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-monotone-d3-e0023/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-monotone-d3-e0023/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..bb07722449f6b91a025c0b856315668091fab3ed --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-e0023/environment/workdir/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The logarithm of one plus a square is increasing on the positive reals. -/ +theorem log_one_add_sq_mono (x y : ℝ) (hx : 0 < x) (h : x ≤ y) : + 0 ≤ Real.log (1 + y ^ 2) - Real.log (1 + x ^ 2) := by + sorry + +/-- The combination is non-decreasing on the positive reals. -/ +theorem monotone_combination (x y : ℝ) (hx : 0 < x) (h : x ≤ y) : + 0 ≤ (5 * Real.exp y + 2 * y ^ 5 + 2 * Real.log y + 3 * Real.log (1 + y ^ 2)) - (5 * Real.exp x + 2 * x ^ 5 + 2 * Real.log x + 3 * Real.log (1 + x ^ 2)) := by + sorry diff --git a/tasks/inequalities/inequalities-monotone-d3-e0023/instruction.md b/tasks/inequalities/inequalities-monotone-d3-e0023/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ac28d54275f62339c478609337a3799c1d4bc757 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-e0023/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that \(0 \le \ln(1 + y^2) - \ln(1 + x^2)\) for real numbers \(0 < x \le y\). Then prove that for such \(x, y\), \[0 \le \left(5\,e^{y} + 2\,y^5 + 2\,\ln y + 3\,\ln(1 + y^2)\right) - \left(5\,e^{x} + 2\,x^5 + 2\,\ln x + 3\,\ln(1 + x^2)\right).\] + +## What to do + +`Solution.lean` in the working directory states 2 theorems in Lean 4 with Mathlib, with `sorry` in place of each proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is the share of the 2 theorems that are proved. If the file does not compile the reward is 0, so leave `sorry` on a theorem you cannot finish rather than a broken proof. diff --git a/tasks/inequalities/inequalities-monotone-d3-e0023/solution/Solution.lean b/tasks/inequalities/inequalities-monotone-d3-e0023/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..e883b4ff4bf9de05938d4e27173df852034c2732 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-e0023/solution/Solution.lean @@ -0,0 +1,19 @@ +import Mathlib + +/-- The logarithm of one plus a square is increasing on the positive reals. -/ +theorem log_one_add_sq_mono (x y : ℝ) (hx : 0 < x) (h : x ≤ y) : + 0 ≤ Real.log (1 + y ^ 2) - Real.log (1 + x ^ 2) := by + have hy : 0 < y := lt_of_lt_of_le hx h + have h3 : Real.log (1 + x ^ 2) ≤ Real.log (1 + y ^ 2) := by + apply Real.log_le_log (by positivity) + nlinarith [mul_pos hx hy, mul_nonneg (sub_nonneg.2 h) hx.le] + linarith + +/-- The combination is non-decreasing on the positive reals. -/ +theorem monotone_combination (x y : ℝ) (hx : 0 < x) (h : x ≤ y) : + 0 ≤ (5 * Real.exp y + 2 * y ^ 5 + 2 * Real.log y + 3 * Real.log (1 + y ^ 2)) - (5 * Real.exp x + 2 * x ^ 5 + 2 * Real.log x + 3 * Real.log (1 + x ^ 2)) := by + have h1 : Real.exp x ≤ Real.exp y := Real.exp_le_exp.2 h + have h2 : x ^ 5 ≤ y ^ 5 := (Odd.strictMono_pow (by decide : Odd 5)).monotone h + have h3 : Real.log x ≤ Real.log y := Real.log_le_log hx h + have h4 := log_one_add_sq_mono x y hx h + linarith diff --git a/tasks/inequalities/inequalities-monotone-d3-e0023/solution/solve.sh b/tasks/inequalities/inequalities-monotone-d3-e0023/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-e0023/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-monotone-d3-e0023/task.toml b/tasks/inequalities/inequalities-monotone-d3-e0023/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..695a30b953bebee0c5289c99c3cf2ddf97a0e5db --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-e0023/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "inequalities" +tags = ["inequalities", "monotone", "msc-26", "eval", "lean4"] +msc = "26" +family = "monotone" +split = "eval" +seed = 10023 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-monotone-d3-e0023/tests/Verify.lean b/tasks/inequalities/inequalities-monotone-d3-e0023/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-e0023/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-monotone-d3-e0023/tests/grade.py b/tasks/inequalities/inequalities-monotone-d3-e0023/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-e0023/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-monotone-d3-e0023/tests/spec.json b/tasks/inequalities/inequalities-monotone-d3-e0023/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..8a961ed808e64bfcca05df10a34f2c70e998079b --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-e0023/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\n/-- The logarithm of one plus a square is increasing on the positive reals. -/\ntheorem log_one_add_sq_mono (x y : ℝ) (hx : 0 < x) (h : x ≤ y) :\n 0 ≤ Real.log (1 + y ^ 2) - Real.log (1 + x ^ 2) := by\n sorry\n\n/-- The combination is non-decreasing on the positive reals. -/\ntheorem monotone_combination (x y : ℝ) (hx : 0 < x) (h : x ≤ y) :\n 0 ≤ (5 * Real.exp y + 2 * y ^ 5 + 2 * Real.log y + 3 * Real.log (1 + y ^ 2)) - (5 * Real.exp x + 2 * x ^ 5 + 2 * Real.log x + 3 * Real.log (1 + x ^ 2)) := by\n sorry\n", + "targets": [ + { + "name": "log_one_add_sq_mono", + "weight": 1.0 + }, + { + "name": "monotone_combination", + "weight": 2.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-monotone-d3-e0023/tests/test.sh b/tasks/inequalities/inequalities-monotone-d3-e0023/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-e0023/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-monotone-d3-t0023/environment/Dockerfile b/tasks/inequalities/inequalities-monotone-d3-t0023/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0023/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-monotone-d3-t0023/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-monotone-d3-t0023/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..ab494d91d6761325febd91671a8bcd916cc4bea7 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0023/environment/workdir/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The logarithm of one plus a square is increasing on the positive reals. -/ +theorem log_one_add_sq_mono (x y : ℝ) (hx : 0 < x) (h : x ≤ y) : + 0 ≤ Real.log (1 + y ^ 2) - Real.log (1 + x ^ 2) := by + sorry + +/-- The combination is non-decreasing on the positive reals. -/ +theorem monotone_combination (x y : ℝ) (hx : 0 < x) (h : x ≤ y) : + 0 ≤ (Real.exp y + 5 * Real.log y + 3 * Real.sqrt y + 3 * Real.log (1 + y ^ 2)) - (Real.exp x + 5 * Real.log x + 3 * Real.sqrt x + 3 * Real.log (1 + x ^ 2)) := by + sorry diff --git a/tasks/inequalities/inequalities-monotone-d3-t0023/instruction.md b/tasks/inequalities/inequalities-monotone-d3-t0023/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..df7d75cf380ac6323e7d2cd6c180d3c26a637cfc --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0023/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that \(0 \le \ln(1 + y^2) - \ln(1 + x^2)\) for real numbers \(0 < x \le y\). Then prove that for such \(x, y\), \[0 \le \left(e^{y} + 5\,\ln y + 3\,\sqrt{y} + 3\,\ln(1 + y^2)\right) - \left(e^{x} + 5\,\ln x + 3\,\sqrt{x} + 3\,\ln(1 + x^2)\right).\] + +## What to do + +`Solution.lean` in the working directory states 2 theorems in Lean 4 with Mathlib, with `sorry` in place of each proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is the share of the 2 theorems that are proved. If the file does not compile the reward is 0, so leave `sorry` on a theorem you cannot finish rather than a broken proof. diff --git a/tasks/inequalities/inequalities-monotone-d3-t0023/solution/Solution.lean b/tasks/inequalities/inequalities-monotone-d3-t0023/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..d0349f991fb4756362066f86f82e52128efc6442 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0023/solution/Solution.lean @@ -0,0 +1,19 @@ +import Mathlib + +/-- The logarithm of one plus a square is increasing on the positive reals. -/ +theorem log_one_add_sq_mono (x y : ℝ) (hx : 0 < x) (h : x ≤ y) : + 0 ≤ Real.log (1 + y ^ 2) - Real.log (1 + x ^ 2) := by + have hy : 0 < y := lt_of_lt_of_le hx h + have h3 : Real.log (1 + x ^ 2) ≤ Real.log (1 + y ^ 2) := by + apply Real.log_le_log (by positivity) + nlinarith [mul_pos hx hy, mul_nonneg (sub_nonneg.2 h) hx.le] + linarith + +/-- The combination is non-decreasing on the positive reals. -/ +theorem monotone_combination (x y : ℝ) (hx : 0 < x) (h : x ≤ y) : + 0 ≤ (Real.exp y + 5 * Real.log y + 3 * Real.sqrt y + 3 * Real.log (1 + y ^ 2)) - (Real.exp x + 5 * Real.log x + 3 * Real.sqrt x + 3 * Real.log (1 + x ^ 2)) := by + have h1 : Real.exp x ≤ Real.exp y := Real.exp_le_exp.2 h + have h2 : Real.log x ≤ Real.log y := Real.log_le_log hx h + have h3 : Real.sqrt x ≤ Real.sqrt y := Real.sqrt_le_sqrt h + have h4 := log_one_add_sq_mono x y hx h + linarith diff --git a/tasks/inequalities/inequalities-monotone-d3-t0023/solution/solve.sh b/tasks/inequalities/inequalities-monotone-d3-t0023/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0023/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-monotone-d3-t0023/task.toml b/tasks/inequalities/inequalities-monotone-d3-t0023/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..061caa330a1b26236307d2e086e84d4876a7a348 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0023/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "inequalities" +tags = ["inequalities", "monotone", "msc-26", "train", "lean4"] +msc = "26" +family = "monotone" +split = "train" +seed = 23 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-monotone-d3-t0023/tests/Verify.lean b/tasks/inequalities/inequalities-monotone-d3-t0023/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0023/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-monotone-d3-t0023/tests/grade.py b/tasks/inequalities/inequalities-monotone-d3-t0023/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0023/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-monotone-d3-t0023/tests/spec.json b/tasks/inequalities/inequalities-monotone-d3-t0023/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..da600a666cb9398b39dcd55f91ac88b2f85f7820 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0023/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\n/-- The logarithm of one plus a square is increasing on the positive reals. -/\ntheorem log_one_add_sq_mono (x y : ℝ) (hx : 0 < x) (h : x ≤ y) :\n 0 ≤ Real.log (1 + y ^ 2) - Real.log (1 + x ^ 2) := by\n sorry\n\n/-- The combination is non-decreasing on the positive reals. -/\ntheorem monotone_combination (x y : ℝ) (hx : 0 < x) (h : x ≤ y) :\n 0 ≤ (Real.exp y + 5 * Real.log y + 3 * Real.sqrt y + 3 * Real.log (1 + y ^ 2)) - (Real.exp x + 5 * Real.log x + 3 * Real.sqrt x + 3 * Real.log (1 + x ^ 2)) := by\n sorry\n", + "targets": [ + { + "name": "log_one_add_sq_mono", + "weight": 1.0 + }, + { + "name": "monotone_combination", + "weight": 2.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-monotone-d3-t0023/tests/test.sh b/tasks/inequalities/inequalities-monotone-d3-t0023/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0023/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-monotone-d3-t0035/environment/Dockerfile b/tasks/inequalities/inequalities-monotone-d3-t0035/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0035/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-monotone-d3-t0035/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-monotone-d3-t0035/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..ac937973ec7beda432f4069b7b2235200633cbd7 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0035/environment/workdir/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The logarithm of one plus a square is increasing on the positive reals. -/ +theorem log_one_add_sq_mono (x y : ℝ) (hx : 0 < x) (h : x ≤ y) : + 0 ≤ Real.log (1 + y ^ 2) - Real.log (1 + x ^ 2) := by + sorry + +/-- The combination is non-decreasing on the positive reals. -/ +theorem monotone_combination (x y : ℝ) (hx : 0 < x) (h : x ≤ y) : + 0 ≤ (5 * Real.arctan y + 2 * y ^ 2 + 2 * Real.sinh y + 4 * Real.log (1 + y ^ 2)) - (5 * Real.arctan x + 2 * x ^ 2 + 2 * Real.sinh x + 4 * Real.log (1 + x ^ 2)) := by + sorry diff --git a/tasks/inequalities/inequalities-monotone-d3-t0035/instruction.md b/tasks/inequalities/inequalities-monotone-d3-t0035/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dc4b497c39e12099ba69d26e91458a6e39219c61 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0035/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that \(0 \le \ln(1 + y^2) - \ln(1 + x^2)\) for real numbers \(0 < x \le y\). Then prove that for such \(x, y\), \[0 \le \left(5\,\arctan y + 2\,y^2 + 2\,\sinh y + 4\,\ln(1 + y^2)\right) - \left(5\,\arctan x + 2\,x^2 + 2\,\sinh x + 4\,\ln(1 + x^2)\right).\] + +## What to do + +`Solution.lean` in the working directory states 2 theorems in Lean 4 with Mathlib, with `sorry` in place of each proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is the share of the 2 theorems that are proved. If the file does not compile the reward is 0, so leave `sorry` on a theorem you cannot finish rather than a broken proof. diff --git a/tasks/inequalities/inequalities-monotone-d3-t0035/solution/Solution.lean b/tasks/inequalities/inequalities-monotone-d3-t0035/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..e38a93cd5f74d4f7206a5968dbbf3431c63baf82 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0035/solution/Solution.lean @@ -0,0 +1,19 @@ +import Mathlib + +/-- The logarithm of one plus a square is increasing on the positive reals. -/ +theorem log_one_add_sq_mono (x y : ℝ) (hx : 0 < x) (h : x ≤ y) : + 0 ≤ Real.log (1 + y ^ 2) - Real.log (1 + x ^ 2) := by + have hy : 0 < y := lt_of_lt_of_le hx h + have h3 : Real.log (1 + x ^ 2) ≤ Real.log (1 + y ^ 2) := by + apply Real.log_le_log (by positivity) + nlinarith [mul_pos hx hy, mul_nonneg (sub_nonneg.2 h) hx.le] + linarith + +/-- The combination is non-decreasing on the positive reals. -/ +theorem monotone_combination (x y : ℝ) (hx : 0 < x) (h : x ≤ y) : + 0 ≤ (5 * Real.arctan y + 2 * y ^ 2 + 2 * Real.sinh y + 4 * Real.log (1 + y ^ 2)) - (5 * Real.arctan x + 2 * x ^ 2 + 2 * Real.sinh x + 4 * Real.log (1 + x ^ 2)) := by + have h1 : Real.arctan x ≤ Real.arctan y := Real.arctan_strictMono.monotone h + have h2 : x ^ 2 ≤ y ^ 2 := pow_le_pow_left₀ hx.le h 2 + have h3 : Real.sinh x ≤ Real.sinh y := Real.sinh_strictMono.monotone h + have h4 := log_one_add_sq_mono x y hx h + linarith diff --git a/tasks/inequalities/inequalities-monotone-d3-t0035/solution/solve.sh b/tasks/inequalities/inequalities-monotone-d3-t0035/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0035/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-monotone-d3-t0035/task.toml b/tasks/inequalities/inequalities-monotone-d3-t0035/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..04a3563a0d43e5336f9baee5c0280bb5b15a1408 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0035/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "inequalities" +tags = ["inequalities", "monotone", "msc-26", "train", "lean4"] +msc = "26" +family = "monotone" +split = "train" +seed = 35 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-monotone-d3-t0035/tests/Verify.lean b/tasks/inequalities/inequalities-monotone-d3-t0035/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0035/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-monotone-d3-t0035/tests/grade.py b/tasks/inequalities/inequalities-monotone-d3-t0035/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0035/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-monotone-d3-t0035/tests/spec.json b/tasks/inequalities/inequalities-monotone-d3-t0035/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..797d0380abb5602a2586d76ed6a47a180dc6df30 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0035/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\n/-- The logarithm of one plus a square is increasing on the positive reals. -/\ntheorem log_one_add_sq_mono (x y : ℝ) (hx : 0 < x) (h : x ≤ y) :\n 0 ≤ Real.log (1 + y ^ 2) - Real.log (1 + x ^ 2) := by\n sorry\n\n/-- The combination is non-decreasing on the positive reals. -/\ntheorem monotone_combination (x y : ℝ) (hx : 0 < x) (h : x ≤ y) :\n 0 ≤ (5 * Real.arctan y + 2 * y ^ 2 + 2 * Real.sinh y + 4 * Real.log (1 + y ^ 2)) - (5 * Real.arctan x + 2 * x ^ 2 + 2 * Real.sinh x + 4 * Real.log (1 + x ^ 2)) := by\n sorry\n", + "targets": [ + { + "name": "log_one_add_sq_mono", + "weight": 1.0 + }, + { + "name": "monotone_combination", + "weight": 2.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-monotone-d3-t0035/tests/test.sh b/tasks/inequalities/inequalities-monotone-d3-t0035/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0035/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-monotone-d3-t0047/environment/Dockerfile b/tasks/inequalities/inequalities-monotone-d3-t0047/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0047/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-monotone-d3-t0047/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-monotone-d3-t0047/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..0e3381839d206670055bd308b44e1410319af905 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0047/environment/workdir/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The logarithm of one plus a square is increasing on the positive reals. -/ +theorem log_one_add_sq_mono (x y : ℝ) (hx : 0 < x) (h : x ≤ y) : + 0 ≤ Real.log (1 + y ^ 2) - Real.log (1 + x ^ 2) := by + sorry + +/-- The combination is non-decreasing on the positive reals. -/ +theorem monotone_combination (x y : ℝ) (hx : 0 < x) (h : x ≤ y) : + 0 ≤ (3 * Real.exp y + 2 * Real.log y + Real.log (1 + y ^ 2)) - (3 * Real.exp x + 2 * Real.log x + Real.log (1 + x ^ 2)) := by + sorry diff --git a/tasks/inequalities/inequalities-monotone-d3-t0047/instruction.md b/tasks/inequalities/inequalities-monotone-d3-t0047/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..38a3d0b7d9d59eb6a35a42fa283ff6e6372d6eae --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0047/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that \(0 \le \ln(1 + y^2) - \ln(1 + x^2)\) for real numbers \(0 < x \le y\). Then prove that for such \(x, y\), \[0 \le \left(3\,e^{y} + 2\,\ln y + \ln(1 + y^2)\right) - \left(3\,e^{x} + 2\,\ln x + \ln(1 + x^2)\right).\] + +## What to do + +`Solution.lean` in the working directory states 2 theorems in Lean 4 with Mathlib, with `sorry` in place of each proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is the share of the 2 theorems that are proved. If the file does not compile the reward is 0, so leave `sorry` on a theorem you cannot finish rather than a broken proof. diff --git a/tasks/inequalities/inequalities-monotone-d3-t0047/solution/Solution.lean b/tasks/inequalities/inequalities-monotone-d3-t0047/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..dd700e0aa2e374d910e0f2cb2e963a34d74ea22a --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0047/solution/Solution.lean @@ -0,0 +1,18 @@ +import Mathlib + +/-- The logarithm of one plus a square is increasing on the positive reals. -/ +theorem log_one_add_sq_mono (x y : ℝ) (hx : 0 < x) (h : x ≤ y) : + 0 ≤ Real.log (1 + y ^ 2) - Real.log (1 + x ^ 2) := by + have hy : 0 < y := lt_of_lt_of_le hx h + have h3 : Real.log (1 + x ^ 2) ≤ Real.log (1 + y ^ 2) := by + apply Real.log_le_log (by positivity) + nlinarith [mul_pos hx hy, mul_nonneg (sub_nonneg.2 h) hx.le] + linarith + +/-- The combination is non-decreasing on the positive reals. -/ +theorem monotone_combination (x y : ℝ) (hx : 0 < x) (h : x ≤ y) : + 0 ≤ (3 * Real.exp y + 2 * Real.log y + Real.log (1 + y ^ 2)) - (3 * Real.exp x + 2 * Real.log x + Real.log (1 + x ^ 2)) := by + have h1 : Real.exp x ≤ Real.exp y := Real.exp_le_exp.2 h + have h2 : Real.log x ≤ Real.log y := Real.log_le_log hx h + have h3 := log_one_add_sq_mono x y hx h + linarith diff --git a/tasks/inequalities/inequalities-monotone-d3-t0047/solution/solve.sh b/tasks/inequalities/inequalities-monotone-d3-t0047/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0047/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-monotone-d3-t0047/task.toml b/tasks/inequalities/inequalities-monotone-d3-t0047/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ba50871777c8b6310b848659cc3b1d8371ecd0f2 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0047/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "inequalities" +tags = ["inequalities", "monotone", "msc-26", "train", "lean4"] +msc = "26" +family = "monotone" +split = "train" +seed = 47 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-monotone-d3-t0047/tests/Verify.lean b/tasks/inequalities/inequalities-monotone-d3-t0047/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0047/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-monotone-d3-t0047/tests/grade.py b/tasks/inequalities/inequalities-monotone-d3-t0047/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0047/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-monotone-d3-t0047/tests/spec.json b/tasks/inequalities/inequalities-monotone-d3-t0047/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..24c1d197b04a3b8760a488b332731840e1289c73 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0047/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\n/-- The logarithm of one plus a square is increasing on the positive reals. -/\ntheorem log_one_add_sq_mono (x y : ℝ) (hx : 0 < x) (h : x ≤ y) :\n 0 ≤ Real.log (1 + y ^ 2) - Real.log (1 + x ^ 2) := by\n sorry\n\n/-- The combination is non-decreasing on the positive reals. -/\ntheorem monotone_combination (x y : ℝ) (hx : 0 < x) (h : x ≤ y) :\n 0 ≤ (3 * Real.exp y + 2 * Real.log y + Real.log (1 + y ^ 2)) - (3 * Real.exp x + 2 * Real.log x + Real.log (1 + x ^ 2)) := by\n sorry\n", + "targets": [ + { + "name": "log_one_add_sq_mono", + "weight": 1.0 + }, + { + "name": "monotone_combination", + "weight": 2.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-monotone-d3-t0047/tests/test.sh b/tasks/inequalities/inequalities-monotone-d3-t0047/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0047/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-monotone-d3-t0059/environment/Dockerfile b/tasks/inequalities/inequalities-monotone-d3-t0059/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0059/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-monotone-d3-t0059/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-monotone-d3-t0059/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..054b2165d050226b6de478342b6ff8ff561a692b --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0059/environment/workdir/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The logarithm of one plus a square is increasing on the positive reals. -/ +theorem log_one_add_sq_mono (x y : ℝ) (hx : 0 < x) (h : x ≤ y) : + 0 ≤ Real.log (1 + y ^ 2) - Real.log (1 + x ^ 2) := by + sorry + +/-- The combination is non-decreasing on the positive reals. -/ +theorem monotone_combination (x y : ℝ) (hx : 0 < x) (h : x ≤ y) : + 0 ≤ (4 * Real.arctan y + 2 * Real.log y + 3 * Real.sinh y + y ^ 2 + 3 * Real.log (1 + y ^ 2)) - (4 * Real.arctan x + 2 * Real.log x + 3 * Real.sinh x + x ^ 2 + 3 * Real.log (1 + x ^ 2)) := by + sorry diff --git a/tasks/inequalities/inequalities-monotone-d3-t0059/instruction.md b/tasks/inequalities/inequalities-monotone-d3-t0059/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c870c67c94e01a15a1870e9f8184603856299d28 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0059/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that \(0 \le \ln(1 + y^2) - \ln(1 + x^2)\) for real numbers \(0 < x \le y\). Then prove that for such \(x, y\), \[0 \le \left(4\,\arctan y + 2\,\ln y + 3\,\sinh y + y^2 + 3\,\ln(1 + y^2)\right) - \left(4\,\arctan x + 2\,\ln x + 3\,\sinh x + x^2 + 3\,\ln(1 + x^2)\right).\] + +## What to do + +`Solution.lean` in the working directory states 2 theorems in Lean 4 with Mathlib, with `sorry` in place of each proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is the share of the 2 theorems that are proved. If the file does not compile the reward is 0, so leave `sorry` on a theorem you cannot finish rather than a broken proof. diff --git a/tasks/inequalities/inequalities-monotone-d3-t0059/solution/Solution.lean b/tasks/inequalities/inequalities-monotone-d3-t0059/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..3766f9c5de1f2e24c53502c3d57ef002305a848c --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0059/solution/Solution.lean @@ -0,0 +1,20 @@ +import Mathlib + +/-- The logarithm of one plus a square is increasing on the positive reals. -/ +theorem log_one_add_sq_mono (x y : ℝ) (hx : 0 < x) (h : x ≤ y) : + 0 ≤ Real.log (1 + y ^ 2) - Real.log (1 + x ^ 2) := by + have hy : 0 < y := lt_of_lt_of_le hx h + have h3 : Real.log (1 + x ^ 2) ≤ Real.log (1 + y ^ 2) := by + apply Real.log_le_log (by positivity) + nlinarith [mul_pos hx hy, mul_nonneg (sub_nonneg.2 h) hx.le] + linarith + +/-- The combination is non-decreasing on the positive reals. -/ +theorem monotone_combination (x y : ℝ) (hx : 0 < x) (h : x ≤ y) : + 0 ≤ (4 * Real.arctan y + 2 * Real.log y + 3 * Real.sinh y + y ^ 2 + 3 * Real.log (1 + y ^ 2)) - (4 * Real.arctan x + 2 * Real.log x + 3 * Real.sinh x + x ^ 2 + 3 * Real.log (1 + x ^ 2)) := by + have h1 : Real.arctan x ≤ Real.arctan y := Real.arctan_strictMono.monotone h + have h2 : Real.log x ≤ Real.log y := Real.log_le_log hx h + have h3 : Real.sinh x ≤ Real.sinh y := Real.sinh_strictMono.monotone h + have h4 : x ^ 2 ≤ y ^ 2 := pow_le_pow_left₀ hx.le h 2 + have h5 := log_one_add_sq_mono x y hx h + linarith diff --git a/tasks/inequalities/inequalities-monotone-d3-t0059/solution/solve.sh b/tasks/inequalities/inequalities-monotone-d3-t0059/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0059/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-monotone-d3-t0059/task.toml b/tasks/inequalities/inequalities-monotone-d3-t0059/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6256f1f6efb032ad589fc59abdd9977b60996a1f --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0059/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "inequalities" +tags = ["inequalities", "monotone", "msc-26", "train", "lean4"] +msc = "26" +family = "monotone" +split = "train" +seed = 59 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-monotone-d3-t0059/tests/Verify.lean b/tasks/inequalities/inequalities-monotone-d3-t0059/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0059/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-monotone-d3-t0059/tests/grade.py b/tasks/inequalities/inequalities-monotone-d3-t0059/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0059/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-monotone-d3-t0059/tests/spec.json b/tasks/inequalities/inequalities-monotone-d3-t0059/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..479784daae620a7a185da97578782f310929d277 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0059/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\n/-- The logarithm of one plus a square is increasing on the positive reals. -/\ntheorem log_one_add_sq_mono (x y : ℝ) (hx : 0 < x) (h : x ≤ y) :\n 0 ≤ Real.log (1 + y ^ 2) - Real.log (1 + x ^ 2) := by\n sorry\n\n/-- The combination is non-decreasing on the positive reals. -/\ntheorem monotone_combination (x y : ℝ) (hx : 0 < x) (h : x ≤ y) :\n 0 ≤ (4 * Real.arctan y + 2 * Real.log y + 3 * Real.sinh y + y ^ 2 + 3 * Real.log (1 + y ^ 2)) - (4 * Real.arctan x + 2 * Real.log x + 3 * Real.sinh x + x ^ 2 + 3 * Real.log (1 + x ^ 2)) := by\n sorry\n", + "targets": [ + { + "name": "log_one_add_sq_mono", + "weight": 1.0 + }, + { + "name": "monotone_combination", + "weight": 2.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-monotone-d3-t0059/tests/test.sh b/tasks/inequalities/inequalities-monotone-d3-t0059/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0059/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-monotone-d3-t0071/environment/Dockerfile b/tasks/inequalities/inequalities-monotone-d3-t0071/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0071/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-monotone-d3-t0071/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-monotone-d3-t0071/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..b5ea63b6b9679ee5e247d171449642446275caaf --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0071/environment/workdir/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The logarithm of one plus a square is increasing on the positive reals. -/ +theorem log_one_add_sq_mono (x y : ℝ) (hx : 0 < x) (h : x ≤ y) : + 0 ≤ Real.log (1 + y ^ 2) - Real.log (1 + x ^ 2) := by + sorry + +/-- The combination is non-decreasing on the positive reals. -/ +theorem monotone_combination (x y : ℝ) (hx : 0 < x) (h : x ≤ y) : + 0 ≤ (Real.sqrt y + 4 * Real.exp y + 5 * Real.log y + Real.log (1 + y ^ 2)) - (Real.sqrt x + 4 * Real.exp x + 5 * Real.log x + Real.log (1 + x ^ 2)) := by + sorry diff --git a/tasks/inequalities/inequalities-monotone-d3-t0071/instruction.md b/tasks/inequalities/inequalities-monotone-d3-t0071/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..04ad3d504aa885d15b114cf7b7963675936e0fc7 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0071/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that \(0 \le \ln(1 + y^2) - \ln(1 + x^2)\) for real numbers \(0 < x \le y\). Then prove that for such \(x, y\), \[0 \le \left(\sqrt{y} + 4\,e^{y} + 5\,\ln y + \ln(1 + y^2)\right) - \left(\sqrt{x} + 4\,e^{x} + 5\,\ln x + \ln(1 + x^2)\right).\] + +## What to do + +`Solution.lean` in the working directory states 2 theorems in Lean 4 with Mathlib, with `sorry` in place of each proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is the share of the 2 theorems that are proved. If the file does not compile the reward is 0, so leave `sorry` on a theorem you cannot finish rather than a broken proof. diff --git a/tasks/inequalities/inequalities-monotone-d3-t0071/solution/Solution.lean b/tasks/inequalities/inequalities-monotone-d3-t0071/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..23aa4ae6d7a2fef711a039fae2ec202c56bd55a2 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0071/solution/Solution.lean @@ -0,0 +1,19 @@ +import Mathlib + +/-- The logarithm of one plus a square is increasing on the positive reals. -/ +theorem log_one_add_sq_mono (x y : ℝ) (hx : 0 < x) (h : x ≤ y) : + 0 ≤ Real.log (1 + y ^ 2) - Real.log (1 + x ^ 2) := by + have hy : 0 < y := lt_of_lt_of_le hx h + have h3 : Real.log (1 + x ^ 2) ≤ Real.log (1 + y ^ 2) := by + apply Real.log_le_log (by positivity) + nlinarith [mul_pos hx hy, mul_nonneg (sub_nonneg.2 h) hx.le] + linarith + +/-- The combination is non-decreasing on the positive reals. -/ +theorem monotone_combination (x y : ℝ) (hx : 0 < x) (h : x ≤ y) : + 0 ≤ (Real.sqrt y + 4 * Real.exp y + 5 * Real.log y + Real.log (1 + y ^ 2)) - (Real.sqrt x + 4 * Real.exp x + 5 * Real.log x + Real.log (1 + x ^ 2)) := by + have h1 : Real.sqrt x ≤ Real.sqrt y := Real.sqrt_le_sqrt h + have h2 : Real.exp x ≤ Real.exp y := Real.exp_le_exp.2 h + have h3 : Real.log x ≤ Real.log y := Real.log_le_log hx h + have h4 := log_one_add_sq_mono x y hx h + linarith diff --git a/tasks/inequalities/inequalities-monotone-d3-t0071/solution/solve.sh b/tasks/inequalities/inequalities-monotone-d3-t0071/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0071/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-monotone-d3-t0071/task.toml b/tasks/inequalities/inequalities-monotone-d3-t0071/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..aabe46dadb467a50193232b219a8cc7350570e2c --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0071/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "inequalities" +tags = ["inequalities", "monotone", "msc-26", "train", "lean4"] +msc = "26" +family = "monotone" +split = "train" +seed = 71 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-monotone-d3-t0071/tests/Verify.lean b/tasks/inequalities/inequalities-monotone-d3-t0071/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0071/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-monotone-d3-t0071/tests/grade.py b/tasks/inequalities/inequalities-monotone-d3-t0071/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0071/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-monotone-d3-t0071/tests/spec.json b/tasks/inequalities/inequalities-monotone-d3-t0071/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..6c60e3b5912f9e203db97901bfc55cc909185dc0 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0071/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\n/-- The logarithm of one plus a square is increasing on the positive reals. -/\ntheorem log_one_add_sq_mono (x y : ℝ) (hx : 0 < x) (h : x ≤ y) :\n 0 ≤ Real.log (1 + y ^ 2) - Real.log (1 + x ^ 2) := by\n sorry\n\n/-- The combination is non-decreasing on the positive reals. -/\ntheorem monotone_combination (x y : ℝ) (hx : 0 < x) (h : x ≤ y) :\n 0 ≤ (Real.sqrt y + 4 * Real.exp y + 5 * Real.log y + Real.log (1 + y ^ 2)) - (Real.sqrt x + 4 * Real.exp x + 5 * Real.log x + Real.log (1 + x ^ 2)) := by\n sorry\n", + "targets": [ + { + "name": "log_one_add_sq_mono", + "weight": 1.0 + }, + { + "name": "monotone_combination", + "weight": 2.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-monotone-d3-t0071/tests/test.sh b/tasks/inequalities/inequalities-monotone-d3-t0071/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0071/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/inequalities/inequalities-monotone-d3-t0083/environment/Dockerfile b/tasks/inequalities/inequalities-monotone-d3-t0083/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0083/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/inequalities/inequalities-monotone-d3-t0083/environment/workdir/Solution.lean b/tasks/inequalities/inequalities-monotone-d3-t0083/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..3158b49a8977a8d09f6cf2ed9570e02794921e0f --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0083/environment/workdir/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The logarithm of one plus a square is increasing on the positive reals. -/ +theorem log_one_add_sq_mono (x y : ℝ) (hx : 0 < x) (h : x ≤ y) : + 0 ≤ Real.log (1 + y ^ 2) - Real.log (1 + x ^ 2) := by + sorry + +/-- The combination is non-decreasing on the positive reals. -/ +theorem monotone_combination (x y : ℝ) (hx : 0 < x) (h : x ≤ y) : + 0 ≤ (3 * Real.sqrt y + 4 * Real.arctan y + Real.log (1 + y ^ 2)) - (3 * Real.sqrt x + 4 * Real.arctan x + Real.log (1 + x ^ 2)) := by + sorry diff --git a/tasks/inequalities/inequalities-monotone-d3-t0083/instruction.md b/tasks/inequalities/inequalities-monotone-d3-t0083/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f90bde7ed8180e0b0a799830bfc42e6d28d2c01f --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0083/instruction.md @@ -0,0 +1,12 @@ +# Prove an inequality over the reals + +Prove that \(0 \le \ln(1 + y^2) - \ln(1 + x^2)\) for real numbers \(0 < x \le y\). Then prove that for such \(x, y\), \[0 \le \left(3\,\sqrt{y} + 4\,\arctan y + \ln(1 + y^2)\right) - \left(3\,\sqrt{x} + 4\,\arctan x + \ln(1 + x^2)\right).\] + +## What to do + +`Solution.lean` in the working directory states 2 theorems in Lean 4 with Mathlib, with `sorry` in place of each proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is the share of the 2 theorems that are proved. If the file does not compile the reward is 0, so leave `sorry` on a theorem you cannot finish rather than a broken proof. diff --git a/tasks/inequalities/inequalities-monotone-d3-t0083/solution/Solution.lean b/tasks/inequalities/inequalities-monotone-d3-t0083/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..e9c445e658f5b0add6a6e875c1af7c68bcdae7bf --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0083/solution/Solution.lean @@ -0,0 +1,18 @@ +import Mathlib + +/-- The logarithm of one plus a square is increasing on the positive reals. -/ +theorem log_one_add_sq_mono (x y : ℝ) (hx : 0 < x) (h : x ≤ y) : + 0 ≤ Real.log (1 + y ^ 2) - Real.log (1 + x ^ 2) := by + have hy : 0 < y := lt_of_lt_of_le hx h + have h3 : Real.log (1 + x ^ 2) ≤ Real.log (1 + y ^ 2) := by + apply Real.log_le_log (by positivity) + nlinarith [mul_pos hx hy, mul_nonneg (sub_nonneg.2 h) hx.le] + linarith + +/-- The combination is non-decreasing on the positive reals. -/ +theorem monotone_combination (x y : ℝ) (hx : 0 < x) (h : x ≤ y) : + 0 ≤ (3 * Real.sqrt y + 4 * Real.arctan y + Real.log (1 + y ^ 2)) - (3 * Real.sqrt x + 4 * Real.arctan x + Real.log (1 + x ^ 2)) := by + have h1 : Real.sqrt x ≤ Real.sqrt y := Real.sqrt_le_sqrt h + have h2 : Real.arctan x ≤ Real.arctan y := Real.arctan_strictMono.monotone h + have h3 := log_one_add_sq_mono x y hx h + linarith diff --git a/tasks/inequalities/inequalities-monotone-d3-t0083/solution/solve.sh b/tasks/inequalities/inequalities-monotone-d3-t0083/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0083/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/inequalities/inequalities-monotone-d3-t0083/task.toml b/tasks/inequalities/inequalities-monotone-d3-t0083/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..46ec0dbcd05287a3027e0d333aadf48a4fdcbba6 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0083/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "inequalities" +tags = ["inequalities", "monotone", "msc-26", "train", "lean4"] +msc = "26" +family = "monotone" +split = "train" +seed = 83 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/inequalities/inequalities-monotone-d3-t0083/tests/Verify.lean b/tasks/inequalities/inequalities-monotone-d3-t0083/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0083/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/inequalities/inequalities-monotone-d3-t0083/tests/grade.py b/tasks/inequalities/inequalities-monotone-d3-t0083/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0083/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/inequalities/inequalities-monotone-d3-t0083/tests/spec.json b/tasks/inequalities/inequalities-monotone-d3-t0083/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..2ccd8ce7578cca32f73f17bf19c8d5b61e9674f8 --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0083/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\n/-- The logarithm of one plus a square is increasing on the positive reals. -/\ntheorem log_one_add_sq_mono (x y : ℝ) (hx : 0 < x) (h : x ≤ y) :\n 0 ≤ Real.log (1 + y ^ 2) - Real.log (1 + x ^ 2) := by\n sorry\n\n/-- The combination is non-decreasing on the positive reals. -/\ntheorem monotone_combination (x y : ℝ) (hx : 0 < x) (h : x ≤ y) :\n 0 ≤ (3 * Real.sqrt y + 4 * Real.arctan y + Real.log (1 + y ^ 2)) - (3 * Real.sqrt x + 4 * Real.arctan x + Real.log (1 + x ^ 2)) := by\n sorry\n", + "targets": [ + { + "name": "log_one_add_sq_mono", + "weight": 1.0 + }, + { + "name": "monotone_combination", + "weight": 2.0 + } + ] +} diff --git a/tasks/inequalities/inequalities-monotone-d3-t0083/tests/test.sh b/tasks/inequalities/inequalities-monotone-d3-t0083/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/inequalities/inequalities-monotone-d3-t0083/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-continuity-d1-t0072/environment/Dockerfile b/tasks/real-analysis/real-analysis-continuity-d1-t0072/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d1-t0072/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-continuity-d1-t0072/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-continuity-d1-t0072/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..acfe72f0163e846477960078293feb93ff502521 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d1-t0072/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Epsilon-delta continuity of a linear function at a point. -/ +theorem continuous_at : + ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (0 : ℝ)| < δ → |((-3 : ℝ) * x + (2 : ℝ)) - ((-3 : ℝ) * (0 : ℝ) + (2 : ℝ))| < ε := by + sorry diff --git a/tasks/real-analysis/real-analysis-continuity-d1-t0072/instruction.md b/tasks/real-analysis/real-analysis-continuity-d1-t0072/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7b7778906e63826de04339464c944edcab873fce --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d1-t0072/instruction.md @@ -0,0 +1,12 @@ +# Prove continuity from the epsilon-delta definition + +Prove, from the epsilon-delta definition, that \(f(x) = -3x + 2\) is continuous at \(x_0 = 0\): for every \(\varepsilon > 0\) there is \(\delta > 0\) such that \(|f(x) - f(x_0)| < \varepsilon\) whenever \(|x - x_0| < \delta\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-continuity-d1-t0072/solution/Solution.lean b/tasks/real-analysis/real-analysis-continuity-d1-t0072/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..ac2cc324dff734a2b4656c65cd1f3aab9c211bfb --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d1-t0072/solution/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- Epsilon-delta continuity of a linear function at a point. -/ +theorem continuous_at : + ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (0 : ℝ)| < δ → |((-3 : ℝ) * x + (2 : ℝ)) - ((-3 : ℝ) * (0 : ℝ) + (2 : ℝ))| < ε := by + intro ε hε + refine ⟨ε / (3 : ℝ), by positivity, fun x hx => ?_⟩ + have e : ((-3 : ℝ) * x + (2 : ℝ)) - ((-3 : ℝ) * (0 : ℝ) + (2 : ℝ)) = (-3 : ℝ) * (x - (0 : ℝ)) := by ring + rw [e, abs_mul, show |(-3 : ℝ)| = (3 : ℝ) by norm_num] + rw [lt_div_iff₀ (by norm_num)] at hx + linarith diff --git a/tasks/real-analysis/real-analysis-continuity-d1-t0072/solution/solve.sh b/tasks/real-analysis/real-analysis-continuity-d1-t0072/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d1-t0072/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-continuity-d1-t0072/task.toml b/tasks/real-analysis/real-analysis-continuity-d1-t0072/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a4ed2b44f53c7968f6c7f0047ca2e04f3d0b9cf0 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d1-t0072/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "real-analysis" +tags = ["real-analysis", "continuity", "msc-26", "train", "lean4"] +msc = "26" +family = "continuity" +split = "train" +seed = 72 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-continuity-d1-t0072/tests/Verify.lean b/tasks/real-analysis/real-analysis-continuity-d1-t0072/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d1-t0072/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-continuity-d1-t0072/tests/grade.py b/tasks/real-analysis/real-analysis-continuity-d1-t0072/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d1-t0072/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-continuity-d1-t0072/tests/spec.json b/tasks/real-analysis/real-analysis-continuity-d1-t0072/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..539b7c8c8eaa4a57fd1818f44b33ed6799b5bf92 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d1-t0072/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- Epsilon-delta continuity of a linear function at a point. -/\ntheorem continuous_at :\n ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (0 : ℝ)| < δ → |((-3 : ℝ) * x + (2 : ℝ)) - ((-3 : ℝ) * (0 : ℝ) + (2 : ℝ))| < ε := by\n sorry\n", + "targets": [ + { + "name": "continuous_at", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-continuity-d1-t0072/tests/test.sh b/tasks/real-analysis/real-analysis-continuity-d1-t0072/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d1-t0072/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-continuity-d2-e0004/environment/Dockerfile b/tasks/real-analysis/real-analysis-continuity-d2-e0004/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-e0004/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-continuity-d2-e0004/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-continuity-d2-e0004/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..aa85906d4a0a61c6ec698082c129cac6cef29170 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-e0004/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Epsilon-delta continuity of a quadratic function at a point. -/ +theorem continuous_at : + ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (-4 : ℝ)| < δ → |((1 : ℝ) * x ^ 2 + (5 : ℝ)) - ((1 : ℝ) * (-4 : ℝ) ^ 2 + (5 : ℝ))| < ε := by + sorry diff --git a/tasks/real-analysis/real-analysis-continuity-d2-e0004/instruction.md b/tasks/real-analysis/real-analysis-continuity-d2-e0004/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0a6439bfce5c3b930fe5e26cb1aafdb3557096e9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-e0004/instruction.md @@ -0,0 +1,12 @@ +# Prove continuity from the epsilon-delta definition + +Prove, from the epsilon-delta definition, that \(f(x) = x^2 + 5\) is continuous at \(x_0 = -4\): for every \(\varepsilon > 0\) there is \(\delta > 0\) such that \(|f(x) - f(x_0)| < \varepsilon\) whenever \(|x - x_0| < \delta\). Do not use any continuity lemma from the library. + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-continuity-d2-e0004/solution/Solution.lean b/tasks/real-analysis/real-analysis-continuity-d2-e0004/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..1b5ae544931e6d6225dade148ded0327bff75742 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-e0004/solution/Solution.lean @@ -0,0 +1,17 @@ +import Mathlib + +/-- Epsilon-delta continuity of a quadratic function at a point. -/ +theorem continuous_at : + ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (-4 : ℝ)| < δ → |((1 : ℝ) * x ^ 2 + (5 : ℝ)) - ((1 : ℝ) * (-4 : ℝ) ^ 2 + (5 : ℝ))| < ε := by + intro ε hε + refine ⟨min 1 (ε / (9 : ℝ)), lt_min one_pos (by positivity), fun x hx => ?_⟩ + have h1 : |x - (-4 : ℝ)| < 1 := lt_of_lt_of_le hx (min_le_left _ _) + have h2 : |x - (-4 : ℝ)| < ε / (9 : ℝ) := lt_of_lt_of_le hx (min_le_right _ _) + have h3 : |x + (-4 : ℝ)| < 2 * (4 : ℝ) + 1 := by + rw [abs_lt] at h1 ⊢ + constructor <;> norm_num <;> linarith [h1.1, h1.2] + have e : ((1 : ℝ) * x ^ 2 + (5 : ℝ)) - ((1 : ℝ) * (-4 : ℝ) ^ 2 + (5 : ℝ)) = (1 : ℝ) * ((x - (-4 : ℝ)) * (x + (-4 : ℝ))) := by ring + rw [e, abs_mul, abs_mul, show |(1 : ℝ)| = (1 : ℝ) by norm_num] + have h4 : |x - (-4 : ℝ)| * (9 : ℝ) < ε := by rwa [lt_div_iff₀ (by norm_num)] at h2 + have h5 := mul_le_mul_of_nonneg_left h3.le (mul_nonneg (by norm_num : (0 : ℝ) ≤ (1 : ℝ)) (abs_nonneg (x - (-4 : ℝ)))) + nlinarith [abs_nonneg (x - (-4 : ℝ)), abs_nonneg (x + (-4 : ℝ))] diff --git a/tasks/real-analysis/real-analysis-continuity-d2-e0004/solution/solve.sh b/tasks/real-analysis/real-analysis-continuity-d2-e0004/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-e0004/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-continuity-d2-e0004/task.toml b/tasks/real-analysis/real-analysis-continuity-d2-e0004/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3e0fa131be01c808b3f2e740c0414b0d1fbf4b46 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-e0004/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "real-analysis" +tags = ["real-analysis", "continuity", "msc-26", "eval", "lean4"] +msc = "26" +family = "continuity" +split = "eval" +seed = 10004 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-continuity-d2-e0004/tests/Verify.lean b/tasks/real-analysis/real-analysis-continuity-d2-e0004/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-e0004/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-continuity-d2-e0004/tests/grade.py b/tasks/real-analysis/real-analysis-continuity-d2-e0004/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-e0004/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-continuity-d2-e0004/tests/spec.json b/tasks/real-analysis/real-analysis-continuity-d2-e0004/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..65cd55967ce62deeaf0b3f7772c1f891ae12d41b --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-e0004/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- Epsilon-delta continuity of a quadratic function at a point. -/\ntheorem continuous_at :\n ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (-4 : ℝ)| < δ → |((1 : ℝ) * x ^ 2 + (5 : ℝ)) - ((1 : ℝ) * (-4 : ℝ) ^ 2 + (5 : ℝ))| < ε := by\n sorry\n", + "targets": [ + { + "name": "continuous_at", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-continuity-d2-e0004/tests/test.sh b/tasks/real-analysis/real-analysis-continuity-d2-e0004/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-e0004/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0004/environment/Dockerfile b/tasks/real-analysis/real-analysis-continuity-d2-t0004/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0004/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0004/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-continuity-d2-t0004/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..d9bacaaefafbe7c6b474b80e67e53ff0184f4b97 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0004/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Epsilon-delta continuity of a quadratic function at a point. -/ +theorem continuous_at : + ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (2 : ℝ)| < δ → |((2 : ℝ) * x ^ 2 + (-2 : ℝ)) - ((2 : ℝ) * (2 : ℝ) ^ 2 + (-2 : ℝ))| < ε := by + sorry diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0004/instruction.md b/tasks/real-analysis/real-analysis-continuity-d2-t0004/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5bd17dbd407f26f87ed6ad6437028f8c6d1eabf0 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0004/instruction.md @@ -0,0 +1,12 @@ +# Prove continuity from the epsilon-delta definition + +Prove, from the epsilon-delta definition, that \(f(x) = 2x^2 - 2\) is continuous at \(x_0 = 2\): for every \(\varepsilon > 0\) there is \(\delta > 0\) such that \(|f(x) - f(x_0)| < \varepsilon\) whenever \(|x - x_0| < \delta\). Do not use any continuity lemma from the library. + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0004/solution/Solution.lean b/tasks/real-analysis/real-analysis-continuity-d2-t0004/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..80c5f65ccd68fc4dad81dd5fa8c3bbe9d8d4ad36 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0004/solution/Solution.lean @@ -0,0 +1,17 @@ +import Mathlib + +/-- Epsilon-delta continuity of a quadratic function at a point. -/ +theorem continuous_at : + ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (2 : ℝ)| < δ → |((2 : ℝ) * x ^ 2 + (-2 : ℝ)) - ((2 : ℝ) * (2 : ℝ) ^ 2 + (-2 : ℝ))| < ε := by + intro ε hε + refine ⟨min 1 (ε / (10 : ℝ)), lt_min one_pos (by positivity), fun x hx => ?_⟩ + have h1 : |x - (2 : ℝ)| < 1 := lt_of_lt_of_le hx (min_le_left _ _) + have h2 : |x - (2 : ℝ)| < ε / (10 : ℝ) := lt_of_lt_of_le hx (min_le_right _ _) + have h3 : |x + (2 : ℝ)| < 2 * (2 : ℝ) + 1 := by + rw [abs_lt] at h1 ⊢ + constructor <;> norm_num <;> linarith [h1.1, h1.2] + have e : ((2 : ℝ) * x ^ 2 + (-2 : ℝ)) - ((2 : ℝ) * (2 : ℝ) ^ 2 + (-2 : ℝ)) = (2 : ℝ) * ((x - (2 : ℝ)) * (x + (2 : ℝ))) := by ring + rw [e, abs_mul, abs_mul, show |(2 : ℝ)| = (2 : ℝ) by norm_num] + have h4 : |x - (2 : ℝ)| * (10 : ℝ) < ε := by rwa [lt_div_iff₀ (by norm_num)] at h2 + have h5 := mul_le_mul_of_nonneg_left h3.le (mul_nonneg (by norm_num : (0 : ℝ) ≤ (2 : ℝ)) (abs_nonneg (x - (2 : ℝ)))) + nlinarith [abs_nonneg (x - (2 : ℝ)), abs_nonneg (x + (2 : ℝ))] diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0004/solution/solve.sh b/tasks/real-analysis/real-analysis-continuity-d2-t0004/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0004/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0004/task.toml b/tasks/real-analysis/real-analysis-continuity-d2-t0004/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..58cf5be0c6aa8827057ba00df967c206bef24186 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0004/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "real-analysis" +tags = ["real-analysis", "continuity", "msc-26", "train", "lean4"] +msc = "26" +family = "continuity" +split = "train" +seed = 4 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0004/tests/Verify.lean b/tasks/real-analysis/real-analysis-continuity-d2-t0004/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0004/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0004/tests/grade.py b/tasks/real-analysis/real-analysis-continuity-d2-t0004/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0004/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0004/tests/spec.json b/tasks/real-analysis/real-analysis-continuity-d2-t0004/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..db27571544c0db67b7d84ab17abf0df99fba4926 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0004/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- Epsilon-delta continuity of a quadratic function at a point. -/\ntheorem continuous_at :\n ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (2 : ℝ)| < δ → |((2 : ℝ) * x ^ 2 + (-2 : ℝ)) - ((2 : ℝ) * (2 : ℝ) ^ 2 + (-2 : ℝ))| < ε := by\n sorry\n", + "targets": [ + { + "name": "continuous_at", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0004/tests/test.sh b/tasks/real-analysis/real-analysis-continuity-d2-t0004/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0004/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0016/environment/Dockerfile b/tasks/real-analysis/real-analysis-continuity-d2-t0016/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0016/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0016/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-continuity-d2-t0016/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..55c7980e2164aaa6fe03d9f7cee93106bb339835 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0016/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Epsilon-delta continuity of a quadratic function at a point. -/ +theorem continuous_at : + ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (3 : ℝ)| < δ → |((-3 : ℝ) * x ^ 2 + (2 : ℝ)) - ((-3 : ℝ) * (3 : ℝ) ^ 2 + (2 : ℝ))| < ε := by + sorry diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0016/instruction.md b/tasks/real-analysis/real-analysis-continuity-d2-t0016/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f3855887721c403bc6a0924a3ebc4180c2601f05 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0016/instruction.md @@ -0,0 +1,12 @@ +# Prove continuity from the epsilon-delta definition + +Prove, from the epsilon-delta definition, that \(f(x) = -3x^2 + 2\) is continuous at \(x_0 = 3\): for every \(\varepsilon > 0\) there is \(\delta > 0\) such that \(|f(x) - f(x_0)| < \varepsilon\) whenever \(|x - x_0| < \delta\). Do not use any continuity lemma from the library. + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0016/solution/Solution.lean b/tasks/real-analysis/real-analysis-continuity-d2-t0016/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..6d912515bbc942d7693dd15877d27f34d6c35a79 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0016/solution/Solution.lean @@ -0,0 +1,17 @@ +import Mathlib + +/-- Epsilon-delta continuity of a quadratic function at a point. -/ +theorem continuous_at : + ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (3 : ℝ)| < δ → |((-3 : ℝ) * x ^ 2 + (2 : ℝ)) - ((-3 : ℝ) * (3 : ℝ) ^ 2 + (2 : ℝ))| < ε := by + intro ε hε + refine ⟨min 1 (ε / (21 : ℝ)), lt_min one_pos (by positivity), fun x hx => ?_⟩ + have h1 : |x - (3 : ℝ)| < 1 := lt_of_lt_of_le hx (min_le_left _ _) + have h2 : |x - (3 : ℝ)| < ε / (21 : ℝ) := lt_of_lt_of_le hx (min_le_right _ _) + have h3 : |x + (3 : ℝ)| < 2 * (3 : ℝ) + 1 := by + rw [abs_lt] at h1 ⊢ + constructor <;> norm_num <;> linarith [h1.1, h1.2] + have e : ((-3 : ℝ) * x ^ 2 + (2 : ℝ)) - ((-3 : ℝ) * (3 : ℝ) ^ 2 + (2 : ℝ)) = (-3 : ℝ) * ((x - (3 : ℝ)) * (x + (3 : ℝ))) := by ring + rw [e, abs_mul, abs_mul, show |(-3 : ℝ)| = (3 : ℝ) by norm_num] + have h4 : |x - (3 : ℝ)| * (21 : ℝ) < ε := by rwa [lt_div_iff₀ (by norm_num)] at h2 + have h5 := mul_le_mul_of_nonneg_left h3.le (mul_nonneg (by norm_num : (0 : ℝ) ≤ (3 : ℝ)) (abs_nonneg (x - (3 : ℝ)))) + nlinarith [abs_nonneg (x - (3 : ℝ)), abs_nonneg (x + (3 : ℝ))] diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0016/solution/solve.sh b/tasks/real-analysis/real-analysis-continuity-d2-t0016/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0016/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0016/task.toml b/tasks/real-analysis/real-analysis-continuity-d2-t0016/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f10ce863fddcd80d3545b094974895aade311fa0 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0016/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "real-analysis" +tags = ["real-analysis", "continuity", "msc-26", "train", "lean4"] +msc = "26" +family = "continuity" +split = "train" +seed = 16 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0016/tests/Verify.lean b/tasks/real-analysis/real-analysis-continuity-d2-t0016/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0016/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0016/tests/grade.py b/tasks/real-analysis/real-analysis-continuity-d2-t0016/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0016/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0016/tests/spec.json b/tasks/real-analysis/real-analysis-continuity-d2-t0016/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..dcc597f8ef737ccb9670cfbcf7bcfc7c4c6bf80e --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0016/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- Epsilon-delta continuity of a quadratic function at a point. -/\ntheorem continuous_at :\n ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (3 : ℝ)| < δ → |((-3 : ℝ) * x ^ 2 + (2 : ℝ)) - ((-3 : ℝ) * (3 : ℝ) ^ 2 + (2 : ℝ))| < ε := by\n sorry\n", + "targets": [ + { + "name": "continuous_at", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0016/tests/test.sh b/tasks/real-analysis/real-analysis-continuity-d2-t0016/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0016/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0028/environment/Dockerfile b/tasks/real-analysis/real-analysis-continuity-d2-t0028/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0028/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0028/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-continuity-d2-t0028/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..b5cfb51a70243ba98e9e3e4cefd825ffe20a5939 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0028/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Epsilon-delta continuity of a quadratic function at a point. -/ +theorem continuous_at : + ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (2 : ℝ)| < δ → |((6 : ℝ) * x ^ 2 + (4 : ℝ)) - ((6 : ℝ) * (2 : ℝ) ^ 2 + (4 : ℝ))| < ε := by + sorry diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0028/instruction.md b/tasks/real-analysis/real-analysis-continuity-d2-t0028/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..50208a753207832bb6f8361992893a31b7acc8c3 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0028/instruction.md @@ -0,0 +1,12 @@ +# Prove continuity from the epsilon-delta definition + +Prove, from the epsilon-delta definition, that \(f(x) = 6x^2 + 4\) is continuous at \(x_0 = 2\): for every \(\varepsilon > 0\) there is \(\delta > 0\) such that \(|f(x) - f(x_0)| < \varepsilon\) whenever \(|x - x_0| < \delta\). Do not use any continuity lemma from the library. + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0028/solution/Solution.lean b/tasks/real-analysis/real-analysis-continuity-d2-t0028/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..9f964241e1af07e0aa92eb7951077aa277556fca --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0028/solution/Solution.lean @@ -0,0 +1,17 @@ +import Mathlib + +/-- Epsilon-delta continuity of a quadratic function at a point. -/ +theorem continuous_at : + ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (2 : ℝ)| < δ → |((6 : ℝ) * x ^ 2 + (4 : ℝ)) - ((6 : ℝ) * (2 : ℝ) ^ 2 + (4 : ℝ))| < ε := by + intro ε hε + refine ⟨min 1 (ε / (30 : ℝ)), lt_min one_pos (by positivity), fun x hx => ?_⟩ + have h1 : |x - (2 : ℝ)| < 1 := lt_of_lt_of_le hx (min_le_left _ _) + have h2 : |x - (2 : ℝ)| < ε / (30 : ℝ) := lt_of_lt_of_le hx (min_le_right _ _) + have h3 : |x + (2 : ℝ)| < 2 * (2 : ℝ) + 1 := by + rw [abs_lt] at h1 ⊢ + constructor <;> norm_num <;> linarith [h1.1, h1.2] + have e : ((6 : ℝ) * x ^ 2 + (4 : ℝ)) - ((6 : ℝ) * (2 : ℝ) ^ 2 + (4 : ℝ)) = (6 : ℝ) * ((x - (2 : ℝ)) * (x + (2 : ℝ))) := by ring + rw [e, abs_mul, abs_mul, show |(6 : ℝ)| = (6 : ℝ) by norm_num] + have h4 : |x - (2 : ℝ)| * (30 : ℝ) < ε := by rwa [lt_div_iff₀ (by norm_num)] at h2 + have h5 := mul_le_mul_of_nonneg_left h3.le (mul_nonneg (by norm_num : (0 : ℝ) ≤ (6 : ℝ)) (abs_nonneg (x - (2 : ℝ)))) + nlinarith [abs_nonneg (x - (2 : ℝ)), abs_nonneg (x + (2 : ℝ))] diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0028/solution/solve.sh b/tasks/real-analysis/real-analysis-continuity-d2-t0028/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0028/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0028/task.toml b/tasks/real-analysis/real-analysis-continuity-d2-t0028/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..866f145183623fa566a4612485bd48e3ecd925b6 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0028/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "real-analysis" +tags = ["real-analysis", "continuity", "msc-26", "train", "lean4"] +msc = "26" +family = "continuity" +split = "train" +seed = 28 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0028/tests/Verify.lean b/tasks/real-analysis/real-analysis-continuity-d2-t0028/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0028/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0028/tests/grade.py b/tasks/real-analysis/real-analysis-continuity-d2-t0028/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0028/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0028/tests/spec.json b/tasks/real-analysis/real-analysis-continuity-d2-t0028/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..0a757f27095340f4e90d7549477ba52cd16bea9b --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0028/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- Epsilon-delta continuity of a quadratic function at a point. -/\ntheorem continuous_at :\n ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (2 : ℝ)| < δ → |((6 : ℝ) * x ^ 2 + (4 : ℝ)) - ((6 : ℝ) * (2 : ℝ) ^ 2 + (4 : ℝ))| < ε := by\n sorry\n", + "targets": [ + { + "name": "continuous_at", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-continuity-d2-t0028/tests/test.sh b/tasks/real-analysis/real-analysis-continuity-d2-t0028/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d2-t0028/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-continuity-d3-e0020/environment/Dockerfile b/tasks/real-analysis/real-analysis-continuity-d3-e0020/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-e0020/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-continuity-d3-e0020/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-continuity-d3-e0020/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..0dbfa1859f941b496fa149bd2b2b70429fb16c9d --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-e0020/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Epsilon-delta continuity of the reciprocal function at a point. -/ +theorem continuous_at : + ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (5 : ℝ)| < δ → |(3 : ℝ) / x - (3 : ℝ) / (5 : ℝ)| < ε := by + sorry diff --git a/tasks/real-analysis/real-analysis-continuity-d3-e0020/instruction.md b/tasks/real-analysis/real-analysis-continuity-d3-e0020/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bcaec2c74f6b6ea7f5098d1eb330dfadf1be8286 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-e0020/instruction.md @@ -0,0 +1,12 @@ +# Prove continuity from the epsilon-delta definition + +Prove, from the epsilon-delta definition, that \(f(x) = \dfrac{3}{x}\) is continuous at \(x_0 = 5\): for every \(\varepsilon > 0\) there is \(\delta > 0\) such that \(|f(x) - f(x_0)| < \varepsilon\) whenever \(|x - x_0| < \delta\). Here \(x\) ranges over all real numbers (in Lean, division by 0 gives 0, which does not matter for small \(\delta\)). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-continuity-d3-e0020/solution/Solution.lean b/tasks/real-analysis/real-analysis-continuity-d3-e0020/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..4838cb56eb21323d18584b352775afd2e8fcde70 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-e0020/solution/Solution.lean @@ -0,0 +1,21 @@ +import Mathlib + +/-- Epsilon-delta continuity of the reciprocal function at a point. -/ +theorem continuous_at : + ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (5 : ℝ)| < δ → |(3 : ℝ) / x - (3 : ℝ) / (5 : ℝ)| < ε := by + intro ε hε + refine ⟨min ((5 : ℝ) / 2) (ε * (5 : ℝ) ^ 2 / (2 * (3 : ℝ))), lt_min (by norm_num) (by positivity), fun x hx => ?_⟩ + have h1 : |x - (5 : ℝ)| < (5 : ℝ) / 2 := lt_of_lt_of_le hx (min_le_left _ _) + have h2 : |x - (5 : ℝ)| < ε * (5 : ℝ) ^ 2 / (2 * (3 : ℝ)) := lt_of_lt_of_le hx (min_le_right _ _) + have hx0 : (5 : ℝ) / 2 < x := by + have := (abs_lt.mp h1).1 + linarith + have hxpos : (0 : ℝ) < x := by linarith + have e : (3 : ℝ) / x - (3 : ℝ) / (5 : ℝ) = (3 : ℝ) * ((5 : ℝ) - x) / (x * (5 : ℝ)) := by + field_simp + have h3 : (3 : ℝ) * |x - (5 : ℝ)| < ε * (5 : ℝ) ^ 2 / 2 := by + rw [lt_div_iff₀ (by norm_num)] at h2 ⊢ + nlinarith [abs_nonneg (x - (5 : ℝ))] + have h4 : ε * (5 : ℝ) ^ 2 / 2 < ε * (x * (5 : ℝ)) := by nlinarith [mul_pos hε (sub_pos.mpr hx0), mul_pos hε hxpos] + rw [e, abs_div, abs_mul, abs_of_pos (by positivity : (0 : ℝ) < x * (5 : ℝ)), abs_sub_comm, show |(3 : ℝ)| = (3 : ℝ) by norm_num, div_lt_iff₀ (by positivity)] + linarith diff --git a/tasks/real-analysis/real-analysis-continuity-d3-e0020/solution/solve.sh b/tasks/real-analysis/real-analysis-continuity-d3-e0020/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-e0020/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-continuity-d3-e0020/task.toml b/tasks/real-analysis/real-analysis-continuity-d3-e0020/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8a6c70159a9e6c0fc1bafddf506cfa01c6865bbe --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-e0020/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "real-analysis" +tags = ["real-analysis", "continuity", "msc-26", "eval", "lean4"] +msc = "26" +family = "continuity" +split = "eval" +seed = 10020 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-continuity-d3-e0020/tests/Verify.lean b/tasks/real-analysis/real-analysis-continuity-d3-e0020/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-e0020/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-continuity-d3-e0020/tests/grade.py b/tasks/real-analysis/real-analysis-continuity-d3-e0020/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-e0020/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-continuity-d3-e0020/tests/spec.json b/tasks/real-analysis/real-analysis-continuity-d3-e0020/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..67b4ea515fb30a213d87544ed5630cd360678391 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-e0020/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- Epsilon-delta continuity of the reciprocal function at a point. -/\ntheorem continuous_at :\n ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (5 : ℝ)| < δ → |(3 : ℝ) / x - (3 : ℝ) / (5 : ℝ)| < ε := by\n sorry\n", + "targets": [ + { + "name": "continuous_at", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-continuity-d3-e0020/tests/test.sh b/tasks/real-analysis/real-analysis-continuity-d3-e0020/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-e0020/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0020/environment/Dockerfile b/tasks/real-analysis/real-analysis-continuity-d3-t0020/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0020/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0020/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-continuity-d3-t0020/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..3f94f80582d20d99305502b198371adc2f97a12f --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0020/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Epsilon-delta continuity of the reciprocal function at a point. -/ +theorem continuous_at : + ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (4 : ℝ)| < δ → |(6 : ℝ) / x - (6 : ℝ) / (4 : ℝ)| < ε := by + sorry diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0020/instruction.md b/tasks/real-analysis/real-analysis-continuity-d3-t0020/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a263075c24fec80fb11b7af6821ad611b4000568 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0020/instruction.md @@ -0,0 +1,12 @@ +# Prove continuity from the epsilon-delta definition + +Prove, from the epsilon-delta definition, that \(f(x) = \dfrac{6}{x}\) is continuous at \(x_0 = 4\): for every \(\varepsilon > 0\) there is \(\delta > 0\) such that \(|f(x) - f(x_0)| < \varepsilon\) whenever \(|x - x_0| < \delta\). Here \(x\) ranges over all real numbers (in Lean, division by 0 gives 0, which does not matter for small \(\delta\)). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0020/solution/Solution.lean b/tasks/real-analysis/real-analysis-continuity-d3-t0020/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..7a34ef464f67f4c214d601c42187328d1eb6e85e --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0020/solution/Solution.lean @@ -0,0 +1,21 @@ +import Mathlib + +/-- Epsilon-delta continuity of the reciprocal function at a point. -/ +theorem continuous_at : + ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (4 : ℝ)| < δ → |(6 : ℝ) / x - (6 : ℝ) / (4 : ℝ)| < ε := by + intro ε hε + refine ⟨min ((4 : ℝ) / 2) (ε * (4 : ℝ) ^ 2 / (2 * (6 : ℝ))), lt_min (by norm_num) (by positivity), fun x hx => ?_⟩ + have h1 : |x - (4 : ℝ)| < (4 : ℝ) / 2 := lt_of_lt_of_le hx (min_le_left _ _) + have h2 : |x - (4 : ℝ)| < ε * (4 : ℝ) ^ 2 / (2 * (6 : ℝ)) := lt_of_lt_of_le hx (min_le_right _ _) + have hx0 : (4 : ℝ) / 2 < x := by + have := (abs_lt.mp h1).1 + linarith + have hxpos : (0 : ℝ) < x := by linarith + have e : (6 : ℝ) / x - (6 : ℝ) / (4 : ℝ) = (6 : ℝ) * ((4 : ℝ) - x) / (x * (4 : ℝ)) := by + field_simp + have h3 : (6 : ℝ) * |x - (4 : ℝ)| < ε * (4 : ℝ) ^ 2 / 2 := by + rw [lt_div_iff₀ (by norm_num)] at h2 ⊢ + nlinarith [abs_nonneg (x - (4 : ℝ))] + have h4 : ε * (4 : ℝ) ^ 2 / 2 < ε * (x * (4 : ℝ)) := by nlinarith [mul_pos hε (sub_pos.mpr hx0), mul_pos hε hxpos] + rw [e, abs_div, abs_mul, abs_of_pos (by positivity : (0 : ℝ) < x * (4 : ℝ)), abs_sub_comm, show |(6 : ℝ)| = (6 : ℝ) by norm_num, div_lt_iff₀ (by positivity)] + linarith diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0020/solution/solve.sh b/tasks/real-analysis/real-analysis-continuity-d3-t0020/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0020/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0020/task.toml b/tasks/real-analysis/real-analysis-continuity-d3-t0020/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c92acde77783a86748dadf2bc103effcd19ff289 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0020/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "real-analysis" +tags = ["real-analysis", "continuity", "msc-26", "train", "lean4"] +msc = "26" +family = "continuity" +split = "train" +seed = 20 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0020/tests/Verify.lean b/tasks/real-analysis/real-analysis-continuity-d3-t0020/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0020/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0020/tests/grade.py b/tasks/real-analysis/real-analysis-continuity-d3-t0020/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0020/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0020/tests/spec.json b/tasks/real-analysis/real-analysis-continuity-d3-t0020/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..0b3b7f6c14053abe23b75ba052f13ff5425d25ec --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0020/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- Epsilon-delta continuity of the reciprocal function at a point. -/\ntheorem continuous_at :\n ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (4 : ℝ)| < δ → |(6 : ℝ) / x - (6 : ℝ) / (4 : ℝ)| < ε := by\n sorry\n", + "targets": [ + { + "name": "continuous_at", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0020/tests/test.sh b/tasks/real-analysis/real-analysis-continuity-d3-t0020/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0020/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0044/environment/Dockerfile b/tasks/real-analysis/real-analysis-continuity-d3-t0044/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0044/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0044/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-continuity-d3-t0044/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..0dbfa1859f941b496fa149bd2b2b70429fb16c9d --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0044/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Epsilon-delta continuity of the reciprocal function at a point. -/ +theorem continuous_at : + ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (5 : ℝ)| < δ → |(3 : ℝ) / x - (3 : ℝ) / (5 : ℝ)| < ε := by + sorry diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0044/instruction.md b/tasks/real-analysis/real-analysis-continuity-d3-t0044/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bcaec2c74f6b6ea7f5098d1eb330dfadf1be8286 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0044/instruction.md @@ -0,0 +1,12 @@ +# Prove continuity from the epsilon-delta definition + +Prove, from the epsilon-delta definition, that \(f(x) = \dfrac{3}{x}\) is continuous at \(x_0 = 5\): for every \(\varepsilon > 0\) there is \(\delta > 0\) such that \(|f(x) - f(x_0)| < \varepsilon\) whenever \(|x - x_0| < \delta\). Here \(x\) ranges over all real numbers (in Lean, division by 0 gives 0, which does not matter for small \(\delta\)). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0044/solution/Solution.lean b/tasks/real-analysis/real-analysis-continuity-d3-t0044/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..4838cb56eb21323d18584b352775afd2e8fcde70 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0044/solution/Solution.lean @@ -0,0 +1,21 @@ +import Mathlib + +/-- Epsilon-delta continuity of the reciprocal function at a point. -/ +theorem continuous_at : + ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (5 : ℝ)| < δ → |(3 : ℝ) / x - (3 : ℝ) / (5 : ℝ)| < ε := by + intro ε hε + refine ⟨min ((5 : ℝ) / 2) (ε * (5 : ℝ) ^ 2 / (2 * (3 : ℝ))), lt_min (by norm_num) (by positivity), fun x hx => ?_⟩ + have h1 : |x - (5 : ℝ)| < (5 : ℝ) / 2 := lt_of_lt_of_le hx (min_le_left _ _) + have h2 : |x - (5 : ℝ)| < ε * (5 : ℝ) ^ 2 / (2 * (3 : ℝ)) := lt_of_lt_of_le hx (min_le_right _ _) + have hx0 : (5 : ℝ) / 2 < x := by + have := (abs_lt.mp h1).1 + linarith + have hxpos : (0 : ℝ) < x := by linarith + have e : (3 : ℝ) / x - (3 : ℝ) / (5 : ℝ) = (3 : ℝ) * ((5 : ℝ) - x) / (x * (5 : ℝ)) := by + field_simp + have h3 : (3 : ℝ) * |x - (5 : ℝ)| < ε * (5 : ℝ) ^ 2 / 2 := by + rw [lt_div_iff₀ (by norm_num)] at h2 ⊢ + nlinarith [abs_nonneg (x - (5 : ℝ))] + have h4 : ε * (5 : ℝ) ^ 2 / 2 < ε * (x * (5 : ℝ)) := by nlinarith [mul_pos hε (sub_pos.mpr hx0), mul_pos hε hxpos] + rw [e, abs_div, abs_mul, abs_of_pos (by positivity : (0 : ℝ) < x * (5 : ℝ)), abs_sub_comm, show |(3 : ℝ)| = (3 : ℝ) by norm_num, div_lt_iff₀ (by positivity)] + linarith diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0044/solution/solve.sh b/tasks/real-analysis/real-analysis-continuity-d3-t0044/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0044/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0044/task.toml b/tasks/real-analysis/real-analysis-continuity-d3-t0044/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3f4ec6c0ac1009274d50eb26b77957501348d250 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0044/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "real-analysis" +tags = ["real-analysis", "continuity", "msc-26", "train", "lean4"] +msc = "26" +family = "continuity" +split = "train" +seed = 44 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0044/tests/Verify.lean b/tasks/real-analysis/real-analysis-continuity-d3-t0044/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0044/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0044/tests/grade.py b/tasks/real-analysis/real-analysis-continuity-d3-t0044/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0044/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0044/tests/spec.json b/tasks/real-analysis/real-analysis-continuity-d3-t0044/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..67b4ea515fb30a213d87544ed5630cd360678391 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0044/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- Epsilon-delta continuity of the reciprocal function at a point. -/\ntheorem continuous_at :\n ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (5 : ℝ)| < δ → |(3 : ℝ) / x - (3 : ℝ) / (5 : ℝ)| < ε := by\n sorry\n", + "targets": [ + { + "name": "continuous_at", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0044/tests/test.sh b/tasks/real-analysis/real-analysis-continuity-d3-t0044/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0044/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0080/environment/Dockerfile b/tasks/real-analysis/real-analysis-continuity-d3-t0080/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0080/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0080/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-continuity-d3-t0080/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..10ea90aebc8891b6bfe53f03c03a11a796f392cd --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0080/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Epsilon-delta continuity of the reciprocal function at a point. -/ +theorem continuous_at : + ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (1 : ℝ)| < δ → |(1 : ℝ) / x - (1 : ℝ) / (1 : ℝ)| < ε := by + sorry diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0080/instruction.md b/tasks/real-analysis/real-analysis-continuity-d3-t0080/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1d66b707898346b280ca84dee7a1765af47ac7c3 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0080/instruction.md @@ -0,0 +1,12 @@ +# Prove continuity from the epsilon-delta definition + +Prove, from the epsilon-delta definition, that \(f(x) = \dfrac{1}{x}\) is continuous at \(x_0 = 1\): for every \(\varepsilon > 0\) there is \(\delta > 0\) such that \(|f(x) - f(x_0)| < \varepsilon\) whenever \(|x - x_0| < \delta\). Here \(x\) ranges over all real numbers (in Lean, division by 0 gives 0, which does not matter for small \(\delta\)). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0080/solution/Solution.lean b/tasks/real-analysis/real-analysis-continuity-d3-t0080/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..71c193c6c38a89d5100cffda135f7f0ffa2f8313 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0080/solution/Solution.lean @@ -0,0 +1,21 @@ +import Mathlib + +/-- Epsilon-delta continuity of the reciprocal function at a point. -/ +theorem continuous_at : + ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (1 : ℝ)| < δ → |(1 : ℝ) / x - (1 : ℝ) / (1 : ℝ)| < ε := by + intro ε hε + refine ⟨min ((1 : ℝ) / 2) (ε * (1 : ℝ) ^ 2 / (2 * (1 : ℝ))), lt_min (by norm_num) (by positivity), fun x hx => ?_⟩ + have h1 : |x - (1 : ℝ)| < (1 : ℝ) / 2 := lt_of_lt_of_le hx (min_le_left _ _) + have h2 : |x - (1 : ℝ)| < ε * (1 : ℝ) ^ 2 / (2 * (1 : ℝ)) := lt_of_lt_of_le hx (min_le_right _ _) + have hx0 : (1 : ℝ) / 2 < x := by + have := (abs_lt.mp h1).1 + linarith + have hxpos : (0 : ℝ) < x := by linarith + have e : (1 : ℝ) / x - (1 : ℝ) / (1 : ℝ) = (1 : ℝ) * ((1 : ℝ) - x) / (x * (1 : ℝ)) := by + field_simp + have h3 : (1 : ℝ) * |x - (1 : ℝ)| < ε * (1 : ℝ) ^ 2 / 2 := by + rw [lt_div_iff₀ (by norm_num)] at h2 ⊢ + nlinarith [abs_nonneg (x - (1 : ℝ))] + have h4 : ε * (1 : ℝ) ^ 2 / 2 < ε * (x * (1 : ℝ)) := by nlinarith [mul_pos hε (sub_pos.mpr hx0), mul_pos hε hxpos] + rw [e, abs_div, abs_mul, abs_of_pos (by positivity : (0 : ℝ) < x * (1 : ℝ)), abs_sub_comm, show |(1 : ℝ)| = (1 : ℝ) by norm_num, div_lt_iff₀ (by positivity)] + linarith diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0080/solution/solve.sh b/tasks/real-analysis/real-analysis-continuity-d3-t0080/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0080/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0080/task.toml b/tasks/real-analysis/real-analysis-continuity-d3-t0080/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8e6a87b89ce3ed36aa20600ff6d4ef331f59e299 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0080/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "real-analysis" +tags = ["real-analysis", "continuity", "msc-26", "train", "lean4"] +msc = "26" +family = "continuity" +split = "train" +seed = 80 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0080/tests/Verify.lean b/tasks/real-analysis/real-analysis-continuity-d3-t0080/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0080/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0080/tests/grade.py b/tasks/real-analysis/real-analysis-continuity-d3-t0080/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0080/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0080/tests/spec.json b/tasks/real-analysis/real-analysis-continuity-d3-t0080/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..592e3ae820a3bb0a6e565bfd2b6d7a018656e152 --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0080/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- Epsilon-delta continuity of the reciprocal function at a point. -/\ntheorem continuous_at :\n ∀ ε > 0, ∃ δ > 0, ∀ x : ℝ, |x - (1 : ℝ)| < δ → |(1 : ℝ) / x - (1 : ℝ) / (1 : ℝ)| < ε := by\n sorry\n", + "targets": [ + { + "name": "continuous_at", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-continuity-d3-t0080/tests/test.sh b/tasks/real-analysis/real-analysis-continuity-d3-t0080/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-continuity-d3-t0080/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/environment/Dockerfile b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..09cf75c6f919c6852e15faf5be2a8b3e562a4be8 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The sequence tends to 0 (epsilon-N definition). -/ +theorem seq_limit : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |(3 : ℝ) / ((n : ℝ) + (1 : ℝ)) - 0| < ε := by + sorry diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/instruction.md b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6dd270b17670785877a59183dffada5f37160fd7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/instruction.md @@ -0,0 +1,12 @@ +# Prove a limit from the definition + +Prove, directly from the definition of a limit, that the sequence \(u_n = \dfrac{3}{n + 1}\) tends to \(0\): for every \(\varepsilon > 0\) there is \(N\) such that \(|u_n - 0| < \varepsilon\) for all \(n \ge N\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/solution/Solution.lean b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..b3bf82a617ba4167115a0e06102331c743881424 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/solution/Solution.lean @@ -0,0 +1,12 @@ +import Mathlib + +/-- The sequence tends to 0 (epsilon-N definition). -/ +theorem seq_limit : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |(3 : ℝ) / ((n : ℝ) + (1 : ℝ)) - 0| < ε := by + intro ε hε + refine ⟨⌈(3 : ℝ) / ε⌉₊, fun n hn => ?_⟩ + have h1 : (3 : ℝ) / ε ≤ (n : ℝ) := (Nat.le_ceil _).trans (by exact_mod_cast hn) + have h2 : (3 : ℝ) ≤ (n : ℝ) * ε := (div_le_iff₀ hε).mp h1 + have hpos : (0 : ℝ) < (n : ℝ) + (1 : ℝ) := by positivity + rw [sub_zero, abs_of_pos (by positivity), div_lt_iff₀ hpos] + nlinarith [mul_pos hε (by norm_num : (0 : ℝ) < (1 : ℝ))] diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/solution/solve.sh b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/task.toml b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f595405f44e28065c4bea4211ad94ec0ad9a8730 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "real-analysis" +tags = ["real-analysis", "limit_sequence", "msc-26", "train", "lean4"] +msc = "26" +family = "limit_sequence" +split = "train" +seed = 61 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/tests/Verify.lean b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/tests/grade.py b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/tests/spec.json b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..cb6a84ede3a06bc1fc9536f9e854337b241d60f4 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The sequence tends to 0 (epsilon-N definition). -/\ntheorem seq_limit :\n ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |(3 : ℝ) / ((n : ℝ) + (1 : ℝ)) - 0| < ε := by\n sorry\n", + "targets": [ + { + "name": "seq_limit", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/tests/test.sh b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d1-t0061/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/environment/Dockerfile b/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..0c6fea43c3dfeb8fb9aa263aa89e4136dfff179d --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The sequence converges to a/c (epsilon-N definition). -/ +theorem seq_limit : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |((-3 : ℝ) * (n : ℝ) + (4 : ℝ)) / ((2 : ℝ) * (n : ℝ) + (5 : ℝ)) - (-3 : ℝ) / (2 : ℝ)| < ε := by + sorry diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/instruction.md b/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c00bb8e5b9596a2af0d4d8cf54610eb3777d37cd --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/instruction.md @@ -0,0 +1,12 @@ +# Prove a limit from the definition + +Prove, directly from the definition of a limit, that \(u_n = \dfrac{-3n + 4}{2n + 5}\) tends to \(\dfrac{-3}{2}\): for every \(\varepsilon > 0\) there is \(N\) such that \(\left|u_n - \frac{-3}{2}\right| < \varepsilon\) for all \(n \ge N\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/solution/Solution.lean b/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..3fcc24b768bed48c7ca29ccbcdb76bc92d92edd8 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/solution/Solution.lean @@ -0,0 +1,17 @@ +import Mathlib + +/-- The sequence converges to a/c (epsilon-N definition). -/ +theorem seq_limit : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |((-3 : ℝ) * (n : ℝ) + (4 : ℝ)) / ((2 : ℝ) * (n : ℝ) + (5 : ℝ)) - (-3 : ℝ) / (2 : ℝ)| < ε := by + intro ε hε + refine ⟨⌈(23 : ℝ) / ε⌉₊, fun n hn => ?_⟩ + have h1 : (23 : ℝ) / ε ≤ (n : ℝ) := (Nat.le_ceil _).trans (by exact_mod_cast hn) + have h2 : (23 : ℝ) ≤ (n : ℝ) * ε := (div_le_iff₀ hε).mp h1 + have hn0 : (0 : ℝ) ≤ (n : ℝ) := Nat.cast_nonneg n + have hden : (0 : ℝ) < (2 : ℝ) * (n : ℝ) + (5 : ℝ) := by positivity + have e : ((-3 : ℝ) * (n : ℝ) + (4 : ℝ)) / ((2 : ℝ) * (n : ℝ) + (5 : ℝ)) - (-3 : ℝ) / (2 : ℝ) = ((2 : ℝ) * (4 : ℝ) - (-3 : ℝ) * (5 : ℝ)) / ((2 : ℝ) * ((2 : ℝ) * (n : ℝ) + (5 : ℝ))) := by + field_simp + ring + have hk : |((2 : ℝ) * (4 : ℝ) - (-3 : ℝ) * (5 : ℝ) : ℝ)| = (23 : ℝ) := by norm_num [abs_of_nonneg, abs_of_nonpos] + rw [e, abs_div, hk, abs_of_pos (by positivity), div_lt_iff₀ (by positivity)] + nlinarith [mul_nonneg hn0 hε.le, hε] diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/solution/solve.sh b/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/task.toml b/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1f66e557db8919e7aaebdc28a180dccffed1110b --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "real-analysis" +tags = ["real-analysis", "limit_sequence", "msc-26", "eval", "lean4"] +msc = "26" +family = "limit_sequence" +split = "eval" +seed = 10017 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/tests/Verify.lean b/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/tests/grade.py b/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/tests/spec.json b/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..f1e5ad84c7040301367c5a089a23e36e2b25ae34 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The sequence converges to a/c (epsilon-N definition). -/\ntheorem seq_limit :\n ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |((-3 : ℝ) * (n : ℝ) + (4 : ℝ)) / ((2 : ℝ) * (n : ℝ) + (5 : ℝ)) - (-3 : ℝ) / (2 : ℝ)| < ε := by\n sorry\n", + "targets": [ + { + "name": "seq_limit", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/tests/test.sh b/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-e0017/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/environment/Dockerfile b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..6b3363bb6245fd932eeec4a35094e2503085f595 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The sequence converges to a/c (epsilon-N definition). -/ +theorem seq_limit : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |((-5 : ℝ) * (n : ℝ) + (2 : ℝ)) / ((2 : ℝ) * (n : ℝ) + (9 : ℝ)) - (-5 : ℝ) / (2 : ℝ)| < ε := by + sorry diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/instruction.md b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4db0950817aa9ba2f2ce8bf69f290242debb5d43 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/instruction.md @@ -0,0 +1,12 @@ +# Prove a limit from the definition + +Prove, directly from the definition of a limit, that \(u_n = \dfrac{-5n + 2}{2n + 9}\) tends to \(\dfrac{-5}{2}\): for every \(\varepsilon > 0\) there is \(N\) such that \(\left|u_n - \frac{-5}{2}\right| < \varepsilon\) for all \(n \ge N\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/solution/Solution.lean b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..a8d53cc0fb76b3e804b9ea76b9ac415329e2db93 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/solution/Solution.lean @@ -0,0 +1,17 @@ +import Mathlib + +/-- The sequence converges to a/c (epsilon-N definition). -/ +theorem seq_limit : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |((-5 : ℝ) * (n : ℝ) + (2 : ℝ)) / ((2 : ℝ) * (n : ℝ) + (9 : ℝ)) - (-5 : ℝ) / (2 : ℝ)| < ε := by + intro ε hε + refine ⟨⌈(49 : ℝ) / ε⌉₊, fun n hn => ?_⟩ + have h1 : (49 : ℝ) / ε ≤ (n : ℝ) := (Nat.le_ceil _).trans (by exact_mod_cast hn) + have h2 : (49 : ℝ) ≤ (n : ℝ) * ε := (div_le_iff₀ hε).mp h1 + have hn0 : (0 : ℝ) ≤ (n : ℝ) := Nat.cast_nonneg n + have hden : (0 : ℝ) < (2 : ℝ) * (n : ℝ) + (9 : ℝ) := by positivity + have e : ((-5 : ℝ) * (n : ℝ) + (2 : ℝ)) / ((2 : ℝ) * (n : ℝ) + (9 : ℝ)) - (-5 : ℝ) / (2 : ℝ) = ((2 : ℝ) * (2 : ℝ) - (-5 : ℝ) * (9 : ℝ)) / ((2 : ℝ) * ((2 : ℝ) * (n : ℝ) + (9 : ℝ))) := by + field_simp + ring + have hk : |((2 : ℝ) * (2 : ℝ) - (-5 : ℝ) * (9 : ℝ) : ℝ)| = (49 : ℝ) := by norm_num [abs_of_nonneg, abs_of_nonpos] + rw [e, abs_div, hk, abs_of_pos (by positivity), div_lt_iff₀ (by positivity)] + nlinarith [mul_nonneg hn0 hε.le, hε] diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/solution/solve.sh b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/task.toml b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bd060c840abda27cb73c7cc0b5de778f7322a83b --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "real-analysis" +tags = ["real-analysis", "limit_sequence", "msc-26", "train", "lean4"] +msc = "26" +family = "limit_sequence" +split = "train" +seed = 5 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/tests/Verify.lean b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/tests/grade.py b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/tests/spec.json b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..e94f411f3ebf33ab8889a2ee4ab53377957a6ed8 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The sequence converges to a/c (epsilon-N definition). -/\ntheorem seq_limit :\n ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |((-5 : ℝ) * (n : ℝ) + (2 : ℝ)) / ((2 : ℝ) * (n : ℝ) + (9 : ℝ)) - (-5 : ℝ) / (2 : ℝ)| < ε := by\n sorry\n", + "targets": [ + { + "name": "seq_limit", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/tests/test.sh b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0005/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/environment/Dockerfile b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..3f193e92aec67d4428d72411e8c75606cd8ccca7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The sequence converges to a/c (epsilon-N definition). -/ +theorem seq_limit : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |((3 : ℝ) * (n : ℝ) + (2 : ℝ)) / ((1 : ℝ) * (n : ℝ) + (7 : ℝ)) - (3 : ℝ) / (1 : ℝ)| < ε := by + sorry diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/instruction.md b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..03a26ce23fa145c5ac6d71eaa9e3b3f949453a84 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/instruction.md @@ -0,0 +1,12 @@ +# Prove a limit from the definition + +Prove, directly from the definition of a limit, that \(u_n = \dfrac{3n + 2}{n + 7}\) tends to \(\dfrac{3}{1}\): for every \(\varepsilon > 0\) there is \(N\) such that \(\left|u_n - \frac{3}{1}\right| < \varepsilon\) for all \(n \ge N\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/solution/Solution.lean b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..f431bb94b9f4614fd40b35f692839a82babbdbd5 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/solution/Solution.lean @@ -0,0 +1,17 @@ +import Mathlib + +/-- The sequence converges to a/c (epsilon-N definition). -/ +theorem seq_limit : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |((3 : ℝ) * (n : ℝ) + (2 : ℝ)) / ((1 : ℝ) * (n : ℝ) + (7 : ℝ)) - (3 : ℝ) / (1 : ℝ)| < ε := by + intro ε hε + refine ⟨⌈(19 : ℝ) / ε⌉₊, fun n hn => ?_⟩ + have h1 : (19 : ℝ) / ε ≤ (n : ℝ) := (Nat.le_ceil _).trans (by exact_mod_cast hn) + have h2 : (19 : ℝ) ≤ (n : ℝ) * ε := (div_le_iff₀ hε).mp h1 + have hn0 : (0 : ℝ) ≤ (n : ℝ) := Nat.cast_nonneg n + have hden : (0 : ℝ) < (1 : ℝ) * (n : ℝ) + (7 : ℝ) := by positivity + have e : ((3 : ℝ) * (n : ℝ) + (2 : ℝ)) / ((1 : ℝ) * (n : ℝ) + (7 : ℝ)) - (3 : ℝ) / (1 : ℝ) = ((1 : ℝ) * (2 : ℝ) - (3 : ℝ) * (7 : ℝ)) / ((1 : ℝ) * ((1 : ℝ) * (n : ℝ) + (7 : ℝ))) := by + field_simp + ring + have hk : |((1 : ℝ) * (2 : ℝ) - (3 : ℝ) * (7 : ℝ) : ℝ)| = (19 : ℝ) := by norm_num [abs_of_nonneg, abs_of_nonpos] + rw [e, abs_div, hk, abs_of_pos (by positivity), div_lt_iff₀ (by positivity)] + nlinarith [mul_nonneg hn0 hε.le, hε] diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/solution/solve.sh b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/task.toml b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6fca437b47359709850c9f5720aaba8d37ba3da6 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "real-analysis" +tags = ["real-analysis", "limit_sequence", "msc-26", "train", "lean4"] +msc = "26" +family = "limit_sequence" +split = "train" +seed = 17 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/tests/Verify.lean b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/tests/grade.py b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/tests/spec.json b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..a450fcaceda121cc586784a0abdf92a97ea36684 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The sequence converges to a/c (epsilon-N definition). -/\ntheorem seq_limit :\n ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |((3 : ℝ) * (n : ℝ) + (2 : ℝ)) / ((1 : ℝ) * (n : ℝ) + (7 : ℝ)) - (3 : ℝ) / (1 : ℝ)| < ε := by\n sorry\n", + "targets": [ + { + "name": "seq_limit", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/tests/test.sh b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0017/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/environment/Dockerfile b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..6e1270f35e50e1e1f6016d1431b317e3b27bc844 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The sequence converges to a/c (epsilon-N definition). -/ +theorem seq_limit : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |((4 : ℝ) * (n : ℝ) + (9 : ℝ)) / ((4 : ℝ) * (n : ℝ) + (2 : ℝ)) - (4 : ℝ) / (4 : ℝ)| < ε := by + sorry diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/instruction.md b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..39bb3ab8af28924d92ce0e693e4167a679796669 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/instruction.md @@ -0,0 +1,12 @@ +# Prove a limit from the definition + +Prove, directly from the definition of a limit, that \(u_n = \dfrac{4n + 9}{4n + 2}\) tends to \(\dfrac{4}{4}\): for every \(\varepsilon > 0\) there is \(N\) such that \(\left|u_n - \frac{4}{4}\right| < \varepsilon\) for all \(n \ge N\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/solution/Solution.lean b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..5c8c84d957b4f0e980e1d46441eebc657a04eefb --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/solution/Solution.lean @@ -0,0 +1,17 @@ +import Mathlib + +/-- The sequence converges to a/c (epsilon-N definition). -/ +theorem seq_limit : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |((4 : ℝ) * (n : ℝ) + (9 : ℝ)) / ((4 : ℝ) * (n : ℝ) + (2 : ℝ)) - (4 : ℝ) / (4 : ℝ)| < ε := by + intro ε hε + refine ⟨⌈(28 : ℝ) / ε⌉₊, fun n hn => ?_⟩ + have h1 : (28 : ℝ) / ε ≤ (n : ℝ) := (Nat.le_ceil _).trans (by exact_mod_cast hn) + have h2 : (28 : ℝ) ≤ (n : ℝ) * ε := (div_le_iff₀ hε).mp h1 + have hn0 : (0 : ℝ) ≤ (n : ℝ) := Nat.cast_nonneg n + have hden : (0 : ℝ) < (4 : ℝ) * (n : ℝ) + (2 : ℝ) := by positivity + have e : ((4 : ℝ) * (n : ℝ) + (9 : ℝ)) / ((4 : ℝ) * (n : ℝ) + (2 : ℝ)) - (4 : ℝ) / (4 : ℝ) = ((4 : ℝ) * (9 : ℝ) - (4 : ℝ) * (2 : ℝ)) / ((4 : ℝ) * ((4 : ℝ) * (n : ℝ) + (2 : ℝ))) := by + field_simp + ring + have hk : |((4 : ℝ) * (9 : ℝ) - (4 : ℝ) * (2 : ℝ) : ℝ)| = (28 : ℝ) := by norm_num [abs_of_nonneg, abs_of_nonpos] + rw [e, abs_div, hk, abs_of_pos (by positivity), div_lt_iff₀ (by positivity)] + nlinarith [mul_nonneg hn0 hε.le, hε] diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/solution/solve.sh b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/task.toml b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a418f5fcce864323355e9a30180a998d050c5e41 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "real-analysis" +tags = ["real-analysis", "limit_sequence", "msc-26", "train", "lean4"] +msc = "26" +family = "limit_sequence" +split = "train" +seed = 29 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/tests/Verify.lean b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/tests/grade.py b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/tests/spec.json b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..c923e3e47dce8fe5d6781266ba7e84af5c16f674 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The sequence converges to a/c (epsilon-N definition). -/\ntheorem seq_limit :\n ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |((4 : ℝ) * (n : ℝ) + (9 : ℝ)) / ((4 : ℝ) * (n : ℝ) + (2 : ℝ)) - (4 : ℝ) / (4 : ℝ)| < ε := by\n sorry\n", + "targets": [ + { + "name": "seq_limit", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/tests/test.sh b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d2-t0029/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/environment/Dockerfile b/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..0bd3c198bac37626fefffd5e2ceb24933b46902f --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The sequence tends to 0 (epsilon-N definition). -/ +theorem seq_limit : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |((1 : ℝ) * (n : ℝ) + (1 : ℝ)) / ((n : ℝ) ^ 2 + (1 : ℝ)) - 0| < ε := by + sorry diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/instruction.md b/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ba608f38fba9ef0b7634ea8e2d99eb86e1a26d32 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/instruction.md @@ -0,0 +1,12 @@ +# Prove a limit from the definition + +Prove, directly from the definition of a limit, that \(u_n = \dfrac{n + 1}{n^2 + 1}\) tends to \(0\): for every \(\varepsilon > 0\) there is \(N\) such that \(|u_n - 0| < \varepsilon\) for all \(n \ge N\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/solution/Solution.lean b/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..df6c7390cd24f6a4ec382df9ee3961fa1fab3c9e --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/solution/Solution.lean @@ -0,0 +1,16 @@ +import Mathlib + +/-- The sequence tends to 0 (epsilon-N definition). -/ +theorem seq_limit : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |((1 : ℝ) * (n : ℝ) + (1 : ℝ)) / ((n : ℝ) ^ 2 + (1 : ℝ)) - 0| < ε := by + intro ε hε + refine ⟨⌈(2 : ℝ) / ε⌉₊ + 1, fun n hn => ?_⟩ + have h1 : (2 : ℝ) / ε ≤ ((⌈(2 : ℝ) / ε⌉₊ : ℕ) : ℝ) := Nat.le_ceil _ + have h1' : (((⌈(2 : ℝ) / ε⌉₊ + 1 : ℕ)) : ℝ) ≤ (n : ℝ) := by exact_mod_cast hn + push_cast at h1' + have h2 : (2 : ℝ) ≤ ((⌈(2 : ℝ) / ε⌉₊ : ℕ) : ℝ) * ε := (div_le_iff₀ hε).mp h1 + have hn1 : (1 : ℝ) ≤ (n : ℝ) := by linarith [Nat.cast_nonneg (α := ℝ) ⌈(2 : ℝ) / ε⌉₊] + have hM : (2 : ℝ) < (n : ℝ) * ε := by nlinarith + have hpos : (0 : ℝ) < (n : ℝ) ^ 2 + (1 : ℝ) := by positivity + rw [sub_zero, abs_of_pos (by positivity), div_lt_iff₀ hpos] + nlinarith [mul_pos hε (by norm_num : (0 : ℝ) < (1 : ℝ)), mul_le_mul_of_nonneg_left hn1 (by positivity : (0 : ℝ) ≤ (1 : ℝ)), mul_pos hε (by linarith : (0 : ℝ) < (n : ℝ))] diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/solution/solve.sh b/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/task.toml b/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..70089141752344dc7e924d008bdf5e66ec7a70a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "real-analysis" +tags = ["real-analysis", "limit_sequence", "msc-26", "eval", "lean4"] +msc = "26" +family = "limit_sequence" +split = "eval" +seed = 10021 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/tests/Verify.lean b/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/tests/grade.py b/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/tests/spec.json b/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..004c6bffb0bc601500ffb26d3637e8533f10f5ed --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The sequence tends to 0 (epsilon-N definition). -/\ntheorem seq_limit :\n ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |((1 : ℝ) * (n : ℝ) + (1 : ℝ)) / ((n : ℝ) ^ 2 + (1 : ℝ)) - 0| < ε := by\n sorry\n", + "targets": [ + { + "name": "seq_limit", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/tests/test.sh b/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-e0021/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/environment/Dockerfile b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..d3b36ccb521ca7202a0af1c6710ce9fe8924df8a --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The sequence tends to 0 (epsilon-N definition). -/ +theorem seq_limit : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |((2 : ℝ) * (n : ℝ) + (2 : ℝ)) / ((n : ℝ) ^ 2 + (6 : ℝ)) - 0| < ε := by + sorry diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/instruction.md b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..50c032ec7517b630fdede26e39d80aaa6221902f --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/instruction.md @@ -0,0 +1,12 @@ +# Prove a limit from the definition + +Prove, directly from the definition of a limit, that \(u_n = \dfrac{2n + 2}{n^2 + 6}\) tends to \(0\): for every \(\varepsilon > 0\) there is \(N\) such that \(|u_n - 0| < \varepsilon\) for all \(n \ge N\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/solution/Solution.lean b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..1334fdb94312c04ed96a77f0115730b6e710fa8b --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/solution/Solution.lean @@ -0,0 +1,16 @@ +import Mathlib + +/-- The sequence tends to 0 (epsilon-N definition). -/ +theorem seq_limit : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |((2 : ℝ) * (n : ℝ) + (2 : ℝ)) / ((n : ℝ) ^ 2 + (6 : ℝ)) - 0| < ε := by + intro ε hε + refine ⟨⌈(4 : ℝ) / ε⌉₊ + 1, fun n hn => ?_⟩ + have h1 : (4 : ℝ) / ε ≤ ((⌈(4 : ℝ) / ε⌉₊ : ℕ) : ℝ) := Nat.le_ceil _ + have h1' : (((⌈(4 : ℝ) / ε⌉₊ + 1 : ℕ)) : ℝ) ≤ (n : ℝ) := by exact_mod_cast hn + push_cast at h1' + have h2 : (4 : ℝ) ≤ ((⌈(4 : ℝ) / ε⌉₊ : ℕ) : ℝ) * ε := (div_le_iff₀ hε).mp h1 + have hn1 : (1 : ℝ) ≤ (n : ℝ) := by linarith [Nat.cast_nonneg (α := ℝ) ⌈(4 : ℝ) / ε⌉₊] + have hM : (4 : ℝ) < (n : ℝ) * ε := by nlinarith + have hpos : (0 : ℝ) < (n : ℝ) ^ 2 + (6 : ℝ) := by positivity + rw [sub_zero, abs_of_pos (by positivity), div_lt_iff₀ hpos] + nlinarith [mul_pos hε (by norm_num : (0 : ℝ) < (6 : ℝ)), mul_le_mul_of_nonneg_left hn1 (by positivity : (0 : ℝ) ≤ (2 : ℝ)), mul_pos hε (by linarith : (0 : ℝ) < (n : ℝ))] diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/solution/solve.sh b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/task.toml b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f4930d43eb69411e256cb8bf92c81e3e03e2f8e2 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "real-analysis" +tags = ["real-analysis", "limit_sequence", "msc-26", "train", "lean4"] +msc = "26" +family = "limit_sequence" +split = "train" +seed = 33 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/tests/Verify.lean b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/tests/grade.py b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/tests/spec.json b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..57141d21f81cd16e954b4f2fa61a2b307a2e6dbf --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The sequence tends to 0 (epsilon-N definition). -/\ntheorem seq_limit :\n ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |((2 : ℝ) * (n : ℝ) + (2 : ℝ)) / ((n : ℝ) ^ 2 + (6 : ℝ)) - 0| < ε := by\n sorry\n", + "targets": [ + { + "name": "seq_limit", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/tests/test.sh b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0033/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/environment/Dockerfile b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..2b00efab0dca8532fcb29f17623ad85b201ff3fa --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The sequence tends to 0 (epsilon-N definition). -/ +theorem seq_limit : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |((4 : ℝ) * (n : ℝ) + (2 : ℝ)) / ((n : ℝ) ^ 2 + (2 : ℝ)) - 0| < ε := by + sorry diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/instruction.md b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0cfdc21c0bd819924b2e5b49734b2cc943d3820f --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/instruction.md @@ -0,0 +1,12 @@ +# Prove a limit from the definition + +Prove, directly from the definition of a limit, that \(u_n = \dfrac{4n + 2}{n^2 + 2}\) tends to \(0\): for every \(\varepsilon > 0\) there is \(N\) such that \(|u_n - 0| < \varepsilon\) for all \(n \ge N\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/solution/Solution.lean b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..df7dd3fb6e10461a7660e6060154e5d5fc97a9be --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/solution/Solution.lean @@ -0,0 +1,16 @@ +import Mathlib + +/-- The sequence tends to 0 (epsilon-N definition). -/ +theorem seq_limit : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |((4 : ℝ) * (n : ℝ) + (2 : ℝ)) / ((n : ℝ) ^ 2 + (2 : ℝ)) - 0| < ε := by + intro ε hε + refine ⟨⌈(6 : ℝ) / ε⌉₊ + 1, fun n hn => ?_⟩ + have h1 : (6 : ℝ) / ε ≤ ((⌈(6 : ℝ) / ε⌉₊ : ℕ) : ℝ) := Nat.le_ceil _ + have h1' : (((⌈(6 : ℝ) / ε⌉₊ + 1 : ℕ)) : ℝ) ≤ (n : ℝ) := by exact_mod_cast hn + push_cast at h1' + have h2 : (6 : ℝ) ≤ ((⌈(6 : ℝ) / ε⌉₊ : ℕ) : ℝ) * ε := (div_le_iff₀ hε).mp h1 + have hn1 : (1 : ℝ) ≤ (n : ℝ) := by linarith [Nat.cast_nonneg (α := ℝ) ⌈(6 : ℝ) / ε⌉₊] + have hM : (6 : ℝ) < (n : ℝ) * ε := by nlinarith + have hpos : (0 : ℝ) < (n : ℝ) ^ 2 + (2 : ℝ) := by positivity + rw [sub_zero, abs_of_pos (by positivity), div_lt_iff₀ hpos] + nlinarith [mul_pos hε (by norm_num : (0 : ℝ) < (2 : ℝ)), mul_le_mul_of_nonneg_left hn1 (by positivity : (0 : ℝ) ≤ (2 : ℝ)), mul_pos hε (by linarith : (0 : ℝ) < (n : ℝ))] diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/solution/solve.sh b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/task.toml b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3fd092ce6be9e2bb3e91ebd21248abd33f056bd7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "real-analysis" +tags = ["real-analysis", "limit_sequence", "msc-26", "train", "lean4"] +msc = "26" +family = "limit_sequence" +split = "train" +seed = 57 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/tests/Verify.lean b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/tests/grade.py b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/tests/spec.json b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..26b0d52cc1689e53c9f158e91549a9269a3b242d --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The sequence tends to 0 (epsilon-N definition). -/\ntheorem seq_limit :\n ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |((4 : ℝ) * (n : ℝ) + (2 : ℝ)) / ((n : ℝ) ^ 2 + (2 : ℝ)) - 0| < ε := by\n sorry\n", + "targets": [ + { + "name": "seq_limit", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/tests/test.sh b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0057/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/environment/Dockerfile b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..45d8fc45f7a9a7867803abd5497b82160725b280 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The sequence tends to 0 (epsilon-N definition). -/ +theorem seq_limit : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |((5 : ℝ) * (n : ℝ) + (6 : ℝ)) / ((n : ℝ) ^ 2 + (8 : ℝ)) - 0| < ε := by + sorry diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/instruction.md b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6b9c6e28a63f03b16d439f841cfd046deb8b967d --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/instruction.md @@ -0,0 +1,12 @@ +# Prove a limit from the definition + +Prove, directly from the definition of a limit, that \(u_n = \dfrac{5n + 6}{n^2 + 8}\) tends to \(0\): for every \(\varepsilon > 0\) there is \(N\) such that \(|u_n - 0| < \varepsilon\) for all \(n \ge N\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/solution/Solution.lean b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..b3dc2fbbc3905e334f25b68098a8be93797a446d --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/solution/Solution.lean @@ -0,0 +1,16 @@ +import Mathlib + +/-- The sequence tends to 0 (epsilon-N definition). -/ +theorem seq_limit : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |((5 : ℝ) * (n : ℝ) + (6 : ℝ)) / ((n : ℝ) ^ 2 + (8 : ℝ)) - 0| < ε := by + intro ε hε + refine ⟨⌈(11 : ℝ) / ε⌉₊ + 1, fun n hn => ?_⟩ + have h1 : (11 : ℝ) / ε ≤ ((⌈(11 : ℝ) / ε⌉₊ : ℕ) : ℝ) := Nat.le_ceil _ + have h1' : (((⌈(11 : ℝ) / ε⌉₊ + 1 : ℕ)) : ℝ) ≤ (n : ℝ) := by exact_mod_cast hn + push_cast at h1' + have h2 : (11 : ℝ) ≤ ((⌈(11 : ℝ) / ε⌉₊ : ℕ) : ℝ) * ε := (div_le_iff₀ hε).mp h1 + have hn1 : (1 : ℝ) ≤ (n : ℝ) := by linarith [Nat.cast_nonneg (α := ℝ) ⌈(11 : ℝ) / ε⌉₊] + have hM : (11 : ℝ) < (n : ℝ) * ε := by nlinarith + have hpos : (0 : ℝ) < (n : ℝ) ^ 2 + (8 : ℝ) := by positivity + rw [sub_zero, abs_of_pos (by positivity), div_lt_iff₀ hpos] + nlinarith [mul_pos hε (by norm_num : (0 : ℝ) < (8 : ℝ)), mul_le_mul_of_nonneg_left hn1 (by positivity : (0 : ℝ) ≤ (6 : ℝ)), mul_pos hε (by linarith : (0 : ℝ) < (n : ℝ))] diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/solution/solve.sh b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/task.toml b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8004e848acaea22b00736ee3f7b2acbbf120b5c1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "real-analysis" +tags = ["real-analysis", "limit_sequence", "msc-26", "train", "lean4"] +msc = "26" +family = "limit_sequence" +split = "train" +seed = 69 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/tests/Verify.lean b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/tests/grade.py b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/tests/spec.json b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..54eccd4b0a51c73573200f778d1d687299c25e25 --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The sequence tends to 0 (epsilon-N definition). -/\ntheorem seq_limit :\n ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, |((5 : ℝ) * (n : ℝ) + (6 : ℝ)) / ((n : ℝ) ^ 2 + (8 : ℝ)) - 0| < ε := by\n sorry\n", + "targets": [ + { + "name": "seq_limit", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/tests/test.sh b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-limit_sequence-d3-t0069/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/environment/Dockerfile b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..c7f68c77184dd521ba8b54d58a615075d0cf1072 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/environment/workdir/Solution.lean @@ -0,0 +1,10 @@ +import Mathlib + +noncomputable def a : ℕ → ℝ + | 0 => (7 / 2 : ℝ) + | (n + 1) => a n / 2 + (7 / 2 : ℝ) + +/-- The sequence stays between 0 and its upper bound. -/ +theorem a_bounds : + ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (7 : ℝ) := by + sorry diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/instruction.md b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fbc8a5bc6f118dae4e8936be9e2013a5a7c28f8c --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/instruction.md @@ -0,0 +1,12 @@ +# Bound a recursive sequence + +Define a real sequence by \(a_0 = \frac{7}{2}\) and \(a_{n+1} = \frac{a_n}{2} + \frac{7}{2}\). Prove that \(0 \le a_n \le 7\) for every \(n\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/solution/Solution.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..49502c27028987c0d4a115899ababde9983bb8b7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/solution/Solution.lean @@ -0,0 +1,16 @@ +import Mathlib + +noncomputable def a : ℕ → ℝ + | 0 => (7 / 2 : ℝ) + | (n + 1) => a n / 2 + (7 / 2 : ℝ) + +/-- The sequence stays between 0 and its upper bound. -/ +theorem a_bounds : + ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (7 : ℝ) := by + intro n + induction n with + | zero => norm_num [a] + | succ k ih => + obtain ⟨h0, h1⟩ := ih + simp only [a] + constructor <;> linarith diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/solution/solve.sh b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/task.toml b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6af0d34ead37b2fb7294ec59252b14d0c92971e0 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "real-analysis" +tags = ["real-analysis", "sequence_bounds", "msc-26", "eval", "lean4"] +msc = "26" +family = "sequence_bounds" +split = "eval" +seed = 10014 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/tests/Verify.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/tests/grade.py b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/tests/spec.json b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..a0ef36653d52b732ec7c6dc6824d85b28f679894 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\nnoncomputable def a : ℕ → ℝ\n | 0 => (7 / 2 : ℝ)\n | (n + 1) => a n / 2 + (7 / 2 : ℝ)\n\n/-- The sequence stays between 0 and its upper bound. -/\ntheorem a_bounds :\n ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (7 : ℝ) := by\n sorry\n", + "targets": [ + { + "name": "a_bounds", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/tests/test.sh b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-e0014/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/environment/Dockerfile b/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..e524eb026aa22345859ab6f2e0d6f76098593478 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/environment/workdir/Solution.lean @@ -0,0 +1,10 @@ +import Mathlib + +noncomputable def a : ℕ → ℝ + | 0 => (0 : ℝ) + | (n + 1) => a n / 2 + (5 / 2 : ℝ) + +/-- The sequence stays between 0 and its upper bound. -/ +theorem a_bounds : + ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (5 : ℝ) := by + sorry diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/instruction.md b/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..18f8ecdedf883422db7a52a0008d97b889a1aaaa --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/instruction.md @@ -0,0 +1,12 @@ +# Bound a recursive sequence + +Define a real sequence by \(a_0 = 0\) and \(a_{n+1} = \frac{a_n}{2} + \frac{5}{2}\). Prove that \(0 \le a_n \le 5\) for every \(n\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/solution/Solution.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..d67cf0ff14386e29c0db60eac7a5a782a20dc112 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/solution/Solution.lean @@ -0,0 +1,16 @@ +import Mathlib + +noncomputable def a : ℕ → ℝ + | 0 => (0 : ℝ) + | (n + 1) => a n / 2 + (5 / 2 : ℝ) + +/-- The sequence stays between 0 and its upper bound. -/ +theorem a_bounds : + ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (5 : ℝ) := by + intro n + induction n with + | zero => norm_num [a] + | succ k ih => + obtain ⟨h0, h1⟩ := ih + simp only [a] + constructor <;> linarith diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/solution/solve.sh b/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/task.toml b/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a4cbe1f711f40aafdd21b26292bdad7b450324cd --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "real-analysis" +tags = ["real-analysis", "sequence_bounds", "msc-26", "train", "lean4"] +msc = "26" +family = "sequence_bounds" +split = "train" +seed = 14 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/tests/Verify.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/tests/grade.py b/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/tests/spec.json b/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..30510fb844cc77ac40fbc262ecd3fc0c0ca24518 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\nnoncomputable def a : ℕ → ℝ\n | 0 => (0 : ℝ)\n | (n + 1) => a n / 2 + (5 / 2 : ℝ)\n\n/-- The sequence stays between 0 and its upper bound. -/\ntheorem a_bounds :\n ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (5 : ℝ) := by\n sorry\n", + "targets": [ + { + "name": "a_bounds", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/tests/test.sh b/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d1-t0014/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/environment/Dockerfile b/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..ef56ef6e2ef3d5a3dee897100ccf04841c5e5371 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/environment/workdir/Solution.lean @@ -0,0 +1,15 @@ +import Mathlib + +noncomputable def a : ℕ → ℝ + | 0 => (5 / 2 : ℝ) + | (n + 1) => a n / 2 + (5 / 2 : ℝ) + +/-- The sequence stays between 0 and its upper bound. -/ +theorem a_bounds : + ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (5 : ℝ) := by + sorry + +/-- The sequence is increasing. -/ +theorem a_monotone : + Monotone a := by + sorry diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/instruction.md b/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6460e1a896c20f7de223345ea9647c64660662dc --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/instruction.md @@ -0,0 +1,12 @@ +# Bound a recursive sequence + +Define a real sequence by \(a_0 = \frac{5}{2}\) and \(a_{n+1} = \frac{a_n}{2} + \frac{5}{2}\). Prove that \(0 \le a_n \le 5\) for every \(n\), and then that the sequence is monotone (non-decreasing). + +## What to do + +`Solution.lean` in the working directory states 2 theorems in Lean 4 with Mathlib, with `sorry` in place of each proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is the share of the 2 theorems that are proved. If the file does not compile the reward is 0, so leave `sorry` on a theorem you cannot finish rather than a broken proof. diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/solution/Solution.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..148508cd7f4e41e37c86e70904e69484b836115c --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/solution/Solution.lean @@ -0,0 +1,25 @@ +import Mathlib + +noncomputable def a : ℕ → ℝ + | 0 => (5 / 2 : ℝ) + | (n + 1) => a n / 2 + (5 / 2 : ℝ) + +/-- The sequence stays between 0 and its upper bound. -/ +theorem a_bounds : + ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (5 : ℝ) := by + intro n + induction n with + | zero => norm_num [a] + | succ k ih => + obtain ⟨h0, h1⟩ := ih + simp only [a] + constructor <;> linarith + +/-- The sequence is increasing. -/ +theorem a_monotone : + Monotone a := by + apply monotone_nat_of_le_succ + intro n + have h := (a_bounds n).2 + simp only [a] + linarith diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/solution/solve.sh b/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/task.toml b/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..30dca48679ec6b22eb3916805e63d8badc491100 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "real-analysis" +tags = ["real-analysis", "sequence_bounds", "msc-26", "eval", "lean4"] +msc = "26" +family = "sequence_bounds" +split = "eval" +seed = 10006 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/tests/Verify.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/tests/grade.py b/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/tests/spec.json b/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..ab21320bda63574ae809df0827c7f634ee960498 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\nnoncomputable def a : ℕ → ℝ\n | 0 => (5 / 2 : ℝ)\n | (n + 1) => a n / 2 + (5 / 2 : ℝ)\n\n/-- The sequence stays between 0 and its upper bound. -/\ntheorem a_bounds :\n ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (5 : ℝ) := by\n sorry\n\n/-- The sequence is increasing. -/\ntheorem a_monotone :\n Monotone a := by\n sorry\n", + "targets": [ + { + "name": "a_bounds", + "weight": 1.0 + }, + { + "name": "a_monotone", + "weight": 2.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/tests/test.sh b/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-e0006/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/environment/Dockerfile b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..a4b5b834b64bbd45f2e66bb8877b0e2f2d5ce63d --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/environment/workdir/Solution.lean @@ -0,0 +1,15 @@ +import Mathlib + +noncomputable def a : ℕ → ℝ + | 0 => (21 / 4 : ℝ) + | (n + 1) => a n / 2 + (7 / 2 : ℝ) + +/-- The sequence stays between 0 and its upper bound. -/ +theorem a_bounds : + ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (7 : ℝ) := by + sorry + +/-- The sequence is increasing. -/ +theorem a_monotone : + Monotone a := by + sorry diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/instruction.md b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0b7015ccc2c6ef310bd0dc34604ae31e78778670 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/instruction.md @@ -0,0 +1,12 @@ +# Bound a recursive sequence + +Define a real sequence by \(a_0 = \frac{21}{4}\) and \(a_{n+1} = \frac{a_n}{2} + \frac{7}{2}\). Prove that \(0 \le a_n \le 7\) for every \(n\), and then that the sequence is monotone (non-decreasing). + +## What to do + +`Solution.lean` in the working directory states 2 theorems in Lean 4 with Mathlib, with `sorry` in place of each proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is the share of the 2 theorems that are proved. If the file does not compile the reward is 0, so leave `sorry` on a theorem you cannot finish rather than a broken proof. diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/solution/Solution.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..40a9878947f585d45d0187e3f32ab7ccf2749fa1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/solution/Solution.lean @@ -0,0 +1,25 @@ +import Mathlib + +noncomputable def a : ℕ → ℝ + | 0 => (21 / 4 : ℝ) + | (n + 1) => a n / 2 + (7 / 2 : ℝ) + +/-- The sequence stays between 0 and its upper bound. -/ +theorem a_bounds : + ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (7 : ℝ) := by + intro n + induction n with + | zero => norm_num [a] + | succ k ih => + obtain ⟨h0, h1⟩ := ih + simp only [a] + constructor <;> linarith + +/-- The sequence is increasing. -/ +theorem a_monotone : + Monotone a := by + apply monotone_nat_of_le_succ + intro n + have h := (a_bounds n).2 + simp only [a] + linarith diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/solution/solve.sh b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/task.toml b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f3a77fdeb2e6ef584bc1f2049cdfb5a248924a84 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "real-analysis" +tags = ["real-analysis", "sequence_bounds", "msc-26", "train", "lean4"] +msc = "26" +family = "sequence_bounds" +split = "train" +seed = 6 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/tests/Verify.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/tests/grade.py b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/tests/spec.json b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..2222161313cf21791ae03239236077e9bec6a824 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\nnoncomputable def a : ℕ → ℝ\n | 0 => (21 / 4 : ℝ)\n | (n + 1) => a n / 2 + (7 / 2 : ℝ)\n\n/-- The sequence stays between 0 and its upper bound. -/\ntheorem a_bounds :\n ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (7 : ℝ) := by\n sorry\n\n/-- The sequence is increasing. -/\ntheorem a_monotone :\n Monotone a := by\n sorry\n", + "targets": [ + { + "name": "a_bounds", + "weight": 1.0 + }, + { + "name": "a_monotone", + "weight": 2.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/tests/test.sh b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0006/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/environment/Dockerfile b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..3b7b5861bbcd1155f6fa03de381f737f6ec1082e --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/environment/workdir/Solution.lean @@ -0,0 +1,15 @@ +import Mathlib + +noncomputable def a : ℕ → ℝ + | 0 => (5 / 2 : ℝ) + | (n + 1) => a n / 2 + (5 / 3 : ℝ) + +/-- The sequence stays between 0 and its upper bound. -/ +theorem a_bounds : + ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (10 / 3 : ℝ) := by + sorry + +/-- The sequence is increasing. -/ +theorem a_monotone : + Monotone a := by + sorry diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/instruction.md b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8718d6a7aab146432250fcd2b541ecfee4e9b2f3 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/instruction.md @@ -0,0 +1,12 @@ +# Bound a recursive sequence + +Define a real sequence by \(a_0 = \frac{5}{2}\) and \(a_{n+1} = \frac{a_n}{2} + \frac{5}{3}\). Prove that \(0 \le a_n \le \frac{10}{3}\) for every \(n\), and then that the sequence is monotone (non-decreasing). + +## What to do + +`Solution.lean` in the working directory states 2 theorems in Lean 4 with Mathlib, with `sorry` in place of each proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is the share of the 2 theorems that are proved. If the file does not compile the reward is 0, so leave `sorry` on a theorem you cannot finish rather than a broken proof. diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/solution/Solution.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..aa44665b45066d4c70682bf97cf7c7a26ed2adde --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/solution/Solution.lean @@ -0,0 +1,25 @@ +import Mathlib + +noncomputable def a : ℕ → ℝ + | 0 => (5 / 2 : ℝ) + | (n + 1) => a n / 2 + (5 / 3 : ℝ) + +/-- The sequence stays between 0 and its upper bound. -/ +theorem a_bounds : + ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (10 / 3 : ℝ) := by + intro n + induction n with + | zero => norm_num [a] + | succ k ih => + obtain ⟨h0, h1⟩ := ih + simp only [a] + constructor <;> linarith + +/-- The sequence is increasing. -/ +theorem a_monotone : + Monotone a := by + apply monotone_nat_of_le_succ + intro n + have h := (a_bounds n).2 + simp only [a] + linarith diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/solution/solve.sh b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/task.toml b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..658759d824790c55bbfc51ee5c0d53c3a1a9c952 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "real-analysis" +tags = ["real-analysis", "sequence_bounds", "msc-26", "train", "lean4"] +msc = "26" +family = "sequence_bounds" +split = "train" +seed = 30 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/tests/Verify.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/tests/grade.py b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/tests/spec.json b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..1c035351c7b707c0a8dfea5df74e8ab7625a3a15 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\nnoncomputable def a : ℕ → ℝ\n | 0 => (5 / 2 : ℝ)\n | (n + 1) => a n / 2 + (5 / 3 : ℝ)\n\n/-- The sequence stays between 0 and its upper bound. -/\ntheorem a_bounds :\n ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (10 / 3 : ℝ) := by\n sorry\n\n/-- The sequence is increasing. -/\ntheorem a_monotone :\n Monotone a := by\n sorry\n", + "targets": [ + { + "name": "a_bounds", + "weight": 1.0 + }, + { + "name": "a_monotone", + "weight": 2.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/tests/test.sh b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0030/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/environment/Dockerfile b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..c95865fdf3727c64e5dd1052eb347382dff480a5 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/environment/workdir/Solution.lean @@ -0,0 +1,15 @@ +import Mathlib + +noncomputable def a : ℕ → ℝ + | 0 => (2 : ℝ) + | (n + 1) => a n / 2 + (2 : ℝ) + +/-- The sequence stays between 0 and its upper bound. -/ +theorem a_bounds : + ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (4 : ℝ) := by + sorry + +/-- The sequence is increasing. -/ +theorem a_monotone : + Monotone a := by + sorry diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/instruction.md b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b3c256069a80550aeec7b9c1efbb98db5b14f6ab --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/instruction.md @@ -0,0 +1,12 @@ +# Bound a recursive sequence + +Define a real sequence by \(a_0 = 2\) and \(a_{n+1} = \frac{a_n}{2} + 2\). Prove that \(0 \le a_n \le 4\) for every \(n\), and then that the sequence is monotone (non-decreasing). + +## What to do + +`Solution.lean` in the working directory states 2 theorems in Lean 4 with Mathlib, with `sorry` in place of each proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is the share of the 2 theorems that are proved. If the file does not compile the reward is 0, so leave `sorry` on a theorem you cannot finish rather than a broken proof. diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/solution/Solution.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..d8a08fbf7d3714d3d2feaaaf6e5f1cba1a3e1be6 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/solution/Solution.lean @@ -0,0 +1,25 @@ +import Mathlib + +noncomputable def a : ℕ → ℝ + | 0 => (2 : ℝ) + | (n + 1) => a n / 2 + (2 : ℝ) + +/-- The sequence stays between 0 and its upper bound. -/ +theorem a_bounds : + ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (4 : ℝ) := by + intro n + induction n with + | zero => norm_num [a] + | succ k ih => + obtain ⟨h0, h1⟩ := ih + simp only [a] + constructor <;> linarith + +/-- The sequence is increasing. -/ +theorem a_monotone : + Monotone a := by + apply monotone_nat_of_le_succ + intro n + have h := (a_bounds n).2 + simp only [a] + linarith diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/solution/solve.sh b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/task.toml b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..42e17ee3f38bec5e7ded1ab60c3f0aa694a5cca7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "real-analysis" +tags = ["real-analysis", "sequence_bounds", "msc-26", "train", "lean4"] +msc = "26" +family = "sequence_bounds" +split = "train" +seed = 54 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/tests/Verify.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/tests/grade.py b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/tests/spec.json b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..0e9888164ffb84fd9342cb21a4d82feffb85c6b4 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\nnoncomputable def a : ℕ → ℝ\n | 0 => (2 : ℝ)\n | (n + 1) => a n / 2 + (2 : ℝ)\n\n/-- The sequence stays between 0 and its upper bound. -/\ntheorem a_bounds :\n ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (4 : ℝ) := by\n sorry\n\n/-- The sequence is increasing. -/\ntheorem a_monotone :\n Monotone a := by\n sorry\n", + "targets": [ + { + "name": "a_bounds", + "weight": 1.0 + }, + { + "name": "a_monotone", + "weight": 2.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/tests/test.sh b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d2-t0054/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/environment/Dockerfile b/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..1aba64c2e105b65a9422d9e37154851f2f3ce08f --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/environment/workdir/Solution.lean @@ -0,0 +1,15 @@ +import Mathlib + +noncomputable def a : ℕ → ℝ + | 0 => (1 / 2 : ℝ) + | (n + 1) => (a n ^ 2 + (8 / 9 : ℝ)) / 2 + +/-- The sequence stays between 0 and the smaller fixed point. -/ +theorem a_bounds : + ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (2 / 3 : ℝ) := by + sorry + +/-- The sequence is increasing. -/ +theorem a_monotone : + Monotone a := by + sorry diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/instruction.md b/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d5884c79bdfa7cfb27255a416edbec3b15d3cf20 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/instruction.md @@ -0,0 +1,12 @@ +# Bound a recursive sequence + +Define a real sequence by \(a_0 = \frac{1}{2}\) and \(a_{n+1} = \dfrac{a_n^2 + \frac{8}{9}}{2}\). Prove that \(0 \le a_n \le \frac{2}{3}\) for every \(n\) (note that \(\frac{2}{3}\) is a fixed point of the recursion), and then that the sequence is monotone (non-decreasing). + +## What to do + +`Solution.lean` in the working directory states 2 theorems in Lean 4 with Mathlib, with `sorry` in place of each proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is the share of the 2 theorems that are proved. If the file does not compile the reward is 0, so leave `sorry` on a theorem you cannot finish rather than a broken proof. diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/solution/Solution.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..047a89b7c50abde708db448b1310e7ab3e5b9643 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/solution/Solution.lean @@ -0,0 +1,29 @@ +import Mathlib + +noncomputable def a : ℕ → ℝ + | 0 => (1 / 2 : ℝ) + | (n + 1) => (a n ^ 2 + (8 / 9 : ℝ)) / 2 + +/-- The sequence stays between 0 and the smaller fixed point. -/ +theorem a_bounds : + ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (2 / 3 : ℝ) := by + intro n + induction n with + | zero => norm_num [a] + | succ k ih => + obtain ⟨h0, h1⟩ := ih + have h2 : a k ^ 2 ≤ (2 / 3 : ℝ) ^ 2 := by nlinarith + simp only [a] + constructor + · nlinarith [sq_nonneg (a k)] + · norm_num at h2 ⊢ + linarith + +/-- The sequence is increasing. -/ +theorem a_monotone : + Monotone a := by + apply monotone_nat_of_le_succ + intro n + obtain ⟨h0, h1⟩ := a_bounds n + simp only [a] + nlinarith [mul_nonneg (sub_nonneg.mpr h1) (by linarith : (0 : ℝ) ≤ (4 / 3 : ℝ) - a n)] diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/solution/solve.sh b/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/task.toml b/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0e3f4508f6202e9477f70c1a4efb2f80c3484849 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "real-analysis" +tags = ["real-analysis", "sequence_bounds", "msc-26", "eval", "lean4"] +msc = "26" +family = "sequence_bounds" +split = "eval" +seed = 10022 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/tests/Verify.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/tests/grade.py b/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/tests/spec.json b/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..4fa001ba6fb2ed47826ae8eeb93f01f54d612d12 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\nnoncomputable def a : ℕ → ℝ\n | 0 => (1 / 2 : ℝ)\n | (n + 1) => (a n ^ 2 + (8 / 9 : ℝ)) / 2\n\n/-- The sequence stays between 0 and the smaller fixed point. -/\ntheorem a_bounds :\n ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (2 / 3 : ℝ) := by\n sorry\n\n/-- The sequence is increasing. -/\ntheorem a_monotone :\n Monotone a := by\n sorry\n", + "targets": [ + { + "name": "a_bounds", + "weight": 1.0 + }, + { + "name": "a_monotone", + "weight": 2.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/tests/test.sh b/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-e0022/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/environment/Dockerfile b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..58cf778e68e26ca9d52f0e1da3a57e26174e1b49 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/environment/workdir/Solution.lean @@ -0,0 +1,15 @@ +import Mathlib + +noncomputable def a : ℕ → ℝ + | 0 => (2 / 15 : ℝ) + | (n + 1) => (a n ^ 2 + (16 / 25 : ℝ)) / 2 + +/-- The sequence stays between 0 and the smaller fixed point. -/ +theorem a_bounds : + ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (2 / 5 : ℝ) := by + sorry + +/-- The sequence is increasing. -/ +theorem a_monotone : + Monotone a := by + sorry diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/instruction.md b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..afaf809b333ce478c632a5e1b3a67cc149ec1ae9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/instruction.md @@ -0,0 +1,12 @@ +# Bound a recursive sequence + +Define a real sequence by \(a_0 = \frac{2}{15}\) and \(a_{n+1} = \dfrac{a_n^2 + \frac{16}{25}}{2}\). Prove that \(0 \le a_n \le \frac{2}{5}\) for every \(n\) (note that \(\frac{2}{5}\) is a fixed point of the recursion), and then that the sequence is monotone (non-decreasing). + +## What to do + +`Solution.lean` in the working directory states 2 theorems in Lean 4 with Mathlib, with `sorry` in place of each proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is the share of the 2 theorems that are proved. If the file does not compile the reward is 0, so leave `sorry` on a theorem you cannot finish rather than a broken proof. diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/solution/Solution.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..17b2b6deade6e4b61bfe5d20ffaccb4665c7296a --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/solution/Solution.lean @@ -0,0 +1,29 @@ +import Mathlib + +noncomputable def a : ℕ → ℝ + | 0 => (2 / 15 : ℝ) + | (n + 1) => (a n ^ 2 + (16 / 25 : ℝ)) / 2 + +/-- The sequence stays between 0 and the smaller fixed point. -/ +theorem a_bounds : + ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (2 / 5 : ℝ) := by + intro n + induction n with + | zero => norm_num [a] + | succ k ih => + obtain ⟨h0, h1⟩ := ih + have h2 : a k ^ 2 ≤ (2 / 5 : ℝ) ^ 2 := by nlinarith + simp only [a] + constructor + · nlinarith [sq_nonneg (a k)] + · norm_num at h2 ⊢ + linarith + +/-- The sequence is increasing. -/ +theorem a_monotone : + Monotone a := by + apply monotone_nat_of_le_succ + intro n + obtain ⟨h0, h1⟩ := a_bounds n + simp only [a] + nlinarith [mul_nonneg (sub_nonneg.mpr h1) (by linarith : (0 : ℝ) ≤ (8 / 5 : ℝ) - a n)] diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/solution/solve.sh b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/task.toml b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b428f86f805135726ec168def13b72025a09e2c8 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "real-analysis" +tags = ["real-analysis", "sequence_bounds", "msc-26", "train", "lean4"] +msc = "26" +family = "sequence_bounds" +split = "train" +seed = 22 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/tests/Verify.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/tests/grade.py b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/tests/spec.json b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..1e2c88e8cb97057f134b533b8bd245fad1c871bc --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\nnoncomputable def a : ℕ → ℝ\n | 0 => (2 / 15 : ℝ)\n | (n + 1) => (a n ^ 2 + (16 / 25 : ℝ)) / 2\n\n/-- The sequence stays between 0 and the smaller fixed point. -/\ntheorem a_bounds :\n ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (2 / 5 : ℝ) := by\n sorry\n\n/-- The sequence is increasing. -/\ntheorem a_monotone :\n Monotone a := by\n sorry\n", + "targets": [ + { + "name": "a_bounds", + "weight": 1.0 + }, + { + "name": "a_monotone", + "weight": 2.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/tests/test.sh b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0022/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/environment/Dockerfile b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..e9b92562e5acc4049975a72460acabbce83b1bdc --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/environment/workdir/Solution.lean @@ -0,0 +1,15 @@ +import Mathlib + +noncomputable def a : ℕ → ℝ + | 0 => (0 : ℝ) + | (n + 1) => (a n ^ 2 + (7 / 16 : ℝ)) / 2 + +/-- The sequence stays between 0 and the smaller fixed point. -/ +theorem a_bounds : + ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (1 / 4 : ℝ) := by + sorry + +/-- The sequence is increasing. -/ +theorem a_monotone : + Monotone a := by + sorry diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/instruction.md b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..976a60a5d00bbaa213e7d2e1bcf7fa2ef4d23247 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/instruction.md @@ -0,0 +1,12 @@ +# Bound a recursive sequence + +Define a real sequence by \(a_0 = 0\) and \(a_{n+1} = \dfrac{a_n^2 + \frac{7}{16}}{2}\). Prove that \(0 \le a_n \le \frac{1}{4}\) for every \(n\) (note that \(\frac{1}{4}\) is a fixed point of the recursion), and then that the sequence is monotone (non-decreasing). + +## What to do + +`Solution.lean` in the working directory states 2 theorems in Lean 4 with Mathlib, with `sorry` in place of each proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is the share of the 2 theorems that are proved. If the file does not compile the reward is 0, so leave `sorry` on a theorem you cannot finish rather than a broken proof. diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/solution/Solution.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..5ae1390d0c07fd36aa0f5e37edfda12d7bc0969c --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/solution/Solution.lean @@ -0,0 +1,29 @@ +import Mathlib + +noncomputable def a : ℕ → ℝ + | 0 => (0 : ℝ) + | (n + 1) => (a n ^ 2 + (7 / 16 : ℝ)) / 2 + +/-- The sequence stays between 0 and the smaller fixed point. -/ +theorem a_bounds : + ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (1 / 4 : ℝ) := by + intro n + induction n with + | zero => norm_num [a] + | succ k ih => + obtain ⟨h0, h1⟩ := ih + have h2 : a k ^ 2 ≤ (1 / 4 : ℝ) ^ 2 := by nlinarith + simp only [a] + constructor + · nlinarith [sq_nonneg (a k)] + · norm_num at h2 ⊢ + linarith + +/-- The sequence is increasing. -/ +theorem a_monotone : + Monotone a := by + apply monotone_nat_of_le_succ + intro n + obtain ⟨h0, h1⟩ := a_bounds n + simp only [a] + nlinarith [mul_nonneg (sub_nonneg.mpr h1) (by linarith : (0 : ℝ) ≤ (7 / 4 : ℝ) - a n)] diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/solution/solve.sh b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/task.toml b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ef9c06926ab2f93b83b4117c0e8ff03dea5b956d --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "real-analysis" +tags = ["real-analysis", "sequence_bounds", "msc-26", "train", "lean4"] +msc = "26" +family = "sequence_bounds" +split = "train" +seed = 46 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/tests/Verify.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/tests/grade.py b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/tests/spec.json b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..b073d4042e0ded744f4fd6f394135b82f6fc5336 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\nnoncomputable def a : ℕ → ℝ\n | 0 => (0 : ℝ)\n | (n + 1) => (a n ^ 2 + (7 / 16 : ℝ)) / 2\n\n/-- The sequence stays between 0 and the smaller fixed point. -/\ntheorem a_bounds :\n ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (1 / 4 : ℝ) := by\n sorry\n\n/-- The sequence is increasing. -/\ntheorem a_monotone :\n Monotone a := by\n sorry\n", + "targets": [ + { + "name": "a_bounds", + "weight": 1.0 + }, + { + "name": "a_monotone", + "weight": 2.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/tests/test.sh b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0046/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/environment/Dockerfile b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..1aba64c2e105b65a9422d9e37154851f2f3ce08f --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/environment/workdir/Solution.lean @@ -0,0 +1,15 @@ +import Mathlib + +noncomputable def a : ℕ → ℝ + | 0 => (1 / 2 : ℝ) + | (n + 1) => (a n ^ 2 + (8 / 9 : ℝ)) / 2 + +/-- The sequence stays between 0 and the smaller fixed point. -/ +theorem a_bounds : + ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (2 / 3 : ℝ) := by + sorry + +/-- The sequence is increasing. -/ +theorem a_monotone : + Monotone a := by + sorry diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/instruction.md b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d5884c79bdfa7cfb27255a416edbec3b15d3cf20 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/instruction.md @@ -0,0 +1,12 @@ +# Bound a recursive sequence + +Define a real sequence by \(a_0 = \frac{1}{2}\) and \(a_{n+1} = \dfrac{a_n^2 + \frac{8}{9}}{2}\). Prove that \(0 \le a_n \le \frac{2}{3}\) for every \(n\) (note that \(\frac{2}{3}\) is a fixed point of the recursion), and then that the sequence is monotone (non-decreasing). + +## What to do + +`Solution.lean` in the working directory states 2 theorems in Lean 4 with Mathlib, with `sorry` in place of each proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is the share of the 2 theorems that are proved. If the file does not compile the reward is 0, so leave `sorry` on a theorem you cannot finish rather than a broken proof. diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/solution/Solution.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..047a89b7c50abde708db448b1310e7ab3e5b9643 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/solution/Solution.lean @@ -0,0 +1,29 @@ +import Mathlib + +noncomputable def a : ℕ → ℝ + | 0 => (1 / 2 : ℝ) + | (n + 1) => (a n ^ 2 + (8 / 9 : ℝ)) / 2 + +/-- The sequence stays between 0 and the smaller fixed point. -/ +theorem a_bounds : + ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (2 / 3 : ℝ) := by + intro n + induction n with + | zero => norm_num [a] + | succ k ih => + obtain ⟨h0, h1⟩ := ih + have h2 : a k ^ 2 ≤ (2 / 3 : ℝ) ^ 2 := by nlinarith + simp only [a] + constructor + · nlinarith [sq_nonneg (a k)] + · norm_num at h2 ⊢ + linarith + +/-- The sequence is increasing. -/ +theorem a_monotone : + Monotone a := by + apply monotone_nat_of_le_succ + intro n + obtain ⟨h0, h1⟩ := a_bounds n + simp only [a] + nlinarith [mul_nonneg (sub_nonneg.mpr h1) (by linarith : (0 : ℝ) ≤ (4 / 3 : ℝ) - a n)] diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/solution/solve.sh b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/task.toml b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..697a757bad20d1aecdc45ece8fa0e045cafca9c1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "real-analysis" +tags = ["real-analysis", "sequence_bounds", "msc-26", "train", "lean4"] +msc = "26" +family = "sequence_bounds" +split = "train" +seed = 70 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/tests/Verify.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/tests/grade.py b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/tests/spec.json b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..4fa001ba6fb2ed47826ae8eeb93f01f54d612d12 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\nnoncomputable def a : ℕ → ℝ\n | 0 => (1 / 2 : ℝ)\n | (n + 1) => (a n ^ 2 + (8 / 9 : ℝ)) / 2\n\n/-- The sequence stays between 0 and the smaller fixed point. -/\ntheorem a_bounds :\n ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (2 / 3 : ℝ) := by\n sorry\n\n/-- The sequence is increasing. -/\ntheorem a_monotone :\n Monotone a := by\n sorry\n", + "targets": [ + { + "name": "a_bounds", + "weight": 1.0 + }, + { + "name": "a_monotone", + "weight": 2.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/tests/test.sh b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0070/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/environment/Dockerfile b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..9e46e60c4c921cd443ed13158e010e52f2b6124c --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/environment/workdir/Solution.lean @@ -0,0 +1,15 @@ +import Mathlib + +noncomputable def a : ℕ → ℝ + | 0 => (1 / 4 : ℝ) + | (n + 1) => (a n ^ 2 + (7 / 16 : ℝ)) / 2 + +/-- The sequence stays between 0 and the smaller fixed point. -/ +theorem a_bounds : + ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (1 / 4 : ℝ) := by + sorry + +/-- The sequence is increasing. -/ +theorem a_monotone : + Monotone a := by + sorry diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/instruction.md b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bb499d4e85ecca91c170aa7e5830aee75df13de6 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/instruction.md @@ -0,0 +1,12 @@ +# Bound a recursive sequence + +Define a real sequence by \(a_0 = \frac{1}{4}\) and \(a_{n+1} = \dfrac{a_n^2 + \frac{7}{16}}{2}\). Prove that \(0 \le a_n \le \frac{1}{4}\) for every \(n\) (note that \(\frac{1}{4}\) is a fixed point of the recursion), and then that the sequence is monotone (non-decreasing). + +## What to do + +`Solution.lean` in the working directory states 2 theorems in Lean 4 with Mathlib, with `sorry` in place of each proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is the share of the 2 theorems that are proved. If the file does not compile the reward is 0, so leave `sorry` on a theorem you cannot finish rather than a broken proof. diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/solution/Solution.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..19f9032e96dd1b6d6117fd30da683f4ad3044536 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/solution/Solution.lean @@ -0,0 +1,29 @@ +import Mathlib + +noncomputable def a : ℕ → ℝ + | 0 => (1 / 4 : ℝ) + | (n + 1) => (a n ^ 2 + (7 / 16 : ℝ)) / 2 + +/-- The sequence stays between 0 and the smaller fixed point. -/ +theorem a_bounds : + ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (1 / 4 : ℝ) := by + intro n + induction n with + | zero => norm_num [a] + | succ k ih => + obtain ⟨h0, h1⟩ := ih + have h2 : a k ^ 2 ≤ (1 / 4 : ℝ) ^ 2 := by nlinarith + simp only [a] + constructor + · nlinarith [sq_nonneg (a k)] + · norm_num at h2 ⊢ + linarith + +/-- The sequence is increasing. -/ +theorem a_monotone : + Monotone a := by + apply monotone_nat_of_le_succ + intro n + obtain ⟨h0, h1⟩ := a_bounds n + simp only [a] + nlinarith [mul_nonneg (sub_nonneg.mpr h1) (by linarith : (0 : ℝ) ≤ (7 / 4 : ℝ) - a n)] diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/solution/solve.sh b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/task.toml b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ca94879a82f21bbabd9ebc0aa9fdf9f4b8725541 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "real-analysis" +tags = ["real-analysis", "sequence_bounds", "msc-26", "train", "lean4"] +msc = "26" +family = "sequence_bounds" +split = "train" +seed = 82 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/tests/Verify.lean b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/tests/grade.py b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/tests/spec.json b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..22a460917544473641288286a2d1e5eaf37244bf --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\nnoncomputable def a : ℕ → ℝ\n | 0 => (1 / 4 : ℝ)\n | (n + 1) => (a n ^ 2 + (7 / 16 : ℝ)) / 2\n\n/-- The sequence stays between 0 and the smaller fixed point. -/\ntheorem a_bounds :\n ∀ n : ℕ, 0 ≤ a n ∧ a n ≤ (1 / 4 : ℝ) := by\n sorry\n\n/-- The sequence is increasing. -/\ntheorem a_monotone :\n Monotone a := by\n sorry\n", + "targets": [ + { + "name": "a_bounds", + "weight": 1.0 + }, + { + "name": "a_monotone", + "weight": 2.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/tests/test.sh b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-sequence_bounds-d3-t0082/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/environment/Dockerfile b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..89f2af954d0a80e910a291c3e8c5c54873840c50 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A bound that does not depend on the point x. -/ +theorem uniform_bound : + ∀ n : ℕ, ∀ x ∈ Set.Icc (-(2 / 5 : ℝ)) (2 / 5 : ℝ), |3 * x ^ (n + 1)| ≤ 3 * (2 / 5 : ℝ) ^ (n + 1) := by + sorry diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/instruction.md b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a177704b83b1047963fd21557dabd85962f3892f --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/instruction.md @@ -0,0 +1,12 @@ +# Prove a uniform bound + +Prove that for every natural number \(n\) and every real \(x\) with \(-\frac{2}{5} \le x \le \frac{2}{5}\), \[|3\,x^{n+1}| \le 3 \cdot \frac{2}{5}^{n+1}.\] + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/solution/Solution.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..7276eacd428ceeda24f6fc802c1d9f89e322e5aa --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/solution/Solution.lean @@ -0,0 +1,10 @@ +import Mathlib + +/-- A bound that does not depend on the point x. -/ +theorem uniform_bound : + ∀ n : ℕ, ∀ x ∈ Set.Icc (-(2 / 5 : ℝ)) (2 / 5 : ℝ), |3 * x ^ (n + 1)| ≤ 3 * (2 / 5 : ℝ) ^ (n + 1) := by + intro n x hx + rw [abs_mul, abs_pow, show |((3 : ℝ))| = (3 : ℝ) by norm_num] + have hx' : |x| ≤ (2 / 5 : ℝ) := abs_le.mpr ⟨hx.1, hx.2⟩ + have := pow_le_pow_left₀ (abs_nonneg x) hx' (n + 1) + linarith diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/solution/solve.sh b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/task.toml b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2b6664557b0406b0d9fde5dc1f0e4e3a03ea8ece --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "real-analysis" +tags = ["real-analysis", "uniform_bounds", "msc-26", "train", "lean4"] +msc = "26" +family = "uniform_bounds" +split = "train" +seed = 15 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/tests/Verify.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/tests/grade.py b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/tests/spec.json b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..dc232bcb3532a9970646585e110343befe509072 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A bound that does not depend on the point x. -/\ntheorem uniform_bound :\n ∀ n : ℕ, ∀ x ∈ Set.Icc (-(2 / 5 : ℝ)) (2 / 5 : ℝ), |3 * x ^ (n + 1)| ≤ 3 * (2 / 5 : ℝ) ^ (n + 1) := by\n sorry\n", + "targets": [ + { + "name": "uniform_bound", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/tests/test.sh b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0015/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/environment/Dockerfile b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..d79c36e174f9904b9a35049118d26a94f87358e9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A bound that does not depend on the point x. -/ +theorem uniform_bound : + ∀ n : ℕ, ∀ x ∈ Set.Icc (-(3 / 5 : ℝ)) (3 / 5 : ℝ), |3 * x ^ (n + 1)| ≤ 3 * (3 / 5 : ℝ) ^ (n + 1) := by + sorry diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/instruction.md b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..04870685d3127cdde81aee29e67e7f5470476904 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/instruction.md @@ -0,0 +1,12 @@ +# Prove a uniform bound + +Prove that for every natural number \(n\) and every real \(x\) with \(-\frac{3}{5} \le x \le \frac{3}{5}\), \[|3\,x^{n+1}| \le 3 \cdot \frac{3}{5}^{n+1}.\] + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/solution/Solution.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..088c36613e25fd624ac92ccf1c9127364eac4433 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/solution/Solution.lean @@ -0,0 +1,10 @@ +import Mathlib + +/-- A bound that does not depend on the point x. -/ +theorem uniform_bound : + ∀ n : ℕ, ∀ x ∈ Set.Icc (-(3 / 5 : ℝ)) (3 / 5 : ℝ), |3 * x ^ (n + 1)| ≤ 3 * (3 / 5 : ℝ) ^ (n + 1) := by + intro n x hx + rw [abs_mul, abs_pow, show |((3 : ℝ))| = (3 : ℝ) by norm_num] + have hx' : |x| ≤ (3 / 5 : ℝ) := abs_le.mpr ⟨hx.1, hx.2⟩ + have := pow_le_pow_left₀ (abs_nonneg x) hx' (n + 1) + linarith diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/solution/solve.sh b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/task.toml b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fb2874062ffdf7901bca325f0eace97bb3c33475 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "real-analysis" +tags = ["real-analysis", "uniform_bounds", "msc-26", "train", "lean4"] +msc = "26" +family = "uniform_bounds" +split = "train" +seed = 39 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/tests/Verify.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/tests/grade.py b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/tests/spec.json b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..d2668325db7649dbf58fc28550097bd8c8fed22e --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A bound that does not depend on the point x. -/\ntheorem uniform_bound :\n ∀ n : ℕ, ∀ x ∈ Set.Icc (-(3 / 5 : ℝ)) (3 / 5 : ℝ), |3 * x ^ (n + 1)| ≤ 3 * (3 / 5 : ℝ) ^ (n + 1) := by\n sorry\n", + "targets": [ + { + "name": "uniform_bound", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/tests/test.sh b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0039/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/environment/Dockerfile b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..5942046ae23f329852bca6dcabf323349b24a989 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A bound that does not depend on the point x. -/ +theorem uniform_bound : + ∀ n : ℕ, ∀ x ∈ Set.Icc (-(3 / 5 : ℝ)) (3 / 5 : ℝ), |8 * x ^ (n + 1)| ≤ 8 * (3 / 5 : ℝ) ^ (n + 1) := by + sorry diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/instruction.md b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6f0d39c2a2e0d19a51cc9d10ab40f53fe2be193a --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/instruction.md @@ -0,0 +1,12 @@ +# Prove a uniform bound + +Prove that for every natural number \(n\) and every real \(x\) with \(-\frac{3}{5} \le x \le \frac{3}{5}\), \[|8\,x^{n+1}| \le 8 \cdot \frac{3}{5}^{n+1}.\] + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/solution/Solution.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..997d647c6bf85d6de2c7003bd4aafa1101fed541 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/solution/Solution.lean @@ -0,0 +1,10 @@ +import Mathlib + +/-- A bound that does not depend on the point x. -/ +theorem uniform_bound : + ∀ n : ℕ, ∀ x ∈ Set.Icc (-(3 / 5 : ℝ)) (3 / 5 : ℝ), |8 * x ^ (n + 1)| ≤ 8 * (3 / 5 : ℝ) ^ (n + 1) := by + intro n x hx + rw [abs_mul, abs_pow, show |((8 : ℝ))| = (8 : ℝ) by norm_num] + have hx' : |x| ≤ (3 / 5 : ℝ) := abs_le.mpr ⟨hx.1, hx.2⟩ + have := pow_le_pow_left₀ (abs_nonneg x) hx' (n + 1) + linarith diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/solution/solve.sh b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/task.toml b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fbe9c49f3554c0bc5585caabaff9fcc6a5452af3 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "real-analysis" +tags = ["real-analysis", "uniform_bounds", "msc-26", "train", "lean4"] +msc = "26" +family = "uniform_bounds" +split = "train" +seed = 63 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/tests/Verify.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/tests/grade.py b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/tests/spec.json b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..7a89167f216fdfe12e40d2109273d2d7fff8637a --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A bound that does not depend on the point x. -/\ntheorem uniform_bound :\n ∀ n : ℕ, ∀ x ∈ Set.Icc (-(3 / 5 : ℝ)) (3 / 5 : ℝ), |8 * x ^ (n + 1)| ≤ 8 * (3 / 5 : ℝ) ^ (n + 1) := by\n sorry\n", + "targets": [ + { + "name": "uniform_bound", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/tests/test.sh b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d1-t0063/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/environment/Dockerfile b/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..cc5d9a9d3897251dcf17c652424b2b733f314c7d --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A bound on partial geometric sums that does not depend on n or x. -/ +theorem uniform_bound : + ∀ n : ℕ, ∀ x ∈ Set.Icc (0 : ℝ) (1 / 4 : ℝ), ∑ i ∈ Finset.range n, x ^ i ≤ 1 / (1 - (1 / 4 : ℝ)) := by + sorry diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/instruction.md b/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c7839994d45c2a0b0be80757b2bd41335802879e --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/instruction.md @@ -0,0 +1,12 @@ +# Prove a uniform bound + +Prove that for every natural number \(n\) and every real \(x\) with \(0 \le x \le \frac{1}{4}\), \[\sum_{i=0}^{n-1} x^{i} \le \frac{1}{1 - \frac{1}{4}}.\] The sum is empty when \(n = 0\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/solution/Solution.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..c7710e265b3611e2f53cc4f40bcddd5ea359bd92 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/solution/Solution.lean @@ -0,0 +1,15 @@ +import Mathlib + +/-- A bound on partial geometric sums that does not depend on n or x. -/ +theorem uniform_bound : + ∀ n : ℕ, ∀ x ∈ Set.Icc (0 : ℝ) (1 / 4 : ℝ), ∑ i ∈ Finset.range n, x ^ i ≤ 1 / (1 - (1 / 4 : ℝ)) := by + intro n x hx + have hq : ((1 / 4 : ℝ) : ℝ) ≠ 1 := by norm_num + have h1 : ∑ i ∈ Finset.range n, x ^ i ≤ ∑ i ∈ Finset.range n, ((1 / 4 : ℝ) : ℝ) ^ i := + Finset.sum_le_sum fun i _ => pow_le_pow_left₀ hx.1 hx.2 i + have h2 : ∑ i ∈ Finset.range n, ((1 / 4 : ℝ) : ℝ) ^ i = (1 - (1 / 4 : ℝ) ^ n) / (1 - (1 / 4 : ℝ)) := by + rw [geom_sum_eq hq n, ← neg_sub, ← neg_sub 1, neg_div_neg_eq] + have h3 : (1 - (1 / 4 : ℝ) ^ n) / (1 - (1 / 4 : ℝ)) ≤ 1 / (1 - (1 / 4 : ℝ)) := by + have : (0 : ℝ) < (1 / 4 : ℝ) ^ n := by positivity + apply div_le_div_of_nonneg_right (by linarith) (by norm_num) + linarith diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/solution/solve.sh b/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/task.toml b/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..08d6110563a62271d595cb67e87773013c2b5605 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "real-analysis" +tags = ["real-analysis", "uniform_bounds", "msc-26", "eval", "lean4"] +msc = "26" +family = "uniform_bounds" +split = "eval" +seed = 10007 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/tests/Verify.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/tests/grade.py b/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/tests/spec.json b/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..150ff2bb06b841911a0edb47a946219f189b6b16 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A bound on partial geometric sums that does not depend on n or x. -/\ntheorem uniform_bound :\n ∀ n : ℕ, ∀ x ∈ Set.Icc (0 : ℝ) (1 / 4 : ℝ), ∑ i ∈ Finset.range n, x ^ i ≤ 1 / (1 - (1 / 4 : ℝ)) := by\n sorry\n", + "targets": [ + { + "name": "uniform_bound", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/tests/test.sh b/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-e0007/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/environment/Dockerfile b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..7221fd13b566a6bed742360d5ea7b6f73dd9739d --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A bound on partial geometric sums that does not depend on n or x. -/ +theorem uniform_bound : + ∀ n : ℕ, ∀ x ∈ Set.Icc (0 : ℝ) (2 / 3 : ℝ), ∑ i ∈ Finset.range n, x ^ i ≤ 1 / (1 - (2 / 3 : ℝ)) := by + sorry diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/instruction.md b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b75d3d7b0463eb314a487b4a8f5f1930f0a4875f --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/instruction.md @@ -0,0 +1,12 @@ +# Prove a uniform bound + +Prove that for every natural number \(n\) and every real \(x\) with \(0 \le x \le \frac{2}{3}\), \[\sum_{i=0}^{n-1} x^{i} \le \frac{1}{1 - \frac{2}{3}}.\] The sum is empty when \(n = 0\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/solution/Solution.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..3b0e59cdfac7e9cbe91efd3c737e1479c1182444 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/solution/Solution.lean @@ -0,0 +1,15 @@ +import Mathlib + +/-- A bound on partial geometric sums that does not depend on n or x. -/ +theorem uniform_bound : + ∀ n : ℕ, ∀ x ∈ Set.Icc (0 : ℝ) (2 / 3 : ℝ), ∑ i ∈ Finset.range n, x ^ i ≤ 1 / (1 - (2 / 3 : ℝ)) := by + intro n x hx + have hq : ((2 / 3 : ℝ) : ℝ) ≠ 1 := by norm_num + have h1 : ∑ i ∈ Finset.range n, x ^ i ≤ ∑ i ∈ Finset.range n, ((2 / 3 : ℝ) : ℝ) ^ i := + Finset.sum_le_sum fun i _ => pow_le_pow_left₀ hx.1 hx.2 i + have h2 : ∑ i ∈ Finset.range n, ((2 / 3 : ℝ) : ℝ) ^ i = (1 - (2 / 3 : ℝ) ^ n) / (1 - (2 / 3 : ℝ)) := by + rw [geom_sum_eq hq n, ← neg_sub, ← neg_sub 1, neg_div_neg_eq] + have h3 : (1 - (2 / 3 : ℝ) ^ n) / (1 - (2 / 3 : ℝ)) ≤ 1 / (1 - (2 / 3 : ℝ)) := by + have : (0 : ℝ) < (2 / 3 : ℝ) ^ n := by positivity + apply div_le_div_of_nonneg_right (by linarith) (by norm_num) + linarith diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/solution/solve.sh b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/task.toml b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5986d3eb634d43bc22301820bf6eb48117fc2b9d --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "real-analysis" +tags = ["real-analysis", "uniform_bounds", "msc-26", "train", "lean4"] +msc = "26" +family = "uniform_bounds" +split = "train" +seed = 79 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/tests/Verify.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/tests/grade.py b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/tests/spec.json b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..e7d9a5c7b52161b281a9ae0db83d169de19f15e2 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A bound on partial geometric sums that does not depend on n or x. -/\ntheorem uniform_bound :\n ∀ n : ℕ, ∀ x ∈ Set.Icc (0 : ℝ) (2 / 3 : ℝ), ∑ i ∈ Finset.range n, x ^ i ≤ 1 / (1 - (2 / 3 : ℝ)) := by\n sorry\n", + "targets": [ + { + "name": "uniform_bound", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/tests/test.sh b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d2-t0079/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/environment/Dockerfile b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..868283cf0562c683f35f01c1e0c2754b9ef4d060 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Uniform convergence of a geometric sequence on an interval. -/ +theorem uniform_convergence : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, ∀ x : ℝ, |x| ≤ (2 / 3 : ℝ) → |3 * x ^ n| < ε := by + sorry diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/instruction.md b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..95066e37e68b8be58bbb6a0b2f379db6953a4192 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/instruction.md @@ -0,0 +1,12 @@ +# Prove a uniform bound + +Prove that \(c\,x^n\) with \(c = 3\) tends to \(0\) uniformly on \([-\frac{2}{3}, \frac{2}{3}]\): for every \(\varepsilon > 0\) there is \(N\) such that \(|3\,x^n| < \varepsilon\) for all \(n \ge N\) and all real \(x\) with \(|x| \le \frac{2}{3}\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/solution/Solution.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..271f6a4db0c4135daeb428c77caeb848b0e2e048 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/solution/Solution.lean @@ -0,0 +1,14 @@ +import Mathlib + +/-- Uniform convergence of a geometric sequence on an interval. -/ +theorem uniform_convergence : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, ∀ x : ℝ, |x| ≤ (2 / 3 : ℝ) → |3 * x ^ n| < ε := by + intro ε hε + obtain ⟨N, hN⟩ := exists_pow_lt_of_lt_one (div_pos hε (by norm_num : (0 : ℝ) < (3 : ℝ))) (by norm_num : ((2 / 3 : ℝ) : ℝ) < 1) + refine ⟨N, fun n hn x hx => ?_⟩ + rw [abs_mul, abs_pow, show |((3 : ℝ))| = (3 : ℝ) by norm_num] + have h1 : |x| ^ n ≤ ((2 / 3 : ℝ) : ℝ) ^ n := pow_le_pow_left₀ (abs_nonneg x) hx n + have h2 : ((2 / 3 : ℝ) : ℝ) ^ n ≤ ((2 / 3 : ℝ) : ℝ) ^ N := pow_le_pow_of_le_one (by norm_num) (by norm_num) hn + have h3 : ((2 / 3 : ℝ) : ℝ) ^ N < ε / (3 : ℝ) := hN + rw [lt_div_iff₀ (by norm_num)] at h3 + nlinarith diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/solution/solve.sh b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/task.toml b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bfa3a11c5e298bc62592bb8841294aa43468e8df --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "real-analysis" +tags = ["real-analysis", "uniform_bounds", "msc-26", "train", "lean4"] +msc = "26" +family = "uniform_bounds" +split = "train" +seed = 47 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/tests/Verify.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/tests/grade.py b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/tests/spec.json b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..ce951784d1cb281adb0b63710c336d605dcc89dd --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- Uniform convergence of a geometric sequence on an interval. -/\ntheorem uniform_convergence :\n ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, ∀ x : ℝ, |x| ≤ (2 / 3 : ℝ) → |3 * x ^ n| < ε := by\n sorry\n", + "targets": [ + { + "name": "uniform_convergence", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/tests/test.sh b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0047/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/environment/Dockerfile b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..a991392345ff43dec1afd72b8cba466a582f36f7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Uniform convergence of a geometric sequence on an interval. -/ +theorem uniform_convergence : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, ∀ x : ℝ, |x| ≤ (1 / 4 : ℝ) → |3 * x ^ n| < ε := by + sorry diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/instruction.md b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c5f08270342f06bbfb47162560c36a61ef977729 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/instruction.md @@ -0,0 +1,12 @@ +# Prove a uniform bound + +Prove that \(c\,x^n\) with \(c = 3\) tends to \(0\) uniformly on \([-\frac{1}{4}, \frac{1}{4}]\): for every \(\varepsilon > 0\) there is \(N\) such that \(|3\,x^n| < \varepsilon\) for all \(n \ge N\) and all real \(x\) with \(|x| \le \frac{1}{4}\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/solution/Solution.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..cc5baadf21a58860a873293ccfe82412f25a2af0 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/solution/Solution.lean @@ -0,0 +1,14 @@ +import Mathlib + +/-- Uniform convergence of a geometric sequence on an interval. -/ +theorem uniform_convergence : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, ∀ x : ℝ, |x| ≤ (1 / 4 : ℝ) → |3 * x ^ n| < ε := by + intro ε hε + obtain ⟨N, hN⟩ := exists_pow_lt_of_lt_one (div_pos hε (by norm_num : (0 : ℝ) < (3 : ℝ))) (by norm_num : ((1 / 4 : ℝ) : ℝ) < 1) + refine ⟨N, fun n hn x hx => ?_⟩ + rw [abs_mul, abs_pow, show |((3 : ℝ))| = (3 : ℝ) by norm_num] + have h1 : |x| ^ n ≤ ((1 / 4 : ℝ) : ℝ) ^ n := pow_le_pow_left₀ (abs_nonneg x) hx n + have h2 : ((1 / 4 : ℝ) : ℝ) ^ n ≤ ((1 / 4 : ℝ) : ℝ) ^ N := pow_le_pow_of_le_one (by norm_num) (by norm_num) hn + have h3 : ((1 / 4 : ℝ) : ℝ) ^ N < ε / (3 : ℝ) := hN + rw [lt_div_iff₀ (by norm_num)] at h3 + nlinarith diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/solution/solve.sh b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/task.toml b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3c0636c413b96fa95165c75fee363c5d6497b7b0 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "real-analysis" +tags = ["real-analysis", "uniform_bounds", "msc-26", "train", "lean4"] +msc = "26" +family = "uniform_bounds" +split = "train" +seed = 71 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/tests/Verify.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/tests/grade.py b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/tests/spec.json b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..d44ddbc47633cfd9d3947f0806deaba78859ce44 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- Uniform convergence of a geometric sequence on an interval. -/\ntheorem uniform_convergence :\n ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, ∀ x : ℝ, |x| ≤ (1 / 4 : ℝ) → |3 * x ^ n| < ε := by\n sorry\n", + "targets": [ + { + "name": "uniform_convergence", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/tests/test.sh b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0071/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/environment/Dockerfile b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/environment/workdir/Solution.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..f009ced467aa7c85c0c2aa413bda2eda00c0a492 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Uniform convergence of a geometric sequence on an interval. -/ +theorem uniform_convergence : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, ∀ x : ℝ, |x| ≤ (3 / 5 : ℝ) → |5 * x ^ n| < ε := by + sorry diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/instruction.md b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f64d57f4515d79eb888c5fa4d2cfa6169d20deb5 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/instruction.md @@ -0,0 +1,12 @@ +# Prove a uniform bound + +Prove that \(c\,x^n\) with \(c = 5\) tends to \(0\) uniformly on \([-\frac{3}{5}, \frac{3}{5}]\): for every \(\varepsilon > 0\) there is \(N\) such that \(|5\,x^n| < \varepsilon\) for all \(n \ge N\) and all real \(x\) with \(|x| \le \frac{3}{5}\). + +## What to do + +`Solution.lean` in the working directory states the theorem in Lean 4 with Mathlib, with `sorry` in place of the proof. Replace every `sorry` with a proof. + +- Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions. +- Check your work with `lake env lean Solution.lean` (run it inside `/opt/arena/lean`, giving the full path to the file). It must compile without errors. +- A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`. +- The reward is 1 if the theorem is proved and 0 otherwise. diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/solution/Solution.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..b5ad00ffafacc19b6c57a5af92bfa6d89f3e1b9a --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/solution/Solution.lean @@ -0,0 +1,14 @@ +import Mathlib + +/-- Uniform convergence of a geometric sequence on an interval. -/ +theorem uniform_convergence : + ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, ∀ x : ℝ, |x| ≤ (3 / 5 : ℝ) → |5 * x ^ n| < ε := by + intro ε hε + obtain ⟨N, hN⟩ := exists_pow_lt_of_lt_one (div_pos hε (by norm_num : (0 : ℝ) < (5 : ℝ))) (by norm_num : ((3 / 5 : ℝ) : ℝ) < 1) + refine ⟨N, fun n hn x hx => ?_⟩ + rw [abs_mul, abs_pow, show |((5 : ℝ))| = (5 : ℝ) by norm_num] + have h1 : |x| ^ n ≤ ((3 / 5 : ℝ) : ℝ) ^ n := pow_le_pow_left₀ (abs_nonneg x) hx n + have h2 : ((3 / 5 : ℝ) : ℝ) ^ n ≤ ((3 / 5 : ℝ) : ℝ) ^ N := pow_le_pow_of_le_one (by norm_num) (by norm_num) hn + have h3 : ((3 / 5 : ℝ) : ℝ) ^ N < ε / (5 : ℝ) := hN + rw [lt_div_iff₀ (by norm_num)] at h3 + nlinarith diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/solution/solve.sh b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/task.toml b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b7613fbd190235a15038886cec673361478dbf22 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "real-analysis" +tags = ["real-analysis", "uniform_bounds", "msc-26", "train", "lean4"] +msc = "26" +family = "uniform_bounds" +split = "train" +seed = 83 + +[verifier] +timeout_sec = 900.0 + +[agent] +timeout_sec = 1800.0 + +[environment] +build_timeout_sec = 1800.0 +cpus = 2 +memory_mb = 6144 +storage_mb = 10240 +allow_internet = false diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/tests/Verify.lean b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/tests/Verify.lean @@ -0,0 +1,135 @@ +/- +Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for. + + lean --run Verify.lean [--free a,b] [--native] ... + +`--free a,b` names definitions the task asks the solver to write: their type must match the +reference, their value is the solver's own. `--native` additionally accepts the axioms that +`native_decide` introduces; it is used only for hidden test theorems the grader itself proves. + +Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only +`Lean`, never the submission, so nothing the submission declares (notation, macros, instances) +can change how the check itself is read. It reads the reference module's constants from its .olean, imports the +submission as an environment, and compares kernel terms: + + 1. every non-target constant the reference module declares (the task's own definitions) must be + present in the submission with the same kind, type and value; + 2. every target must be present with exactly the reference type; + 3. the proof of every target may depend only on the three standard axioms. + +It prints one JSON object per target and exits 0. The caller turns that into a reward. +-/ +import Lean +open Lean + +def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound] + +/-- All axioms a constant depends on, found by walking every constant it mentions. -/ +partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do + let mut seen : NameSet := {} + let mut todo : Array Name := #[root] + let mut out : Array Name := #[] + while h : todo.size > 0 do + let c := todo[todo.size - 1] + todo := todo.pop + if seen.contains c then continue + seen := seen.insert c + match env.find? c with + | none => out := out.push (`missing ++ c) + | some info => + let mut es : Array Expr := #[info.type] + match info with + | .axiomInfo _ => out := out.push c + | .defnInfo v => es := es.push v.value + | .thmInfo v => es := es.push v.value + | .opaqueInfo v => es := es.push v.value + | .ctorInfo v => todo := todo.push v.induct + | .inductInfo v => for k in v.ctors do todo := todo.push k + | .recInfo v => for r in v.rules do es := es.push r.rhs + | .quotInfo _ => pure () + for e in es do + for k in e.getUsedConstants do + if !seen.contains k then todo := todo.push k + return out + +def kindOf : ConstantInfo → String + | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem" + | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive" + | .ctorInfo _ => "constructor" | .recInfo _ => "recursor" + +def valueOf : ConstantInfo → Option Expr + | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value + | _ => none + +def sameDecl (a b : ConstantInfo) : Bool := + kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b + +def jstr (s : String) : String := (Json.str s).compress + +def isNativeAxiom (n : Name) : Bool := + n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler || + n.components.any (fun c => c == `native_decide) + +def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c) + +partial def parseFlags (args : List String) (free : List Name) (native : Bool) : + List Name × Bool × List String := + match args with + | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native + | "--native" :: rest => parseFlags rest free true + | rest => (free, native, rest) + +def main (args : List String) : IO UInt32 := do + let (free, native, args) := parseFlags args [] false + match args with + | refMod :: solMod :: targets => + initSearchPath (← findSysroot) + let refName := refMod.toName + let solName := solMod.toName + let targetNames := targets.map String.toName + -- The reference is read straight from its .olean: that file holds exactly the constants the + -- reference module declares, which is all the comparison needs. Only the submission is imported + -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two. + let (refData, _) ← readModuleData (← findOLean refName) + let mut refMap : Std.HashMap Name ConstantInfo := {} + for i in [0:refData.constNames.size] do + refMap := refMap.insert refData.constNames[i]! refData.constants[i]! + let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0) + -- 1. the task's own definitions are unchanged + let mut tampered : Array Name := #[] + for c in refData.constNames do + if targetNames.contains c then continue + let some r := refMap[c]? | continue + if free.contains c then + match solEnv.find? c with + | some s => + if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c + | none => tampered := tampered.push c + continue + if isUnder free c then continue + match solEnv.find? c with + | some s => if !sameDecl r s then tampered := tampered.push c + | none => tampered := tampered.push c + for t in targetNames do + let mut ok := true + let mut why := "" + match refMap[t]?, solEnv.find? t with + | none, _ => ok := false; why := "target missing from reference" + | _, none => ok := false; why := "theorem not found in the submission" + | some r, some s => + if !tampered.isEmpty then + ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}" + else if kindOf s != "theorem" && kindOf s != "def" then + ok := false; why := s!"declared as {kindOf s}, not proved" + else if r.levelParams != s.levelParams || r.type != s.type then + ok := false; why := "the statement differs from the one asked for" + else + let ax := axiomsOf solEnv t + let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a)) + if !bad.isEmpty then + ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}" + IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}" + return 0 + | _ => + IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] ..." + return 2 diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/tests/grade.py b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/tests/grade.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Grade a Lean submission against a task. Standard library only. + + python3 grade.py --spec spec.json --solution Solution.lean --out + +`spec.json` holds the hidden reference file, the target theorem names and their weights (see +arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as +asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a +second kernel check by `leanchecker`. A submission that does not compile scores 0. + +The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this +file, then /opt/arena/lean. +""" +import argparse, json, os, shutil, subprocess, sys, tempfile, time + +HERE = os.path.dirname(os.path.abspath(__file__)) +TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600")) + +def project(): + for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"): + if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p) + raise SystemExit("Lean project not found; set ARENA_LEAN") + +_lp = {} +def lean_path(proj): + if proj not in _lp: + cache = os.path.join(proj, ".lake", "lean_path.txt") + if os.path.exists(cache): _lp[proj] = open(cache).read().strip() + else: + _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip() + try: open(cache, "w").write(_lp[proj]) + except OSError: pass + return _lp[proj] + +class Slot: + """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir.""" + def __enter__(self): + self.path = None + n = int(os.environ.get("ARENA_SLOTS", "0")) + if not n: return self + d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True) + while True: + for i in range(n): + p = os.path.join(d, "slot%d" % i) + try: + os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self + except FileExistsError: + try: + pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0) + except (OSError, ValueError): + shutil.rmtree(p, ignore_errors=True) # stale + time.sleep(1) + def __exit__(self, *a): + if self.path: shutil.rmtree(self.path, ignore_errors=True) + +def run(cmd, proj, extra_path=None, timeout=TIMEOUT): + env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "") + with Slot(): + try: + r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout) + return r.returncode, (r.stdout + r.stderr) + except subprocess.TimeoutExpired: + return 124, "timed out after %d s" % timeout + +def compile_lean(proj, src, work): + """Compile work/.lean to work/.olean. Returns (ok, messages).""" + olean = os.path.join(work, src + ".olean") + if os.path.exists(olean): os.remove(olean) + code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work) + return code == 0 and os.path.exists(olean), out + +def grade(spec, solution_text, keep=None): + proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-") + os.makedirs(work, exist_ok=True) + targets = spec["targets"]; total = float(sum(t["weight"] for t in targets)) + res = {"reward": 0.0, "stage": "", "targets": [], "log": ""} + def fail(stage, log): + res["stage"] = stage; res["log"] = log[-4000:] + res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets] + return res + try: + open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"]) + open(os.path.join(work, "Solution.lean"), "w").write(solution_text) + ok, out = compile_lean(proj, "Reference", work) + if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out) + ok, out = compile_lean(proj, "Solution", work) + if not ok: return fail("the submission does not compile", out) + code, out = run(["leanchecker", "Solution"], proj, work) + if code != 0: return fail("the submission fails the kernel re-check", out) + sub = "Solution"; flags = [] + if spec.get("tests"): + open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"]) + ok, out = compile_lean(proj, "Tests", work) + if not ok: return fail("the hidden tests do not pass", out) + code, out = run(["leanchecker", "Tests"], proj, work) + if code != 0: return fail("the tests fail the kernel re-check", out) + sub = "Tests"; flags = ["--native"] + if spec.get("free"): flags += ["--free", ",".join(spec["free"])] + verify = os.path.join(HERE, "Verify.lean") + if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean") + code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work) + got = {} + for line in out.splitlines(): + if line.startswith("{"): + try: j = json.loads(line); got[j["target"]] = j + except ValueError: pass + if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out) + res["targets"] = [got[t["name"]] for t in targets] + res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4) + res["stage"] = "graded" + return res + finally: + if not keep: shutil.rmtree(work, ignore_errors=True) + +if __name__ == "__main__": + ap = argparse.ArgumentParser() + ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None) + a = ap.parse_args() + spec = json.load(open(a.spec, encoding="utf-8")) + try: text = open(a.solution, encoding="utf-8").read() + except OSError: text = None + res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""} + print(json.dumps(res, indent=1, ensure_ascii=False)) + if a.out: + os.makedirs(a.out, exist_ok=True) + open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"]) + json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False) diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/tests/spec.json b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..37bd01aac3f79259cbf99af471731deff45fbbaa --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- Uniform convergence of a geometric sequence on an interval. -/\ntheorem uniform_convergence :\n ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, ∀ x : ℝ, |x| ≤ (3 / 5 : ℝ) → |5 * x ^ n| < ε := by\n sorry\n", + "targets": [ + { + "name": "uniform_convergence", + "weight": 1.0 + } + ] +} diff --git a/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/tests/test.sh b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/real-analysis/real-analysis-uniform_bounds-d3-t0083/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +mkdir -p /logs/verifier +python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt