diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..c2942b9dcbe62cd434bcf6409d422a0041ec9588 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/environment/workdir/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The determinant of the product is the product of the determinants. -/ +theorem det_of_product : Matrix.det (!![4, 1; 1, -3] * !![3, 1; 1, 1] : Matrix (Fin 2) (Fin 2) ℤ) = (-26 : ℤ) := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/instruction.md b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..14b8efdf10b83547848ee6b8d637f9d6a71239f9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/instruction.md @@ -0,0 +1,14 @@ +# Determinant and trace of 2x2 matrices + +Prove the following statement. + +Compute the determinant of the product \(\begin{pmatrix} 4 & 1 \\ 1 & -3 \end{pmatrix}\) \(\begin{pmatrix} 3 & 1 \\ 1 & 1 \end{pmatrix}\) of integer matrices. Show that it equals -26. + +## 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/linear-algebra/linear-algebra-det_trace-d1-e0000/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..01489f09888c3bc2f7c335e27bac412779379f82 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/solution/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The determinant of the product is the product of the determinants. -/ +theorem det_of_product : Matrix.det (!![4, 1; 1, -3] * !![3, 1; 1, 1] : Matrix (Fin 2) (Fin 2) ℤ) = (-26 : ℤ) := by + rw [Matrix.det_mul, Matrix.det_fin_two_of, Matrix.det_fin_two_of] + norm_num diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/solution/solve.sh b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/task.toml b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9c48938ddb00f92395749c42b3f56e84c610b641 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "linear-algebra" +tags = ["linear-algebra", "det_trace", "msc-15", "eval", "lean4"] +msc = "15" +family = "det_trace" +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/linear-algebra/linear-algebra-det_trace-d1-e0000/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d1-e0000/tests/grade.py b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d1-e0000/tests/spec.json b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..a38e28efff9dcd67d1937d8a07c002f1767975b5 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The determinant of the product is the product of the determinants. -/\ntheorem det_of_product : Matrix.det (!![4, 1; 1, -3] * !![3, 1; 1, 1] : Matrix (Fin 2) (Fin 2) ℤ) = (-26 : ℤ) := by\n sorry\n", + "targets": [ + { + "name": "det_of_product", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/tests/test.sh b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d1-e0012/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..ef2d966258322e8f733dcab1b64afe948e59de57 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/environment/workdir/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The determinant of the product is the product of the determinants. -/ +theorem det_of_product : Matrix.det (!![3, 1; -2, 2] * !![4, -1; -3, 2] : Matrix (Fin 2) (Fin 2) ℤ) = 40 := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/instruction.md b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..130b085e542ad77a783455578a857a753c768a35 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/instruction.md @@ -0,0 +1,14 @@ +# Determinant and trace of 2x2 matrices + +Prove the following statement. + +Compute the determinant of the product \(\begin{pmatrix} 3 & 1 \\ -2 & 2 \end{pmatrix}\) \(\begin{pmatrix} 4 & -1 \\ -3 & 2 \end{pmatrix}\) of integer matrices. Show that it equals 40. + +## 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/linear-algebra/linear-algebra-det_trace-d1-e0012/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..3130e8ffd54f977f20105ace6a195387b0a60d64 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/solution/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The determinant of the product is the product of the determinants. -/ +theorem det_of_product : Matrix.det (!![3, 1; -2, 2] * !![4, -1; -3, 2] : Matrix (Fin 2) (Fin 2) ℤ) = 40 := by + rw [Matrix.det_mul, Matrix.det_fin_two_of, Matrix.det_fin_two_of] + norm_num diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/solution/solve.sh b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/task.toml b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..301c4575377ecb849adfda503346d46577615b96 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "linear-algebra" +tags = ["linear-algebra", "det_trace", "msc-15", "eval", "lean4"] +msc = "15" +family = "det_trace" +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/linear-algebra/linear-algebra-det_trace-d1-e0012/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d1-e0012/tests/grade.py b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d1-e0012/tests/spec.json b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..51709903a0dfd1ffc09451dde90613a29dee09c7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The determinant of the product is the product of the determinants. -/\ntheorem det_of_product : Matrix.det (!![3, 1; -2, 2] * !![4, -1; -3, 2] : Matrix (Fin 2) (Fin 2) ℤ) = 40 := by\n sorry\n", + "targets": [ + { + "name": "det_of_product", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/tests/test.sh b/tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d1-t0000/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..b3fa8320d0390b9d8e552b6b8aeb494978116019 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/environment/workdir/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The determinant of the product is the product of the determinants. -/ +theorem det_of_product : Matrix.det (!![-2, 3; 3, 0] * !![-2, 4; 3, 0] : Matrix (Fin 2) (Fin 2) ℤ) = 108 := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/instruction.md b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..34efd2d3a2ff1bdd8920bc92bd183125dae4174b --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/instruction.md @@ -0,0 +1,14 @@ +# Determinant and trace of 2x2 matrices + +Prove the following statement. + +Compute the determinant of the product \(\begin{pmatrix} -2 & 3 \\ 3 & 0 \end{pmatrix}\) \(\begin{pmatrix} -2 & 4 \\ 3 & 0 \end{pmatrix}\) of integer matrices. Show that it equals 108. + +## 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/linear-algebra/linear-algebra-det_trace-d1-t0000/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..c9ac4018f40e6af4d0fe6b46d58b7f288d44344e --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/solution/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The determinant of the product is the product of the determinants. -/ +theorem det_of_product : Matrix.det (!![-2, 3; 3, 0] * !![-2, 4; 3, 0] : Matrix (Fin 2) (Fin 2) ℤ) = 108 := by + rw [Matrix.det_mul, Matrix.det_fin_two_of, Matrix.det_fin_two_of] + norm_num diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/solution/solve.sh b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/task.toml b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f59800dfd564cb6b142975c7f32120caa4c364f8 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "linear-algebra" +tags = ["linear-algebra", "det_trace", "msc-15", "train", "lean4"] +msc = "15" +family = "det_trace" +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/linear-algebra/linear-algebra-det_trace-d1-t0000/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d1-t0000/tests/grade.py b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d1-t0000/tests/spec.json b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..f926d31ea8f323e4eb665f5662129a03f77892fc --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The determinant of the product is the product of the determinants. -/\ntheorem det_of_product : Matrix.det (!![-2, 3; 3, 0] * !![-2, 4; 3, 0] : Matrix (Fin 2) (Fin 2) ℤ) = 108 := by\n sorry\n", + "targets": [ + { + "name": "det_of_product", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/tests/test.sh b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d1-t0012/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..634ff3992ec06a0a2a7438400618db6625bd2752 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A matrix times its adjugate is its determinant times the identity. -/ +theorem adjugate_product (x : ℤ) : + !![x + 0, 2; -3, x - 3] * !![x - 3, -2; 3, x + 0] = (x ^ 2 + -3 * x + 6) • (1 : Matrix (Fin 2) (Fin 2) ℤ) := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/instruction.md b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e9faef78adff9360b5373d5a8c59f45f8e1b8906 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/instruction.md @@ -0,0 +1,14 @@ +# Determinant and trace of 2x2 matrices + +Prove the following statement. + +For every integer \(x\), \[\begin{pmatrix} x+0 & 2 \\ -3 & x-3 \end{pmatrix}\begin{pmatrix} x-3 & -2 \\ 3 & x+0 \end{pmatrix} = (x^2 -3 x +6) \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix}.\] + +## 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/linear-algebra/linear-algebra-det_trace-d1-t0012/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..9f9ff0a9a78c4e5a71512676b769c8ab2abda05b --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- A matrix times its adjugate is its determinant times the identity. -/ +theorem adjugate_product (x : ℤ) : + !![x + 0, 2; -3, x - 3] * !![x - 3, -2; 3, x + 0] = (x ^ 2 + -3 * x + 6) • (1 : Matrix (Fin 2) (Fin 2) ℤ) := by + rw [Matrix.one_fin_two, Matrix.mul_fin_two] + ext i j + fin_cases i <;> fin_cases j <;> simp <;> ring diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/solution/solve.sh b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/task.toml b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2e8328ef676f27febbe2be90812ab4863304abd2 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "linear-algebra" +tags = ["linear-algebra", "det_trace", "msc-15", "train", "lean4"] +msc = "15" +family = "det_trace" +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/linear-algebra/linear-algebra-det_trace-d1-t0012/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d1-t0012/tests/grade.py b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d1-t0012/tests/spec.json b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..fa1ad38f5dfdd32e3c87840ca4dc8159bb5b9a9f --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A matrix times its adjugate is its determinant times the identity. -/\ntheorem adjugate_product (x : ℤ) :\n !![x + 0, 2; -3, x - 3] * !![x - 3, -2; 3, x + 0] = (x ^ 2 + -3 * x + 6) • (1 : Matrix (Fin 2) (Fin 2) ℤ) := by\n sorry\n", + "targets": [ + { + "name": "adjugate_product", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/tests/test.sh b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d1-t0024/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..92c692cba5a82488408597f56e435426a4ddb3d8 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/environment/workdir/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The determinant of the product is the product of the determinants. -/ +theorem det_of_product : Matrix.det (!![-2, 0; 1, -3] * !![3, -2; 4, -1] : Matrix (Fin 2) (Fin 2) ℤ) = 30 := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/instruction.md b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..43a47b8ff2c7823baead04638ec27dcd5f6bfc97 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/instruction.md @@ -0,0 +1,14 @@ +# Determinant and trace of 2x2 matrices + +Prove the following statement. + +Compute the determinant of the product \(\begin{pmatrix} -2 & 0 \\ 1 & -3 \end{pmatrix}\) \(\begin{pmatrix} 3 & -2 \\ 4 & -1 \end{pmatrix}\) of integer matrices. Show that it equals 30. + +## 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/linear-algebra/linear-algebra-det_trace-d1-t0024/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..4f2f2f6058cfcbb18cb70d79081e057fee95b16b --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/solution/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The determinant of the product is the product of the determinants. -/ +theorem det_of_product : Matrix.det (!![-2, 0; 1, -3] * !![3, -2; 4, -1] : Matrix (Fin 2) (Fin 2) ℤ) = 30 := by + rw [Matrix.det_mul, Matrix.det_fin_two_of, Matrix.det_fin_two_of] + norm_num diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/solution/solve.sh b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/task.toml b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2a151bab3fd6533b04d94452075a2cf4e3f94431 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "linear-algebra" +tags = ["linear-algebra", "det_trace", "msc-15", "train", "lean4"] +msc = "15" +family = "det_trace" +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/linear-algebra/linear-algebra-det_trace-d1-t0024/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d1-t0024/tests/grade.py b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d1-t0024/tests/spec.json b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..7db873bdedfbdb5bf872a72ad84b49b9883073c1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The determinant of the product is the product of the determinants. -/\ntheorem det_of_product : Matrix.det (!![-2, 0; 1, -3] * !![3, -2; 4, -1] : Matrix (Fin 2) (Fin 2) ℤ) = 30 := by\n sorry\n", + "targets": [ + { + "name": "det_of_product", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/tests/test.sh b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d1-t0036/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0036/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0036/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-t0036/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0036/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..0a743ca78f31caca4bcb0c5d1f42320503b7e6ec --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0036/environment/workdir/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The determinant of the product is the product of the determinants. -/ +theorem det_of_product : Matrix.det (!![4, 0; -2, 3] * !![1, 4; -1, 3] : Matrix (Fin 2) (Fin 2) ℤ) = 84 := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-t0036/instruction.md b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0036/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..32aeb48863cdd6775accd773370bc4c35659e9cb --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0036/instruction.md @@ -0,0 +1,14 @@ +# Determinant and trace of 2x2 matrices + +Prove the following statement. + +Compute the determinant of the product \(\begin{pmatrix} 4 & 0 \\ -2 & 3 \end{pmatrix}\) \(\begin{pmatrix} 1 & 4 \\ -1 & 3 \end{pmatrix}\) of integer matrices. Show that it equals 84. + +## 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/linear-algebra/linear-algebra-det_trace-d1-t0036/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0036/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..6c263b065d917e7469e01524e471df33d42fbeed --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0036/solution/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The determinant of the product is the product of the determinants. -/ +theorem det_of_product : Matrix.det (!![4, 0; -2, 3] * !![1, 4; -1, 3] : Matrix (Fin 2) (Fin 2) ℤ) = 84 := by + rw [Matrix.det_mul, Matrix.det_fin_two_of, Matrix.det_fin_two_of] + norm_num diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-t0036/solution/solve.sh b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0036/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0036/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-t0036/task.toml b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0036/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1e56d186ace49cbe95c1b58ec307ea3444c5994c --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0036/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "linear-algebra" +tags = ["linear-algebra", "det_trace", "msc-15", "train", "lean4"] +msc = "15" +family = "det_trace" +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/linear-algebra/linear-algebra-det_trace-d1-t0036/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0036/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d1-t0036/tests/grade.py b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0036/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d1-t0036/tests/spec.json b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0036/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..865b0d2b6a9b6df94a3715d79916c02e9d180f78 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0036/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The determinant of the product is the product of the determinants. -/\ntheorem det_of_product : Matrix.det (!![4, 0; -2, 3] * !![1, 4; -1, 3] : Matrix (Fin 2) (Fin 2) ℤ) = 84 := by\n sorry\n", + "targets": [ + { + "name": "det_of_product", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-t0036/tests/test.sh b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0036/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d1-t0048/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0048/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0048/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-t0048/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0048/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..43a2b8c431a3ad395361ab0c521ebc0b51206705 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0048/environment/workdir/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The determinant of the product is the product of the determinants. -/ +theorem det_of_product : Matrix.det (!![-1, 0; 0, 2] * !![0, -2; 3, 2] : Matrix (Fin 2) (Fin 2) ℤ) = (-12 : ℤ) := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-t0048/instruction.md b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0048/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8bdcbc62f58d228b734cb580bef628d76c8c8db8 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0048/instruction.md @@ -0,0 +1,14 @@ +# Determinant and trace of 2x2 matrices + +Prove the following statement. + +Compute the determinant of the product \(\begin{pmatrix} -1 & 0 \\ 0 & 2 \end{pmatrix}\) \(\begin{pmatrix} 0 & -2 \\ 3 & 2 \end{pmatrix}\) of integer matrices. Show that it equals -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/linear-algebra/linear-algebra-det_trace-d1-t0048/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0048/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..f494131729c914fcd3c042216281801f94a14e99 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0048/solution/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The determinant of the product is the product of the determinants. -/ +theorem det_of_product : Matrix.det (!![-1, 0; 0, 2] * !![0, -2; 3, 2] : Matrix (Fin 2) (Fin 2) ℤ) = (-12 : ℤ) := by + rw [Matrix.det_mul, Matrix.det_fin_two_of, Matrix.det_fin_two_of] + norm_num diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-t0048/solution/solve.sh b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0048/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0048/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-t0048/task.toml b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0048/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..09b241d2cbcded8f09e71c32480d934a8a8903e6 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0048/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "linear-algebra" +tags = ["linear-algebra", "det_trace", "msc-15", "train", "lean4"] +msc = "15" +family = "det_trace" +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/linear-algebra/linear-algebra-det_trace-d1-t0048/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0048/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d1-t0048/tests/grade.py b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0048/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d1-t0048/tests/spec.json b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0048/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..8dac2477adc4caf1e408527772d6fcd5d5b650cb --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0048/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The determinant of the product is the product of the determinants. -/\ntheorem det_of_product : Matrix.det (!![-1, 0; 0, 2] * !![0, -2; 3, 2] : Matrix (Fin 2) (Fin 2) ℤ) = (-12 : ℤ) := by\n sorry\n", + "targets": [ + { + "name": "det_of_product", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d1-t0048/tests/test.sh b/tasks/linear-algebra/linear-algebra-det_trace-d1-t0048/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d2-t0040/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0040/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0040/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d2-t0040/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0040/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..7c5457b18b1e6b7bc204e9b7bfe3fdf961b1506b --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0040/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The characteristic polynomial of a 2x2 matrix is x^2 - tr x + det. -/ +theorem char_poly_value (x : ℤ) : + Matrix.det (x • (1 : Matrix (Fin 2) (Fin 2) ℤ) - !![-2, -1; -3, -2]) = x ^ 2 - (-4 : ℤ) * x + 1 := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d2-t0040/instruction.md b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0040/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4f175cb267551172f5a122b187324e1fc7d4fedc --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0040/instruction.md @@ -0,0 +1,14 @@ +# Determinant and trace of 2x2 matrices + +Prove the following statement. + +For every integer \(x\), \[\det\left(x I - \begin{pmatrix} -2 & -1 \\ -3 & -2 \end{pmatrix}\right) = x^2 - (-4)\,x + (1),\] where \(I\) is the \(2 \times 2\) identity matrix. + +## 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/linear-algebra/linear-algebra-det_trace-d2-t0040/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0040/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..5f7f0968ce9703e349c1b3d6a7c2a41fc44dfd13 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0040/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The characteristic polynomial of a 2x2 matrix is x^2 - tr x + det. -/ +theorem char_poly_value (x : ℤ) : + Matrix.det (x • (1 : Matrix (Fin 2) (Fin 2) ℤ) - !![-2, -1; -3, -2]) = x ^ 2 - (-4 : ℤ) * x + 1 := by + rw [Matrix.one_fin_two, Matrix.det_fin_two] + simp + ring diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d2-t0040/solution/solve.sh b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0040/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0040/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d2-t0040/task.toml b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0040/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a59be1eee5c20e61adf6dc4a09962ab35b1a3c63 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0040/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "linear-algebra" +tags = ["linear-algebra", "det_trace", "msc-15", "train", "lean4"] +msc = "15" +family = "det_trace" +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/linear-algebra/linear-algebra-det_trace-d2-t0040/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0040/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d2-t0040/tests/grade.py b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0040/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d2-t0040/tests/spec.json b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0040/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..b728b415cd9bf3110021e54b452bed19cccee5f7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0040/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The characteristic polynomial of a 2x2 matrix is x^2 - tr x + det. -/\ntheorem char_poly_value (x : ℤ) :\n Matrix.det (x • (1 : Matrix (Fin 2) (Fin 2) ℤ) - !![-2, -1; -3, -2]) = x ^ 2 - (-4 : ℤ) * x + 1 := by\n sorry\n", + "targets": [ + { + "name": "char_poly_value", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d2-t0040/tests/test.sh b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0040/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d2-t0052/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0052/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0052/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d2-t0052/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0052/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..3e4d905e66635fe57d99d413c9f0664477ae3336 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0052/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The characteristic polynomial of a 2x2 matrix is x^2 - tr x + det. -/ +theorem char_poly_value (x : ℤ) : + Matrix.det (x • (1 : Matrix (Fin 2) (Fin 2) ℤ) - !![2, 0; -2, -1]) = x ^ 2 - 1 * x + (-2 : ℤ) := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d2-t0052/instruction.md b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0052/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c62c52d9704c1e52c93710bd68bbde4030fba42a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0052/instruction.md @@ -0,0 +1,14 @@ +# Determinant and trace of 2x2 matrices + +Prove the following statement. + +For every integer \(x\), \[\det\left(x I - \begin{pmatrix} 2 & 0 \\ -2 & -1 \end{pmatrix}\right) = x^2 - (1)\,x + (-2),\] where \(I\) is the \(2 \times 2\) identity matrix. + +## 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/linear-algebra/linear-algebra-det_trace-d2-t0052/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0052/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..9cfde0920a7d93f008addcdfbc450251318212dd --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0052/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The characteristic polynomial of a 2x2 matrix is x^2 - tr x + det. -/ +theorem char_poly_value (x : ℤ) : + Matrix.det (x • (1 : Matrix (Fin 2) (Fin 2) ℤ) - !![2, 0; -2, -1]) = x ^ 2 - 1 * x + (-2 : ℤ) := by + rw [Matrix.one_fin_two, Matrix.det_fin_two] + simp + ring diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d2-t0052/solution/solve.sh b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0052/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0052/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d2-t0052/task.toml b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0052/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6d327730dee226afa85ce16b94dcfabce9b98fe5 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0052/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "linear-algebra" +tags = ["linear-algebra", "det_trace", "msc-15", "train", "lean4"] +msc = "15" +family = "det_trace" +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/linear-algebra/linear-algebra-det_trace-d2-t0052/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0052/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d2-t0052/tests/grade.py b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0052/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d2-t0052/tests/spec.json b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0052/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..38a87e306e50b01d79246292d37dbf9095ba43ef --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0052/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The characteristic polynomial of a 2x2 matrix is x^2 - tr x + det. -/\ntheorem char_poly_value (x : ℤ) :\n Matrix.det (x • (1 : Matrix (Fin 2) (Fin 2) ℤ) - !![2, 0; -2, -1]) = x ^ 2 - 1 * x + (-2 : ℤ) := by\n sorry\n", + "targets": [ + { + "name": "char_poly_value", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d2-t0052/tests/test.sh b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0052/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d2-t0064/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0064/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0064/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d2-t0064/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0064/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..21579e3305f561dfa5498dcb2a25638e943f775e --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0064/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The determinant of a product of matrices with a variable entry. -/ +theorem det_of_polynomial_product (x : ℤ) : + Matrix.det (!![x + 1, -1; 1, x + 0] * !![x, -3; 2, x - 1] : Matrix (Fin 2) (Fin 2) ℤ) = x ^ 4 + 6 * x ^ 2 + 5 * x + 6 := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d2-t0064/instruction.md b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0064/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b79e10c4cc11c3f0668f11afd4ce06de060d4157 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0064/instruction.md @@ -0,0 +1,14 @@ +# Determinant and trace of 2x2 matrices + +Prove the following statement. + +For every integer \(x\), the determinant of \[\begin{pmatrix} x+1 & -1 \\ 1 & x+0 \end{pmatrix}\begin{pmatrix} x & -3 \\ 2 & x-1 \end{pmatrix}\] equals \(x^4 + 6x^2 + 5x + 6\). + +## 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/linear-algebra/linear-algebra-det_trace-d2-t0064/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0064/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..bedcbc393e5b3966ecbc761c40ef72500e694974 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0064/solution/Solution.lean @@ -0,0 +1,7 @@ +import Mathlib + +/-- The determinant of a product of matrices with a variable entry. -/ +theorem det_of_polynomial_product (x : ℤ) : + Matrix.det (!![x + 1, -1; 1, x + 0] * !![x, -3; 2, x - 1] : Matrix (Fin 2) (Fin 2) ℤ) = x ^ 4 + 6 * x ^ 2 + 5 * x + 6 := by + rw [Matrix.det_mul, Matrix.det_fin_two_of, Matrix.det_fin_two_of] + ring diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d2-t0064/solution/solve.sh b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0064/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0064/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d2-t0064/task.toml b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0064/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..08eaab9f5e38ce062dd3d8ae838d55d6e23ad0fd --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0064/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "linear-algebra" +tags = ["linear-algebra", "det_trace", "msc-15", "train", "lean4"] +msc = "15" +family = "det_trace" +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/linear-algebra/linear-algebra-det_trace-d2-t0064/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0064/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d2-t0064/tests/grade.py b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0064/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d2-t0064/tests/spec.json b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0064/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..a4d6c0b69d1726ec325bb72007e2f1379990fd2a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0064/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The determinant of a product of matrices with a variable entry. -/\ntheorem det_of_polynomial_product (x : ℤ) :\n Matrix.det (!![x + 1, -1; 1, x + 0] * !![x, -3; 2, x - 1] : Matrix (Fin 2) (Fin 2) ℤ) = x ^ 4 + 6 * x ^ 2 + 5 * x + 6 := by\n sorry\n", + "targets": [ + { + "name": "det_of_polynomial_product", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d2-t0064/tests/test.sh b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0064/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d2-t0076/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0076/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0076/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d2-t0076/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0076/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..3ab85999f5a45aa04d8dc1a50cfc92aadb785378 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0076/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A^2 = tr(A) A - det(A) I with the given trace and determinant. -/ +theorem square_of_matrix (A : Matrix (Fin 2) (Fin 2) ℤ) (ht : Matrix.trace A = (3 : ℤ)) (hd : Matrix.det A = (1 : ℤ)) : + A ^ 2 = (3 : ℤ) • A - (1 : ℤ) • (1 : Matrix (Fin 2) (Fin 2) ℤ) := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d2-t0076/instruction.md b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0076/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5a40afc6fb96db3eec0cb97231fe4408fc045308 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0076/instruction.md @@ -0,0 +1,14 @@ +# Determinant and trace of 2x2 matrices + +Prove the following statement. + +Let \(A\) be a \(2 \times 2\) integer matrix with trace 3 and determinant 1. Then \(A^2 = 3 A - 1 I\), where \(I\) is the identity matrix. + +## 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/linear-algebra/linear-algebra-det_trace-d2-t0076/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0076/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..2498c2bd8df1758933c86f6f9acc417beccafeec --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0076/solution/Solution.lean @@ -0,0 +1,10 @@ +import Mathlib + +/-- A^2 = tr(A) A - det(A) I with the given trace and determinant. -/ +theorem square_of_matrix (A : Matrix (Fin 2) (Fin 2) ℤ) (ht : Matrix.trace A = (3 : ℤ)) (hd : Matrix.det A = (1 : ℤ)) : + A ^ 2 = (3 : ℤ) • A - (1 : ℤ) • (1 : Matrix (Fin 2) (Fin 2) ℤ) := by + have key : A ^ 2 = Matrix.trace A • A - Matrix.det A • (1 : Matrix (Fin 2) (Fin 2) ℤ) := by + rw [Matrix.eta_fin_two A, Matrix.one_fin_two, pow_two, Matrix.mul_fin_two, Matrix.trace_fin_two, Matrix.det_fin_two] + ext i j + fin_cases i <;> fin_cases j <;> simp <;> ring + rw [key, ht, hd] diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d2-t0076/solution/solve.sh b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0076/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0076/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d2-t0076/task.toml b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0076/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b3a245658329adf2b9411eb685e2b0a83a5c80fb --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0076/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "linear-algebra" +tags = ["linear-algebra", "det_trace", "msc-15", "train", "lean4"] +msc = "15" +family = "det_trace" +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/linear-algebra/linear-algebra-det_trace-d2-t0076/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0076/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d2-t0076/tests/grade.py b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0076/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d2-t0076/tests/spec.json b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0076/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..d7d62278277e08200865f65c279a94e3a20af786 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0076/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A^2 = tr(A) A - det(A) I with the given trace and determinant. -/\ntheorem square_of_matrix (A : Matrix (Fin 2) (Fin 2) ℤ) (ht : Matrix.trace A = (3 : ℤ)) (hd : Matrix.det A = (1 : ℤ)) :\n A ^ 2 = (3 : ℤ) • A - (1 : ℤ) • (1 : Matrix (Fin 2) (Fin 2) ℤ) := by\n sorry\n", + "targets": [ + { + "name": "square_of_matrix", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d2-t0076/tests/test.sh b/tasks/linear-algebra/linear-algebra-det_trace-d2-t0076/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d3-e0008/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-det_trace-d3-e0008/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d3-e0008/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d3-e0008/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-det_trace-d3-e0008/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..695558b4cb6c3de5fe5a85db154b692b141f512c --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d3-e0008/environment/workdir/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- Cayley-Hamilton for 2x2 integer matrices. -/ +theorem cayley_hamilton_two (A : Matrix (Fin 2) (Fin 2) ℤ) : + A ^ 2 = Matrix.trace A • A - Matrix.det A • (1 : Matrix (Fin 2) (Fin 2) ℤ) := by + sorry + +/-- The trace of A^2 from the trace and determinant of A. -/ +theorem trace_of_square (A : Matrix (Fin 2) (Fin 2) ℤ) (ht : Matrix.trace A = (-1 : ℤ)) (hd : Matrix.det A = (-3 : ℤ)) : + Matrix.trace (A ^ 2) = 7 := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d3-e0008/instruction.md b/tasks/linear-algebra/linear-algebra-det_trace-d3-e0008/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c95d8e0d04d4d7bdb863be0aeadf08059d950663 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d3-e0008/instruction.md @@ -0,0 +1,14 @@ +# Determinant and trace of 2x2 matrices + +Prove the following statement. + +Let \(A\) be a \(2 \times 2\) integer matrix with trace -1 and determinant -3. Then the trace of \(A^2\) is 7. You may first prove \(A^2 = (\operatorname{tr} A) A - (\det A) I\) for every \(2 \times 2\) integer matrix. + +## 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/linear-algebra/linear-algebra-det_trace-d3-e0008/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-det_trace-d3-e0008/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..bc833b26c28ca68850f016824332fdf3e1559a23 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d3-e0008/solution/Solution.lean @@ -0,0 +1,14 @@ +import Mathlib + +/-- Cayley-Hamilton for 2x2 integer matrices. -/ +theorem cayley_hamilton_two (A : Matrix (Fin 2) (Fin 2) ℤ) : + A ^ 2 = Matrix.trace A • A - Matrix.det A • (1 : Matrix (Fin 2) (Fin 2) ℤ) := by + rw [Matrix.eta_fin_two A, Matrix.one_fin_two, pow_two, Matrix.mul_fin_two, Matrix.trace_fin_two, Matrix.det_fin_two] + ext i j + fin_cases i <;> fin_cases j <;> simp <;> ring + +/-- The trace of A^2 from the trace and determinant of A. -/ +theorem trace_of_square (A : Matrix (Fin 2) (Fin 2) ℤ) (ht : Matrix.trace A = (-1 : ℤ)) (hd : Matrix.det A = (-3 : ℤ)) : + Matrix.trace (A ^ 2) = 7 := by + rw [cayley_hamilton_two A, Matrix.trace_sub, Matrix.trace_smul, Matrix.trace_smul, Matrix.trace_one, ht, hd] + norm_num diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d3-e0008/solution/solve.sh b/tasks/linear-algebra/linear-algebra-det_trace-d3-e0008/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d3-e0008/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d3-e0008/task.toml b/tasks/linear-algebra/linear-algebra-det_trace-d3-e0008/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5d785a9e4c6fe231461f7a563192db2dc72db550 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d3-e0008/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "linear-algebra" +tags = ["linear-algebra", "det_trace", "msc-15", "eval", "lean4"] +msc = "15" +family = "det_trace" +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/linear-algebra/linear-algebra-det_trace-d3-e0008/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-det_trace-d3-e0008/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d3-e0008/tests/grade.py b/tasks/linear-algebra/linear-algebra-det_trace-d3-e0008/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d3-e0008/tests/spec.json b/tasks/linear-algebra/linear-algebra-det_trace-d3-e0008/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..3e1c829aeb7f0cb8e1215b190dbb551598d50690 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d3-e0008/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\n/-- Cayley-Hamilton for 2x2 integer matrices. -/\ntheorem cayley_hamilton_two (A : Matrix (Fin 2) (Fin 2) ℤ) :\n A ^ 2 = Matrix.trace A • A - Matrix.det A • (1 : Matrix (Fin 2) (Fin 2) ℤ) := by\n sorry\n\n/-- The trace of A^2 from the trace and determinant of A. -/\ntheorem trace_of_square (A : Matrix (Fin 2) (Fin 2) ℤ) (ht : Matrix.trace A = (-1 : ℤ)) (hd : Matrix.det A = (-3 : ℤ)) :\n Matrix.trace (A ^ 2) = 7 := by\n sorry\n", + "targets": [ + { + "name": "cayley_hamilton_two", + "weight": 0.4 + }, + { + "name": "trace_of_square", + "weight": 0.6 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d3-e0008/tests/test.sh b/tasks/linear-algebra/linear-algebra-det_trace-d3-e0008/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d3-t0008/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-det_trace-d3-t0008/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d3-t0008/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d3-t0008/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-det_trace-d3-t0008/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..7b135b5258a3393fdbba0b0aa61682790066369e --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d3-t0008/environment/workdir/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- Cayley-Hamilton for 2x2 integer matrices. -/ +theorem cayley_hamilton_two (A : Matrix (Fin 2) (Fin 2) ℤ) : + A ^ 2 = Matrix.trace A • A - Matrix.det A • (1 : Matrix (Fin 2) (Fin 2) ℤ) := by + sorry + +/-- The trace of A^2 from the trace and determinant of A. -/ +theorem trace_of_square (A : Matrix (Fin 2) (Fin 2) ℤ) (ht : Matrix.trace A = (1 : ℤ)) (hd : Matrix.det A = (3 : ℤ)) : + Matrix.trace (A ^ 2) = (-5 : ℤ) := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d3-t0008/instruction.md b/tasks/linear-algebra/linear-algebra-det_trace-d3-t0008/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9cc19632d3937090adf4c1f11884db9583aadf45 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d3-t0008/instruction.md @@ -0,0 +1,14 @@ +# Determinant and trace of 2x2 matrices + +Prove the following statement. + +Let \(A\) be a \(2 \times 2\) integer matrix with trace 1 and determinant 3. Then the trace of \(A^2\) is -5. You may first prove \(A^2 = (\operatorname{tr} A) A - (\det A) I\) for every \(2 \times 2\) integer matrix. + +## 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/linear-algebra/linear-algebra-det_trace-d3-t0008/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-det_trace-d3-t0008/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..42126f799465e423e6628329dabcecb3be509c52 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d3-t0008/solution/Solution.lean @@ -0,0 +1,14 @@ +import Mathlib + +/-- Cayley-Hamilton for 2x2 integer matrices. -/ +theorem cayley_hamilton_two (A : Matrix (Fin 2) (Fin 2) ℤ) : + A ^ 2 = Matrix.trace A • A - Matrix.det A • (1 : Matrix (Fin 2) (Fin 2) ℤ) := by + rw [Matrix.eta_fin_two A, Matrix.one_fin_two, pow_two, Matrix.mul_fin_two, Matrix.trace_fin_two, Matrix.det_fin_two] + ext i j + fin_cases i <;> fin_cases j <;> simp <;> ring + +/-- The trace of A^2 from the trace and determinant of A. -/ +theorem trace_of_square (A : Matrix (Fin 2) (Fin 2) ℤ) (ht : Matrix.trace A = (1 : ℤ)) (hd : Matrix.det A = (3 : ℤ)) : + Matrix.trace (A ^ 2) = (-5 : ℤ) := by + rw [cayley_hamilton_two A, Matrix.trace_sub, Matrix.trace_smul, Matrix.trace_smul, Matrix.trace_one, ht, hd] + norm_num diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d3-t0008/solution/solve.sh b/tasks/linear-algebra/linear-algebra-det_trace-d3-t0008/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d3-t0008/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d3-t0008/task.toml b/tasks/linear-algebra/linear-algebra-det_trace-d3-t0008/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2de3c99413e4010ef59ddc5768d22b7a6ee84810 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d3-t0008/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "linear-algebra" +tags = ["linear-algebra", "det_trace", "msc-15", "train", "lean4"] +msc = "15" +family = "det_trace" +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/linear-algebra/linear-algebra-det_trace-d3-t0008/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-det_trace-d3-t0008/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d3-t0008/tests/grade.py b/tasks/linear-algebra/linear-algebra-det_trace-d3-t0008/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-det_trace-d3-t0008/tests/spec.json b/tasks/linear-algebra/linear-algebra-det_trace-d3-t0008/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..da46b5d2885ca872221da6772004d6a1784ea073 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-d3-t0008/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\n/-- Cayley-Hamilton for 2x2 integer matrices. -/\ntheorem cayley_hamilton_two (A : Matrix (Fin 2) (Fin 2) ℤ) :\n A ^ 2 = Matrix.trace A • A - Matrix.det A • (1 : Matrix (Fin 2) (Fin 2) ℤ) := by\n sorry\n\n/-- The trace of A^2 from the trace and determinant of A. -/\ntheorem trace_of_square (A : Matrix (Fin 2) (Fin 2) ℤ) (ht : Matrix.trace A = (1 : ℤ)) (hd : Matrix.det A = (3 : ℤ)) :\n Matrix.trace (A ^ 2) = (-5 : ℤ) := by\n sorry\n", + "targets": [ + { + "name": "cayley_hamilton_two", + "weight": 0.4 + }, + { + "name": "trace_of_square", + "weight": 0.6 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-det_trace-d3-t0008/tests/test.sh b/tasks/linear-algebra/linear-algebra-det_trace-d3-t0008/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-det_trace-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/linear-algebra/linear-algebra-independence-d1-e0001/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-independence-d1-e0001/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-e0001/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-e0001/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-independence-d1-e0001/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..9309eca563544d18fcd9a6694ebe35014240c6e0 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-e0001/environment/workdir/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The given vectors are linearly dependent over the rationals. -/ +theorem vectors_dependent : ¬ LinearIndependent ℚ ![(![0, -2] : Fin 2 → ℚ), ![0, 6]] := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-e0001/instruction.md b/tasks/linear-algebra/linear-algebra-independence-d1-e0001/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..10159b4dd37ae09a61603e9da6e096dbe934f3bc --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-e0001/instruction.md @@ -0,0 +1,14 @@ +# Linear independence of explicit vectors + +Prove the following statement. + +In \(\mathbb{Q}^2\) consider the vectors \(\begin{pmatrix} 0 \\ -2 \end{pmatrix}\), \(\begin{pmatrix} 0 \\ 6 \end{pmatrix}\). Show that they are not linearly independent over \(\mathbb{Q}\). + +## 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/linear-algebra/linear-algebra-independence-d1-e0001/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-independence-d1-e0001/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..a8494b57213f6982b9370ba6cf4cc9477246ceb7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-e0001/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The given vectors are linearly dependent over the rationals. -/ +theorem vectors_dependent : ¬ LinearIndependent ℚ ![(![0, -2] : Fin 2 → ℚ), ![0, 6]] := by + rw [Fintype.not_linearIndependent_iff] + refine ⟨![(-3 : ℚ), (-1 : ℚ)], ?_, 1, by simp⟩ + ext i + fin_cases i <;> simp [Fin.sum_univ_two] <;> norm_num diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-e0001/solution/solve.sh b/tasks/linear-algebra/linear-algebra-independence-d1-e0001/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-e0001/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-e0001/task.toml b/tasks/linear-algebra/linear-algebra-independence-d1-e0001/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..511931113f9c163b1f40ba142630b2e550969280 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-e0001/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "linear-algebra" +tags = ["linear-algebra", "independence", "msc-15", "eval", "lean4"] +msc = "15" +family = "independence" +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/linear-algebra/linear-algebra-independence-d1-e0001/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-independence-d1-e0001/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d1-e0001/tests/grade.py b/tasks/linear-algebra/linear-algebra-independence-d1-e0001/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d1-e0001/tests/spec.json b/tasks/linear-algebra/linear-algebra-independence-d1-e0001/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..1eff919787633e7fd9329bb1e26e5382e7b43f4f --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-e0001/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The given vectors are linearly dependent over the rationals. -/\ntheorem vectors_dependent : ¬ LinearIndependent ℚ ![(![0, -2] : Fin 2 → ℚ), ![0, 6]] := by\n sorry\n", + "targets": [ + { + "name": "vectors_dependent", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-e0001/tests/test.sh b/tasks/linear-algebra/linear-algebra-independence-d1-e0001/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d1-e0013/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-independence-d1-e0013/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-e0013/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-e0013/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-independence-d1-e0013/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..5f0d22e4705dbc5f310e1f2d132a26f537820aba --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-e0013/environment/workdir/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The given vectors are linearly independent over the rationals. -/ +theorem vectors_independent : LinearIndependent ℚ ![(![2, -3] : Fin 2 → ℚ), ![1, -1]] := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-e0013/instruction.md b/tasks/linear-algebra/linear-algebra-independence-d1-e0013/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0cbed2945dc67ef39bc1b62bbd95be8c539375e6 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-e0013/instruction.md @@ -0,0 +1,14 @@ +# Linear independence of explicit vectors + +Prove the following statement. + +In \(\mathbb{Q}^2\) consider the vectors \(\begin{pmatrix} 2 \\ -3 \end{pmatrix}\), \(\begin{pmatrix} 1 \\ -1 \end{pmatrix}\). Show that they are linearly independent over \(\mathbb{Q}\). + +## 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/linear-algebra/linear-algebra-independence-d1-e0013/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-independence-d1-e0013/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..12355c4306e00162b25e1a214853cc69305da0a8 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-e0013/solution/Solution.lean @@ -0,0 +1,10 @@ +import Mathlib + +/-- The given vectors are linearly independent over the rationals. -/ +theorem vectors_independent : LinearIndependent ℚ ![(![2, -3] : Fin 2 → ℚ), ![1, -1]] := by + rw [LinearIndependent.pair_iff] + intro s t h + have h0 := congr_fun h 0 + have h1 := congr_fun h 1 + simp at h0 h1 + constructor <;> linarith diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-e0013/solution/solve.sh b/tasks/linear-algebra/linear-algebra-independence-d1-e0013/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-e0013/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-e0013/task.toml b/tasks/linear-algebra/linear-algebra-independence-d1-e0013/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9e5d8621079a490d6c6c74ccbcd513e3c20856eb --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-e0013/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "linear-algebra" +tags = ["linear-algebra", "independence", "msc-15", "eval", "lean4"] +msc = "15" +family = "independence" +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/linear-algebra/linear-algebra-independence-d1-e0013/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-independence-d1-e0013/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d1-e0013/tests/grade.py b/tasks/linear-algebra/linear-algebra-independence-d1-e0013/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d1-e0013/tests/spec.json b/tasks/linear-algebra/linear-algebra-independence-d1-e0013/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..4c3117f3a17484ddce02bb5c0c5fbdc3d12f649f --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-e0013/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The given vectors are linearly independent over the rationals. -/\ntheorem vectors_independent : LinearIndependent ℚ ![(![2, -3] : Fin 2 → ℚ), ![1, -1]] := by\n sorry\n", + "targets": [ + { + "name": "vectors_independent", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-e0013/tests/test.sh b/tasks/linear-algebra/linear-algebra-independence-d1-e0013/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d1-t0001/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-independence-d1-t0001/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0001/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-t0001/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-independence-d1-t0001/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..60d2ad590d8bc92b1add580c23cbf4555c488da1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0001/environment/workdir/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The given vectors are linearly independent over the rationals. -/ +theorem vectors_independent : LinearIndependent ℚ ![(![0, 2] : Fin 2 → ℚ), ![2, 3]] := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-t0001/instruction.md b/tasks/linear-algebra/linear-algebra-independence-d1-t0001/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..44a14d5c1bac742b6b7ec286b6f906cc88bfe3db --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0001/instruction.md @@ -0,0 +1,14 @@ +# Linear independence of explicit vectors + +Prove the following statement. + +In \(\mathbb{Q}^2\) consider the vectors \(\begin{pmatrix} 0 \\ 2 \end{pmatrix}\), \(\begin{pmatrix} 2 \\ 3 \end{pmatrix}\). Show that they are linearly independent over \(\mathbb{Q}\). + +## 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/linear-algebra/linear-algebra-independence-d1-t0001/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-independence-d1-t0001/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..175e3491d4699c112dc30c1b6b5f5bea594fe275 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0001/solution/Solution.lean @@ -0,0 +1,10 @@ +import Mathlib + +/-- The given vectors are linearly independent over the rationals. -/ +theorem vectors_independent : LinearIndependent ℚ ![(![0, 2] : Fin 2 → ℚ), ![2, 3]] := by + rw [LinearIndependent.pair_iff] + intro s t h + have h0 := congr_fun h 0 + have h1 := congr_fun h 1 + simp at h0 h1 + constructor <;> linarith diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-t0001/solution/solve.sh b/tasks/linear-algebra/linear-algebra-independence-d1-t0001/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0001/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-t0001/task.toml b/tasks/linear-algebra/linear-algebra-independence-d1-t0001/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a00ce5cb6808adefb41233dce1a605c21db06c33 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0001/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "linear-algebra" +tags = ["linear-algebra", "independence", "msc-15", "train", "lean4"] +msc = "15" +family = "independence" +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/linear-algebra/linear-algebra-independence-d1-t0001/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-independence-d1-t0001/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d1-t0001/tests/grade.py b/tasks/linear-algebra/linear-algebra-independence-d1-t0001/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d1-t0001/tests/spec.json b/tasks/linear-algebra/linear-algebra-independence-d1-t0001/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..da8a3271409f0c2ac2504a6c2c27adfdd0b0b453 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0001/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The given vectors are linearly independent over the rationals. -/\ntheorem vectors_independent : LinearIndependent ℚ ![(![0, 2] : Fin 2 → ℚ), ![2, 3]] := by\n sorry\n", + "targets": [ + { + "name": "vectors_independent", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-t0001/tests/test.sh b/tasks/linear-algebra/linear-algebra-independence-d1-t0001/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d1-t0013/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-independence-d1-t0013/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0013/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-t0013/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-independence-d1-t0013/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..4988ed38d0761ce0bdeac14985fe3073b66a2766 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0013/environment/workdir/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The given vectors are linearly dependent over the rationals. -/ +theorem vectors_dependent : ¬ LinearIndependent ℚ ![(![-2, 3] : Fin 2 → ℚ), ![6, -9]] := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-t0013/instruction.md b/tasks/linear-algebra/linear-algebra-independence-d1-t0013/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a0873758f6a24fa86d55abad35ae2f5fdaca5156 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0013/instruction.md @@ -0,0 +1,14 @@ +# Linear independence of explicit vectors + +Prove the following statement. + +In \(\mathbb{Q}^2\) consider the vectors \(\begin{pmatrix} -2 \\ 3 \end{pmatrix}\), \(\begin{pmatrix} 6 \\ -9 \end{pmatrix}\). Show that they are not linearly independent over \(\mathbb{Q}\). + +## 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/linear-algebra/linear-algebra-independence-d1-t0013/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-independence-d1-t0013/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..70425bdce8fbf0989cd14aac0e70cd7466e7bffa --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0013/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The given vectors are linearly dependent over the rationals. -/ +theorem vectors_dependent : ¬ LinearIndependent ℚ ![(![-2, 3] : Fin 2 → ℚ), ![6, -9]] := by + rw [Fintype.not_linearIndependent_iff] + refine ⟨![(-3 : ℚ), (-1 : ℚ)], ?_, 1, by simp⟩ + ext i + fin_cases i <;> simp [Fin.sum_univ_two] <;> norm_num diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-t0013/solution/solve.sh b/tasks/linear-algebra/linear-algebra-independence-d1-t0013/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0013/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-t0013/task.toml b/tasks/linear-algebra/linear-algebra-independence-d1-t0013/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fb365ffa8fe1be14579e4131d6e2e4cff6ae7aa5 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0013/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "linear-algebra" +tags = ["linear-algebra", "independence", "msc-15", "train", "lean4"] +msc = "15" +family = "independence" +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/linear-algebra/linear-algebra-independence-d1-t0013/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-independence-d1-t0013/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d1-t0013/tests/grade.py b/tasks/linear-algebra/linear-algebra-independence-d1-t0013/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d1-t0013/tests/spec.json b/tasks/linear-algebra/linear-algebra-independence-d1-t0013/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..4f411ac8785dad92d16d8a16ba7ee27104d36c32 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0013/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The given vectors are linearly dependent over the rationals. -/\ntheorem vectors_dependent : ¬ LinearIndependent ℚ ![(![-2, 3] : Fin 2 → ℚ), ![6, -9]] := by\n sorry\n", + "targets": [ + { + "name": "vectors_dependent", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-t0013/tests/test.sh b/tasks/linear-algebra/linear-algebra-independence-d1-t0013/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d1-t0025/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-independence-d1-t0025/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0025/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-t0025/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-independence-d1-t0025/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..673f4e9d77078017916495b9cc3ea9f2d21599f6 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0025/environment/workdir/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The given vectors are linearly dependent over the rationals. -/ +theorem vectors_dependent : ¬ LinearIndependent ℚ ![(![-4, -1] : Fin 2 → ℚ), ![4, 1]] := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-t0025/instruction.md b/tasks/linear-algebra/linear-algebra-independence-d1-t0025/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..30aef38e4bb9d739801d3f21fd414717c4b3b025 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0025/instruction.md @@ -0,0 +1,14 @@ +# Linear independence of explicit vectors + +Prove the following statement. + +In \(\mathbb{Q}^2\) consider the vectors \(\begin{pmatrix} -4 \\ -1 \end{pmatrix}\), \(\begin{pmatrix} 4 \\ 1 \end{pmatrix}\). Show that they are not linearly independent over \(\mathbb{Q}\). + +## 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/linear-algebra/linear-algebra-independence-d1-t0025/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-independence-d1-t0025/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..5609407ca1b85fac0d12738c7d9d9185d8c8f655 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0025/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The given vectors are linearly dependent over the rationals. -/ +theorem vectors_dependent : ¬ LinearIndependent ℚ ![(![-4, -1] : Fin 2 → ℚ), ![4, 1]] := by + rw [Fintype.not_linearIndependent_iff] + refine ⟨![(-1 : ℚ), (-1 : ℚ)], ?_, 1, by simp⟩ + ext i + fin_cases i <;> simp [Fin.sum_univ_two] <;> norm_num diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-t0025/solution/solve.sh b/tasks/linear-algebra/linear-algebra-independence-d1-t0025/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0025/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-t0025/task.toml b/tasks/linear-algebra/linear-algebra-independence-d1-t0025/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..466e5b7a080e72f43968fbabe4d398ce3beb71ef --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0025/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "linear-algebra" +tags = ["linear-algebra", "independence", "msc-15", "train", "lean4"] +msc = "15" +family = "independence" +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/linear-algebra/linear-algebra-independence-d1-t0025/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-independence-d1-t0025/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d1-t0025/tests/grade.py b/tasks/linear-algebra/linear-algebra-independence-d1-t0025/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d1-t0025/tests/spec.json b/tasks/linear-algebra/linear-algebra-independence-d1-t0025/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..144336c31fea24997adca3f6edf96997e82702ed --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0025/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The given vectors are linearly dependent over the rationals. -/\ntheorem vectors_dependent : ¬ LinearIndependent ℚ ![(![-4, -1] : Fin 2 → ℚ), ![4, 1]] := by\n sorry\n", + "targets": [ + { + "name": "vectors_dependent", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-t0025/tests/test.sh b/tasks/linear-algebra/linear-algebra-independence-d1-t0025/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d1-t0037/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-independence-d1-t0037/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0037/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-t0037/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-independence-d1-t0037/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..3aac7eb7637a7910360868c5a831ec4f744ccc1d --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0037/environment/workdir/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The given vectors are linearly independent over the rationals. -/ +theorem vectors_independent : LinearIndependent ℚ ![(![-4, -4] : Fin 2 → ℚ), ![4, 3]] := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-t0037/instruction.md b/tasks/linear-algebra/linear-algebra-independence-d1-t0037/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f8c1a3e744285d86088c0c93c21454c6be1982e8 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0037/instruction.md @@ -0,0 +1,14 @@ +# Linear independence of explicit vectors + +Prove the following statement. + +In \(\mathbb{Q}^2\) consider the vectors \(\begin{pmatrix} -4 \\ -4 \end{pmatrix}\), \(\begin{pmatrix} 4 \\ 3 \end{pmatrix}\). Show that they are linearly independent over \(\mathbb{Q}\). + +## 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/linear-algebra/linear-algebra-independence-d1-t0037/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-independence-d1-t0037/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..63a855a3d61fa17ccd0d620213b16521af83a31d --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0037/solution/Solution.lean @@ -0,0 +1,10 @@ +import Mathlib + +/-- The given vectors are linearly independent over the rationals. -/ +theorem vectors_independent : LinearIndependent ℚ ![(![-4, -4] : Fin 2 → ℚ), ![4, 3]] := by + rw [LinearIndependent.pair_iff] + intro s t h + have h0 := congr_fun h 0 + have h1 := congr_fun h 1 + simp at h0 h1 + constructor <;> linarith diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-t0037/solution/solve.sh b/tasks/linear-algebra/linear-algebra-independence-d1-t0037/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0037/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-t0037/task.toml b/tasks/linear-algebra/linear-algebra-independence-d1-t0037/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bd2ddafdf72d961c6c74448bcf145f25726cf9e6 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0037/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "linear-algebra" +tags = ["linear-algebra", "independence", "msc-15", "train", "lean4"] +msc = "15" +family = "independence" +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/linear-algebra/linear-algebra-independence-d1-t0037/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-independence-d1-t0037/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d1-t0037/tests/grade.py b/tasks/linear-algebra/linear-algebra-independence-d1-t0037/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d1-t0037/tests/spec.json b/tasks/linear-algebra/linear-algebra-independence-d1-t0037/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..e7527f554e3027fcd2a5f7a2f8f31cd483722a0b --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0037/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The given vectors are linearly independent over the rationals. -/\ntheorem vectors_independent : LinearIndependent ℚ ![(![-4, -4] : Fin 2 → ℚ), ![4, 3]] := by\n sorry\n", + "targets": [ + { + "name": "vectors_independent", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-t0037/tests/test.sh b/tasks/linear-algebra/linear-algebra-independence-d1-t0037/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d1-t0049/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-independence-d1-t0049/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0049/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-t0049/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-independence-d1-t0049/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..67bd55d494da086bd9ee7b94119614c5b8a226d1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0049/environment/workdir/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The given vectors are linearly dependent over the rationals. -/ +theorem vectors_dependent : ¬ LinearIndependent ℚ ![(![3, 2] : Fin 2 → ℚ), ![-3, -2]] := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-t0049/instruction.md b/tasks/linear-algebra/linear-algebra-independence-d1-t0049/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..77aa13e966d5747fe336310917a37d17cd6cfe3a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0049/instruction.md @@ -0,0 +1,14 @@ +# Linear independence of explicit vectors + +Prove the following statement. + +In \(\mathbb{Q}^2\) consider the vectors \(\begin{pmatrix} 3 \\ 2 \end{pmatrix}\), \(\begin{pmatrix} -3 \\ -2 \end{pmatrix}\). Show that they are not linearly independent over \(\mathbb{Q}\). + +## 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/linear-algebra/linear-algebra-independence-d1-t0049/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-independence-d1-t0049/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..fc7c2f5c801161992fc1aee1239dc0f34163ac75 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0049/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The given vectors are linearly dependent over the rationals. -/ +theorem vectors_dependent : ¬ LinearIndependent ℚ ![(![3, 2] : Fin 2 → ℚ), ![-3, -2]] := by + rw [Fintype.not_linearIndependent_iff] + refine ⟨![(-1 : ℚ), (-1 : ℚ)], ?_, 1, by simp⟩ + ext i + fin_cases i <;> simp [Fin.sum_univ_two] <;> norm_num diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-t0049/solution/solve.sh b/tasks/linear-algebra/linear-algebra-independence-d1-t0049/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0049/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-t0049/task.toml b/tasks/linear-algebra/linear-algebra-independence-d1-t0049/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..17cf4043aac089df1b8bc2a2695aa97bdd88ba49 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0049/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "linear-algebra" +tags = ["linear-algebra", "independence", "msc-15", "train", "lean4"] +msc = "15" +family = "independence" +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/linear-algebra/linear-algebra-independence-d1-t0049/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-independence-d1-t0049/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d1-t0049/tests/grade.py b/tasks/linear-algebra/linear-algebra-independence-d1-t0049/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d1-t0049/tests/spec.json b/tasks/linear-algebra/linear-algebra-independence-d1-t0049/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..2a7d11f7d077d448bc353d21b97bed8c64ba4fcd --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d1-t0049/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The given vectors are linearly dependent over the rationals. -/\ntheorem vectors_dependent : ¬ LinearIndependent ℚ ![(![3, 2] : Fin 2 → ℚ), ![-3, -2]] := by\n sorry\n", + "targets": [ + { + "name": "vectors_dependent", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-independence-d1-t0049/tests/test.sh b/tasks/linear-algebra/linear-algebra-independence-d1-t0049/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d2-t0041/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-independence-d2-t0041/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d2-t0041/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-independence-d2-t0041/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-independence-d2-t0041/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..b4319ec87652caeb1a136e5b0aef5bb23361eeb6 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d2-t0041/environment/workdir/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The given vectors are linearly independent over the rationals. -/ +theorem vectors_independent : LinearIndependent ℚ ![(![3, 6] : Fin 2 → ℚ), ![5, -5]] := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-independence-d2-t0041/instruction.md b/tasks/linear-algebra/linear-algebra-independence-d2-t0041/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..54e1de9eccbc51854fd7aa7cb8226cadd5a91135 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d2-t0041/instruction.md @@ -0,0 +1,14 @@ +# Linear independence of explicit vectors + +Prove the following statement. + +In \(\mathbb{Q}^2\) consider the vectors \(\begin{pmatrix} 3 \\ 6 \end{pmatrix}\), \(\begin{pmatrix} 5 \\ -5 \end{pmatrix}\). Show that they are linearly independent over \(\mathbb{Q}\). + +## 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/linear-algebra/linear-algebra-independence-d2-t0041/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-independence-d2-t0041/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..f52f0f68b12f964ed79bc3ea4447b32f3d1f0e49 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d2-t0041/solution/Solution.lean @@ -0,0 +1,10 @@ +import Mathlib + +/-- The given vectors are linearly independent over the rationals. -/ +theorem vectors_independent : LinearIndependent ℚ ![(![3, 6] : Fin 2 → ℚ), ![5, -5]] := by + rw [LinearIndependent.pair_iff] + intro s t h + have h0 := congr_fun h 0 + have h1 := congr_fun h 1 + simp at h0 h1 + constructor <;> linarith diff --git a/tasks/linear-algebra/linear-algebra-independence-d2-t0041/solution/solve.sh b/tasks/linear-algebra/linear-algebra-independence-d2-t0041/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d2-t0041/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-independence-d2-t0041/task.toml b/tasks/linear-algebra/linear-algebra-independence-d2-t0041/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8d9e005c2f814318d00add1869cce3b841c49b84 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d2-t0041/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "linear-algebra" +tags = ["linear-algebra", "independence", "msc-15", "train", "lean4"] +msc = "15" +family = "independence" +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/linear-algebra/linear-algebra-independence-d2-t0041/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-independence-d2-t0041/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d2-t0041/tests/grade.py b/tasks/linear-algebra/linear-algebra-independence-d2-t0041/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d2-t0041/tests/spec.json b/tasks/linear-algebra/linear-algebra-independence-d2-t0041/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..fa77b06e38108295238b3afb233d8dad115ddd22 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d2-t0041/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The given vectors are linearly independent over the rationals. -/\ntheorem vectors_independent : LinearIndependent ℚ ![(![3, 6] : Fin 2 → ℚ), ![5, -5]] := by\n sorry\n", + "targets": [ + { + "name": "vectors_independent", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-independence-d2-t0041/tests/test.sh b/tasks/linear-algebra/linear-algebra-independence-d2-t0041/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d2-t0053/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-independence-d2-t0053/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d2-t0053/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-independence-d2-t0053/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-independence-d2-t0053/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..4ed092c63f700c2ef64d01abec8e7a10709f3a7c --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d2-t0053/environment/workdir/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The given vectors are linearly dependent over the rationals. -/ +theorem vectors_dependent : ¬ LinearIndependent ℚ ![(![3, -1] : Fin 2 → ℚ), ![-6, 2]] := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-independence-d2-t0053/instruction.md b/tasks/linear-algebra/linear-algebra-independence-d2-t0053/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..362063232d0b15ef498d201bbd517b74e8cb29f3 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d2-t0053/instruction.md @@ -0,0 +1,14 @@ +# Linear independence of explicit vectors + +Prove the following statement. + +In \(\mathbb{Q}^2\) consider the vectors \(\begin{pmatrix} 3 \\ -1 \end{pmatrix}\), \(\begin{pmatrix} -6 \\ 2 \end{pmatrix}\). Show that they are not linearly independent over \(\mathbb{Q}\). + +## 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/linear-algebra/linear-algebra-independence-d2-t0053/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-independence-d2-t0053/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..5b5d55f14c76512d2081c699e62a60d402c6f9c5 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d2-t0053/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The given vectors are linearly dependent over the rationals. -/ +theorem vectors_dependent : ¬ LinearIndependent ℚ ![(![3, -1] : Fin 2 → ℚ), ![-6, 2]] := by + rw [Fintype.not_linearIndependent_iff] + refine ⟨![(-2 : ℚ), (-1 : ℚ)], ?_, 1, by simp⟩ + ext i + fin_cases i <;> simp [Fin.sum_univ_two] <;> norm_num diff --git a/tasks/linear-algebra/linear-algebra-independence-d2-t0053/solution/solve.sh b/tasks/linear-algebra/linear-algebra-independence-d2-t0053/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d2-t0053/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-independence-d2-t0053/task.toml b/tasks/linear-algebra/linear-algebra-independence-d2-t0053/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3bb63d3a3c81f06fa3d419583d4f4a2070020b29 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d2-t0053/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "linear-algebra" +tags = ["linear-algebra", "independence", "msc-15", "train", "lean4"] +msc = "15" +family = "independence" +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/linear-algebra/linear-algebra-independence-d2-t0053/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-independence-d2-t0053/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d2-t0053/tests/grade.py b/tasks/linear-algebra/linear-algebra-independence-d2-t0053/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d2-t0053/tests/spec.json b/tasks/linear-algebra/linear-algebra-independence-d2-t0053/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..b3201f81268ca1562bfa3019b4f4afc43f5a71f9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d2-t0053/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The given vectors are linearly dependent over the rationals. -/\ntheorem vectors_dependent : ¬ LinearIndependent ℚ ![(![3, -1] : Fin 2 → ℚ), ![-6, 2]] := by\n sorry\n", + "targets": [ + { + "name": "vectors_dependent", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-independence-d2-t0053/tests/test.sh b/tasks/linear-algebra/linear-algebra-independence-d2-t0053/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d2-t0065/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-independence-d2-t0065/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d2-t0065/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-independence-d2-t0065/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-independence-d2-t0065/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..629032ef1c9a40be6125eaea41d4eaf82a85717d --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d2-t0065/environment/workdir/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The given vectors are linearly dependent over the rationals. -/ +theorem vectors_dependent : ¬ LinearIndependent ℚ ![(![0, 6] : Fin 2 → ℚ), ![0, -6]] := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-independence-d2-t0065/instruction.md b/tasks/linear-algebra/linear-algebra-independence-d2-t0065/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..af7a0454c9e5dbf40b30b2419456b085484eae6a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d2-t0065/instruction.md @@ -0,0 +1,14 @@ +# Linear independence of explicit vectors + +Prove the following statement. + +In \(\mathbb{Q}^2\) consider the vectors \(\begin{pmatrix} 0 \\ 6 \end{pmatrix}\), \(\begin{pmatrix} 0 \\ -6 \end{pmatrix}\). Show that they are not linearly independent over \(\mathbb{Q}\). + +## 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/linear-algebra/linear-algebra-independence-d2-t0065/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-independence-d2-t0065/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..443aacefca7add82411d755529d6ec7f9ed61c04 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d2-t0065/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The given vectors are linearly dependent over the rationals. -/ +theorem vectors_dependent : ¬ LinearIndependent ℚ ![(![0, 6] : Fin 2 → ℚ), ![0, -6]] := by + rw [Fintype.not_linearIndependent_iff] + refine ⟨![(-1 : ℚ), (-1 : ℚ)], ?_, 1, by simp⟩ + ext i + fin_cases i <;> simp [Fin.sum_univ_two] <;> norm_num diff --git a/tasks/linear-algebra/linear-algebra-independence-d2-t0065/solution/solve.sh b/tasks/linear-algebra/linear-algebra-independence-d2-t0065/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d2-t0065/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-independence-d2-t0065/task.toml b/tasks/linear-algebra/linear-algebra-independence-d2-t0065/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..942d362f0fbdc0a4fee4afae64ba2078ee7102f6 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d2-t0065/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "linear-algebra" +tags = ["linear-algebra", "independence", "msc-15", "train", "lean4"] +msc = "15" +family = "independence" +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/linear-algebra/linear-algebra-independence-d2-t0065/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-independence-d2-t0065/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d2-t0065/tests/grade.py b/tasks/linear-algebra/linear-algebra-independence-d2-t0065/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d2-t0065/tests/spec.json b/tasks/linear-algebra/linear-algebra-independence-d2-t0065/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..ab7eff26a90583c0bb31c0f7e5bf7fef80c83fac --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d2-t0065/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The given vectors are linearly dependent over the rationals. -/\ntheorem vectors_dependent : ¬ LinearIndependent ℚ ![(![0, 6] : Fin 2 → ℚ), ![0, -6]] := by\n sorry\n", + "targets": [ + { + "name": "vectors_dependent", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-independence-d2-t0065/tests/test.sh b/tasks/linear-algebra/linear-algebra-independence-d2-t0065/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d2-t0077/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-independence-d2-t0077/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d2-t0077/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-independence-d2-t0077/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-independence-d2-t0077/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..8bf42c5c0825616d03fd32ea1548401b0407ef8f --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d2-t0077/environment/workdir/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The given vectors are linearly independent over the rationals. -/ +theorem vectors_independent : LinearIndependent ℚ ![(![-2, -1] : Fin 2 → ℚ), ![-6, -6]] := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-independence-d2-t0077/instruction.md b/tasks/linear-algebra/linear-algebra-independence-d2-t0077/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bf08cd34329815cac77afe2587b4c59b09248c9b --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d2-t0077/instruction.md @@ -0,0 +1,14 @@ +# Linear independence of explicit vectors + +Prove the following statement. + +In \(\mathbb{Q}^2\) consider the vectors \(\begin{pmatrix} -2 \\ -1 \end{pmatrix}\), \(\begin{pmatrix} -6 \\ -6 \end{pmatrix}\). Show that they are linearly independent over \(\mathbb{Q}\). + +## 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/linear-algebra/linear-algebra-independence-d2-t0077/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-independence-d2-t0077/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..a513c28fdff106ae0c6f6080ee306361080fa3b0 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d2-t0077/solution/Solution.lean @@ -0,0 +1,10 @@ +import Mathlib + +/-- The given vectors are linearly independent over the rationals. -/ +theorem vectors_independent : LinearIndependent ℚ ![(![-2, -1] : Fin 2 → ℚ), ![-6, -6]] := by + rw [LinearIndependent.pair_iff] + intro s t h + have h0 := congr_fun h 0 + have h1 := congr_fun h 1 + simp at h0 h1 + constructor <;> linarith diff --git a/tasks/linear-algebra/linear-algebra-independence-d2-t0077/solution/solve.sh b/tasks/linear-algebra/linear-algebra-independence-d2-t0077/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d2-t0077/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-independence-d2-t0077/task.toml b/tasks/linear-algebra/linear-algebra-independence-d2-t0077/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6568f99734654f2fcf2e6f9760f1f184b5b086ed --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d2-t0077/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "linear-algebra" +tags = ["linear-algebra", "independence", "msc-15", "train", "lean4"] +msc = "15" +family = "independence" +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/linear-algebra/linear-algebra-independence-d2-t0077/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-independence-d2-t0077/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d2-t0077/tests/grade.py b/tasks/linear-algebra/linear-algebra-independence-d2-t0077/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d2-t0077/tests/spec.json b/tasks/linear-algebra/linear-algebra-independence-d2-t0077/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..3622e953a2c9a60a13a9af804611af512a08acd3 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d2-t0077/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The given vectors are linearly independent over the rationals. -/\ntheorem vectors_independent : LinearIndependent ℚ ![(![-2, -1] : Fin 2 → ℚ), ![-6, -6]] := by\n sorry\n", + "targets": [ + { + "name": "vectors_independent", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-independence-d2-t0077/tests/test.sh b/tasks/linear-algebra/linear-algebra-independence-d2-t0077/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d3-e0009/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-independence-d3-e0009/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d3-e0009/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-independence-d3-e0009/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-independence-d3-e0009/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..c2194f9432e66f73d909062ac33089ef25011192 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d3-e0009/environment/workdir/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The given vectors are linearly dependent over the rationals. -/ +theorem vectors_dependent : ¬ LinearIndependent ℚ ![(![6, 0, -4] : Fin 3 → ℚ), ![4, 6, 3], ![-4, 12, 14]] := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-independence-d3-e0009/instruction.md b/tasks/linear-algebra/linear-algebra-independence-d3-e0009/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e8f74adc590d94154d4838a7ca289195798341d8 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d3-e0009/instruction.md @@ -0,0 +1,14 @@ +# Linear independence of explicit vectors + +Prove the following statement. + +In \(\mathbb{Q}^3\) consider the vectors \(\begin{pmatrix} 6 \\ 0 \\ -4 \end{pmatrix}\), \(\begin{pmatrix} 4 \\ 6 \\ 3 \end{pmatrix}\), \(\begin{pmatrix} -4 \\ 12 \\ 14 \end{pmatrix}\). Show that they are not linearly independent over \(\mathbb{Q}\). + +## 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/linear-algebra/linear-algebra-independence-d3-e0009/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-independence-d3-e0009/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..d96ec84338b5feb4863a46c78848d2c4e883bc68 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d3-e0009/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The given vectors are linearly dependent over the rationals. -/ +theorem vectors_dependent : ¬ LinearIndependent ℚ ![(![6, 0, -4] : Fin 3 → ℚ), ![4, 6, 3], ![-4, 12, 14]] := by + rw [Fintype.not_linearIndependent_iff] + refine ⟨![(-2 : ℚ), (2 : ℚ), (-1 : ℚ)], ?_, 2, by simp⟩ + ext i + fin_cases i <;> simp [Fin.sum_univ_three] <;> norm_num diff --git a/tasks/linear-algebra/linear-algebra-independence-d3-e0009/solution/solve.sh b/tasks/linear-algebra/linear-algebra-independence-d3-e0009/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d3-e0009/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-independence-d3-e0009/task.toml b/tasks/linear-algebra/linear-algebra-independence-d3-e0009/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a0765fee079fa95cd969220f4db2c35c0e8850a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d3-e0009/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "linear-algebra" +tags = ["linear-algebra", "independence", "msc-15", "eval", "lean4"] +msc = "15" +family = "independence" +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/linear-algebra/linear-algebra-independence-d3-e0009/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-independence-d3-e0009/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d3-e0009/tests/grade.py b/tasks/linear-algebra/linear-algebra-independence-d3-e0009/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d3-e0009/tests/spec.json b/tasks/linear-algebra/linear-algebra-independence-d3-e0009/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..201ea97fe5857d230f8cfaa0d7453d82d4089a58 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d3-e0009/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The given vectors are linearly dependent over the rationals. -/\ntheorem vectors_dependent : ¬ LinearIndependent ℚ ![(![6, 0, -4] : Fin 3 → ℚ), ![4, 6, 3], ![-4, 12, 14]] := by\n sorry\n", + "targets": [ + { + "name": "vectors_dependent", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-independence-d3-e0009/tests/test.sh b/tasks/linear-algebra/linear-algebra-independence-d3-e0009/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d3-t0009/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-independence-d3-t0009/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d3-t0009/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-independence-d3-t0009/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-independence-d3-t0009/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..eaaac2a782a0fcbcdc51150f9492add41cac7198 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d3-t0009/environment/workdir/Solution.lean @@ -0,0 +1,5 @@ +import Mathlib + +/-- The given vectors are linearly independent over the rationals. -/ +theorem vectors_independent : LinearIndependent ℚ ![(![6, -6, 5] : Fin 3 → ℚ), ![-5, 6, 2], ![-1, -5, 0]] := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-independence-d3-t0009/instruction.md b/tasks/linear-algebra/linear-algebra-independence-d3-t0009/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0ac1d7544f8870f3e2f7b911415fde680f2de472 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d3-t0009/instruction.md @@ -0,0 +1,14 @@ +# Linear independence of explicit vectors + +Prove the following statement. + +In \(\mathbb{Q}^3\) consider the vectors \(\begin{pmatrix} 6 \\ -6 \\ 5 \end{pmatrix}\), \(\begin{pmatrix} -5 \\ 6 \\ 2 \end{pmatrix}\), \(\begin{pmatrix} -1 \\ -5 \\ 0 \end{pmatrix}\). Show that they are linearly independent over \(\mathbb{Q}\). + +## 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/linear-algebra/linear-algebra-independence-d3-t0009/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-independence-d3-t0009/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..1785bca4f955f8557c99fd0314ad1bf11508562d --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d3-t0009/solution/Solution.lean @@ -0,0 +1,12 @@ +import Mathlib + +/-- The given vectors are linearly independent over the rationals. -/ +theorem vectors_independent : LinearIndependent ℚ ![(![6, -6, 5] : Fin 3 → ℚ), ![-5, 6, 2], ![-1, -5, 0]] := by + rw [Fintype.linearIndependent_iff] + intro g hg + have h0 := congr_fun hg 0 + have h1 := congr_fun hg 1 + have h2 := congr_fun hg 2 + simp [Fin.sum_univ_three] at h0 h1 h2 + intro i + fin_cases i <;> simp <;> linarith diff --git a/tasks/linear-algebra/linear-algebra-independence-d3-t0009/solution/solve.sh b/tasks/linear-algebra/linear-algebra-independence-d3-t0009/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d3-t0009/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-independence-d3-t0009/task.toml b/tasks/linear-algebra/linear-algebra-independence-d3-t0009/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..64e2993703ae629a8bd10aa62834a3a959dfdc20 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d3-t0009/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "linear-algebra" +tags = ["linear-algebra", "independence", "msc-15", "train", "lean4"] +msc = "15" +family = "independence" +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/linear-algebra/linear-algebra-independence-d3-t0009/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-independence-d3-t0009/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d3-t0009/tests/grade.py b/tasks/linear-algebra/linear-algebra-independence-d3-t0009/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-independence-d3-t0009/tests/spec.json b/tasks/linear-algebra/linear-algebra-independence-d3-t0009/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..076b69ef2b0d4cf9c83a900f8564333feed01ad9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-d3-t0009/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The given vectors are linearly independent over the rationals. -/\ntheorem vectors_independent : LinearIndependent ℚ ![(![6, -6, 5] : Fin 3 → ℚ), ![-5, 6, 2], ![-1, -5, 0]] := by\n sorry\n", + "targets": [ + { + "name": "vectors_independent", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-independence-d3-t0009/tests/test.sh b/tasks/linear-algebra/linear-algebra-independence-d3-t0009/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-independence-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/linear-algebra/linear-algebra-linear_map-d1-e0002/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-linear_map-d1-e0002/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-e0002/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d1-e0002/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-linear_map-d1-e0002/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..7e01bd1e005d45e88b84c0abcd170e46805bc1c6 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-e0002/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- x - p x lies in the kernel of an idempotent map p. -/ +theorem sub_proj_mem_ker {V : Type*} [AddCommGroup V] [Module ℚ V] (q : V →ₗ[ℚ] V) (hp : ∀ x, q (q x) = q x) (u : V) : + u - q u ∈ LinearMap.ker q := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d1-e0002/instruction.md b/tasks/linear-algebra/linear-algebra-linear_map-d1-e0002/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..97552768b18cd7a1b7cbd5ec98a925d7b8d9b198 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-e0002/instruction.md @@ -0,0 +1,14 @@ +# Kernels, ranges and projections + +Prove the following statement. + +Let \(q : V \to V\) be a linear map over \(\mathbb{Q}\) with \(q(v(v)) = v(v)\) for every \(v\). Then \(u - q(u)\) lies in the kernel of \(q\) for every \(u \in V\). + +## 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/linear-algebra/linear-algebra-linear_map-d1-e0002/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-linear_map-d1-e0002/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..66c9b083dc40a447019a067f7572d185c786430d --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-e0002/solution/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- x - p x lies in the kernel of an idempotent map p. -/ +theorem sub_proj_mem_ker {V : Type*} [AddCommGroup V] [Module ℚ V] (q : V →ₗ[ℚ] V) (hp : ∀ x, q (q x) = q x) (u : V) : + u - q u ∈ LinearMap.ker q := by + rw [LinearMap.mem_ker, map_sub, hp, sub_self] diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d1-e0002/solution/solve.sh b/tasks/linear-algebra/linear-algebra-linear_map-d1-e0002/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-e0002/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d1-e0002/task.toml b/tasks/linear-algebra/linear-algebra-linear_map-d1-e0002/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a3e5536e6e1eda7c4b32ac3247b09198cb79f8fc --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-e0002/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "linear-algebra" +tags = ["linear-algebra", "linear_map", "msc-15", "eval", "lean4"] +msc = "15" +family = "linear_map" +split = "eval" +seed = 10002 + +[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/linear-algebra/linear-algebra-linear_map-d1-e0002/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-linear_map-d1-e0002/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-e0002/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/linear-algebra/linear-algebra-linear_map-d1-e0002/tests/grade.py b/tasks/linear-algebra/linear-algebra-linear_map-d1-e0002/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-e0002/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/linear-algebra/linear-algebra-linear_map-d1-e0002/tests/spec.json b/tasks/linear-algebra/linear-algebra-linear_map-d1-e0002/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..915939f9a77ef262148c92c8376b6774674d2956 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-e0002/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- x - p x lies in the kernel of an idempotent map p. -/\ntheorem sub_proj_mem_ker {V : Type*} [AddCommGroup V] [Module ℚ V] (q : V →ₗ[ℚ] V) (hp : ∀ x, q (q x) = q x) (u : V) :\n u - q u ∈ LinearMap.ker q := by\n sorry\n", + "targets": [ + { + "name": "sub_proj_mem_ker", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d1-e0002/tests/test.sh b/tasks/linear-algebra/linear-algebra-linear_map-d1-e0002/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-e0002/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/linear-algebra/linear-algebra-linear_map-d1-t0002/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0002/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0002/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d1-t0002/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0002/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..6159b4b43af5c39e5052ad8568f68410a6bbd912 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0002/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The kernel is closed under linear combinations. -/ +theorem kernel_combination {V W : Type*} [AddCommGroup V] [Module ℝ V] [AddCommGroup W] [Module ℝ W] (f : V →ₗ[ℝ] W) {x y : V} + (hx : f x = 0) (hy : f y = 0) : f ((3 : ℝ) • x + (4 : ℝ) • y) = 0 := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d1-t0002/instruction.md b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0002/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ee4c3103f76c2f74f23867b97cb51e81b48e2080 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0002/instruction.md @@ -0,0 +1,14 @@ +# Kernels, ranges and projections + +Prove the following statement. + +Let \(f : V \to W\) be a linear map of vector spaces over \(\mathbb{R}\) and \(x, y \in V\) with \(f(x) = 0\) and \(f(y) = 0\). Then \(f(3x + 4y) = 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/linear-algebra/linear-algebra-linear_map-d1-t0002/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0002/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..a5d5e07ebcb6d38e1daabe4c991ba378c9e1efb7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0002/solution/Solution.lean @@ -0,0 +1,7 @@ +import Mathlib + +/-- The kernel is closed under linear combinations. -/ +theorem kernel_combination {V W : Type*} [AddCommGroup V] [Module ℝ V] [AddCommGroup W] [Module ℝ W] (f : V →ₗ[ℝ] W) {x y : V} + (hx : f x = 0) (hy : f y = 0) : f ((3 : ℝ) • x + (4 : ℝ) • y) = 0 := by + rw [map_add, map_smul, map_smul, hx, hy] + simp diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d1-t0002/solution/solve.sh b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0002/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0002/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d1-t0002/task.toml b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0002/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..19075d63d5b46f1e23266e7793f5f30ccb8fc98e --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0002/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "linear-algebra" +tags = ["linear-algebra", "linear_map", "msc-15", "train", "lean4"] +msc = "15" +family = "linear_map" +split = "train" +seed = 2 + +[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/linear-algebra/linear-algebra-linear_map-d1-t0002/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0002/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0002/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/linear-algebra/linear-algebra-linear_map-d1-t0002/tests/grade.py b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0002/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0002/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/linear-algebra/linear-algebra-linear_map-d1-t0002/tests/spec.json b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0002/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..05b0676bf676072c3bd4b1e4a68e38fb051e8667 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0002/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The kernel is closed under linear combinations. -/\ntheorem kernel_combination {V W : Type*} [AddCommGroup V] [Module ℝ V] [AddCommGroup W] [Module ℝ W] (f : V →ₗ[ℝ] W) {x y : V}\n (hx : f x = 0) (hy : f y = 0) : f ((3 : ℝ) • x + (4 : ℝ) • y) = 0 := by\n sorry\n", + "targets": [ + { + "name": "kernel_combination", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d1-t0002/tests/test.sh b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0002/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0002/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/linear-algebra/linear-algebra-linear_map-d1-t0026/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0026/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0026/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d1-t0026/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0026/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..6a4b8f508d646c0c9921a36856559dad0d641a3b --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0026/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The kernel is closed under linear combinations. -/ +theorem kernel_combination {V W : Type*} [AddCommGroup V] [Module ℚ V] [AddCommGroup W] [Module ℚ W] (f : V →ₗ[ℚ] W) {a b : V} + (hx : f a = 0) (hy : f b = 0) : f ((7 : ℚ) • a + (3 : ℚ) • b) = 0 := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d1-t0026/instruction.md b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0026/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d5a57ffa9f5d4eb5f7c1d480e9eee65db57ec388 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0026/instruction.md @@ -0,0 +1,14 @@ +# Kernels, ranges and projections + +Prove the following statement. + +Let \(f : V \to W\) be a linear map of vector spaces over \(\mathbb{Q}\) and \(a, b \in V\) with \(f(a) = 0\) and \(f(b) = 0\). Then \(f(7a + 3b) = 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/linear-algebra/linear-algebra-linear_map-d1-t0026/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0026/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..42d93d66c89ad8a3665ff62f608bc1dea074272d --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0026/solution/Solution.lean @@ -0,0 +1,7 @@ +import Mathlib + +/-- The kernel is closed under linear combinations. -/ +theorem kernel_combination {V W : Type*} [AddCommGroup V] [Module ℚ V] [AddCommGroup W] [Module ℚ W] (f : V →ₗ[ℚ] W) {a b : V} + (hx : f a = 0) (hy : f b = 0) : f ((7 : ℚ) • a + (3 : ℚ) • b) = 0 := by + rw [map_add, map_smul, map_smul, hx, hy] + simp diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d1-t0026/solution/solve.sh b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0026/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0026/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d1-t0026/task.toml b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0026/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4384212d4282c9c92b06c4f6b7309ec7b6bfe5cc --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0026/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "linear-algebra" +tags = ["linear-algebra", "linear_map", "msc-15", "train", "lean4"] +msc = "15" +family = "linear_map" +split = "train" +seed = 26 + +[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/linear-algebra/linear-algebra-linear_map-d1-t0026/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0026/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0026/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/linear-algebra/linear-algebra-linear_map-d1-t0026/tests/grade.py b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0026/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0026/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/linear-algebra/linear-algebra-linear_map-d1-t0026/tests/spec.json b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0026/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..92a2463f61662131059c9acff4ebb3c4e6d53f8e --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0026/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The kernel is closed under linear combinations. -/\ntheorem kernel_combination {V W : Type*} [AddCommGroup V] [Module ℚ V] [AddCommGroup W] [Module ℚ W] (f : V →ₗ[ℚ] W) {a b : V}\n (hx : f a = 0) (hy : f b = 0) : f ((7 : ℚ) • a + (3 : ℚ) • b) = 0 := by\n sorry\n", + "targets": [ + { + "name": "kernel_combination", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d1-t0026/tests/test.sh b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0026/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0026/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/linear-algebra/linear-algebra-linear_map-d1-t0050/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0050/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0050/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d1-t0050/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0050/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..1b66847f78684c30a225c3f5e7faaddf298b767c --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0050/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- x - p x lies in the kernel of an idempotent map p. -/ +theorem sub_proj_mem_ker {V : Type*} [AddCommGroup V] [Module ℝ V] (e : V →ₗ[ℝ] V) (hp : ∀ x, e (e x) = e x) (a : V) : + a - e a ∈ LinearMap.ker e := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d1-t0050/instruction.md b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0050/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f5f7afefc697ea0770c6539c1ca8d8abe6df4c31 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0050/instruction.md @@ -0,0 +1,14 @@ +# Kernels, ranges and projections + +Prove the following statement. + +Let \(e : V \to V\) be a linear map over \(\mathbb{R}\) with \(e(v(v)) = v(v)\) for every \(v\). Then \(a - e(a)\) lies in the kernel of \(e\) for every \(a \in V\). + +## 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/linear-algebra/linear-algebra-linear_map-d1-t0050/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0050/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..abb5f825267b0a64ed7eb711979c1a294b689aeb --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0050/solution/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- x - p x lies in the kernel of an idempotent map p. -/ +theorem sub_proj_mem_ker {V : Type*} [AddCommGroup V] [Module ℝ V] (e : V →ₗ[ℝ] V) (hp : ∀ x, e (e x) = e x) (a : V) : + a - e a ∈ LinearMap.ker e := by + rw [LinearMap.mem_ker, map_sub, hp, sub_self] diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d1-t0050/solution/solve.sh b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0050/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0050/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d1-t0050/task.toml b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0050/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..209cc827db1c1fe4697bb03ea3aa5da33ddba058 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0050/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "linear-algebra" +tags = ["linear-algebra", "linear_map", "msc-15", "train", "lean4"] +msc = "15" +family = "linear_map" +split = "train" +seed = 50 + +[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/linear-algebra/linear-algebra-linear_map-d1-t0050/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0050/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0050/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/linear-algebra/linear-algebra-linear_map-d1-t0050/tests/grade.py b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0050/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0050/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/linear-algebra/linear-algebra-linear_map-d1-t0050/tests/spec.json b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0050/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..26895b1a6f8022a654f3252b0eb4e53a81724822 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0050/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- x - p x lies in the kernel of an idempotent map p. -/\ntheorem sub_proj_mem_ker {V : Type*} [AddCommGroup V] [Module ℝ V] (e : V →ₗ[ℝ] V) (hp : ∀ x, e (e x) = e x) (a : V) :\n a - e a ∈ LinearMap.ker e := by\n sorry\n", + "targets": [ + { + "name": "sub_proj_mem_ker", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d1-t0050/tests/test.sh b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0050/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0050/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/linear-algebra/linear-algebra-linear_map-d1-t0074/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0074/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0074/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d1-t0074/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0074/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..7e01bd1e005d45e88b84c0abcd170e46805bc1c6 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0074/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- x - p x lies in the kernel of an idempotent map p. -/ +theorem sub_proj_mem_ker {V : Type*} [AddCommGroup V] [Module ℚ V] (q : V →ₗ[ℚ] V) (hp : ∀ x, q (q x) = q x) (u : V) : + u - q u ∈ LinearMap.ker q := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d1-t0074/instruction.md b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0074/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..97552768b18cd7a1b7cbd5ec98a925d7b8d9b198 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0074/instruction.md @@ -0,0 +1,14 @@ +# Kernels, ranges and projections + +Prove the following statement. + +Let \(q : V \to V\) be a linear map over \(\mathbb{Q}\) with \(q(v(v)) = v(v)\) for every \(v\). Then \(u - q(u)\) lies in the kernel of \(q\) for every \(u \in V\). + +## 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/linear-algebra/linear-algebra-linear_map-d1-t0074/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0074/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..66c9b083dc40a447019a067f7572d185c786430d --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0074/solution/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- x - p x lies in the kernel of an idempotent map p. -/ +theorem sub_proj_mem_ker {V : Type*} [AddCommGroup V] [Module ℚ V] (q : V →ₗ[ℚ] V) (hp : ∀ x, q (q x) = q x) (u : V) : + u - q u ∈ LinearMap.ker q := by + rw [LinearMap.mem_ker, map_sub, hp, sub_self] diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d1-t0074/solution/solve.sh b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0074/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0074/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d1-t0074/task.toml b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0074/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..07bd5dc3f75270703a00c5f49ff51460be2e5f21 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0074/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "linear-algebra" +tags = ["linear-algebra", "linear_map", "msc-15", "train", "lean4"] +msc = "15" +family = "linear_map" +split = "train" +seed = 74 + +[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/linear-algebra/linear-algebra-linear_map-d1-t0074/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0074/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0074/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/linear-algebra/linear-algebra-linear_map-d1-t0074/tests/grade.py b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0074/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0074/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/linear-algebra/linear-algebra-linear_map-d1-t0074/tests/spec.json b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0074/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..915939f9a77ef262148c92c8376b6774674d2956 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0074/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- x - p x lies in the kernel of an idempotent map p. -/\ntheorem sub_proj_mem_ker {V : Type*} [AddCommGroup V] [Module ℚ V] (q : V →ₗ[ℚ] V) (hp : ∀ x, q (q x) = q x) (u : V) :\n u - q u ∈ LinearMap.ker q := by\n sorry\n", + "targets": [ + { + "name": "sub_proj_mem_ker", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d1-t0074/tests/test.sh b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0074/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d1-t0074/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/linear-algebra/linear-algebra-linear_map-d2-e0018/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-linear_map-d2-e0018/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d2-e0018/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d2-e0018/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-linear_map-d2-e0018/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..7bb1be7d5363b41c19ac3f2052faf44c32e03b05 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d2-e0018/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A nonzero scalar multiple has the same kernel. -/ +theorem ker_smul_eq {V W : Type*} [AddCommGroup V] [Module ℝ V] [AddCommGroup W] [Module ℝ W] (f : V →ₗ[ℝ] W) : + LinearMap.ker ((-1 : ℝ) • f) = LinearMap.ker f := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d2-e0018/instruction.md b/tasks/linear-algebra/linear-algebra-linear_map-d2-e0018/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fc156206e8110f9c67e9d2440637b7d757708e68 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d2-e0018/instruction.md @@ -0,0 +1,14 @@ +# Kernels, ranges and projections + +Prove the following statement. + +Let \(f : V \to W\) be a linear map of vector spaces over \(\mathbb{R}\). Then the kernel of \(-1f\) equals the kernel of \(f\). + +## 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/linear-algebra/linear-algebra-linear_map-d2-e0018/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-linear_map-d2-e0018/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..97fb5104802b6970a1353200656cff7a84e4d651 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d2-e0018/solution/Solution.lean @@ -0,0 +1,13 @@ +import Mathlib + +/-- A nonzero scalar multiple has the same kernel. -/ +theorem ker_smul_eq {V W : Type*} [AddCommGroup V] [Module ℝ V] [AddCommGroup W] [Module ℝ W] (f : V →ₗ[ℝ] W) : + LinearMap.ker ((-1 : ℝ) • f) = LinearMap.ker f := by + ext x + simp only [LinearMap.mem_ker, LinearMap.smul_apply, smul_eq_zero] + constructor + · rintro (h | h) + · norm_num at h + · exact h + · intro h + exact Or.inr h diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d2-e0018/solution/solve.sh b/tasks/linear-algebra/linear-algebra-linear_map-d2-e0018/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d2-e0018/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d2-e0018/task.toml b/tasks/linear-algebra/linear-algebra-linear_map-d2-e0018/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ee0de38bac8aa7e9c99c490d7b81697ce4a9f8d2 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d2-e0018/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "linear-algebra" +tags = ["linear-algebra", "linear_map", "msc-15", "eval", "lean4"] +msc = "15" +family = "linear_map" +split = "eval" +seed = 10018 + +[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/linear-algebra/linear-algebra-linear_map-d2-e0018/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-linear_map-d2-e0018/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d2-e0018/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/linear-algebra/linear-algebra-linear_map-d2-e0018/tests/grade.py b/tasks/linear-algebra/linear-algebra-linear_map-d2-e0018/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d2-e0018/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/linear-algebra/linear-algebra-linear_map-d2-e0018/tests/spec.json b/tasks/linear-algebra/linear-algebra-linear_map-d2-e0018/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..bc997ac17965c2511867d15edecdb21b994f0e97 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d2-e0018/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A nonzero scalar multiple has the same kernel. -/\ntheorem ker_smul_eq {V W : Type*} [AddCommGroup V] [Module ℝ V] [AddCommGroup W] [Module ℝ W] (f : V →ₗ[ℝ] W) :\n LinearMap.ker ((-1 : ℝ) • f) = LinearMap.ker f := by\n sorry\n", + "targets": [ + { + "name": "ker_smul_eq", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d2-e0018/tests/test.sh b/tasks/linear-algebra/linear-algebra-linear_map-d2-e0018/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d2-e0018/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/linear-algebra/linear-algebra-linear_map-d2-t0066/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-linear_map-d2-t0066/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d2-t0066/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d2-t0066/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-linear_map-d2-t0066/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..7bb1be7d5363b41c19ac3f2052faf44c32e03b05 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d2-t0066/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- A nonzero scalar multiple has the same kernel. -/ +theorem ker_smul_eq {V W : Type*} [AddCommGroup V] [Module ℝ V] [AddCommGroup W] [Module ℝ W] (f : V →ₗ[ℝ] W) : + LinearMap.ker ((-1 : ℝ) • f) = LinearMap.ker f := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d2-t0066/instruction.md b/tasks/linear-algebra/linear-algebra-linear_map-d2-t0066/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fc156206e8110f9c67e9d2440637b7d757708e68 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d2-t0066/instruction.md @@ -0,0 +1,14 @@ +# Kernels, ranges and projections + +Prove the following statement. + +Let \(f : V \to W\) be a linear map of vector spaces over \(\mathbb{R}\). Then the kernel of \(-1f\) equals the kernel of \(f\). + +## 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/linear-algebra/linear-algebra-linear_map-d2-t0066/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-linear_map-d2-t0066/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..855ee8059ba501f22dcba967efc25d9830d7f7f6 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d2-t0066/solution/Solution.lean @@ -0,0 +1,13 @@ +import Mathlib + +/-- A nonzero scalar multiple has the same kernel. -/ +theorem ker_smul_eq {V W : Type*} [AddCommGroup V] [Module ℝ V] [AddCommGroup W] [Module ℝ W] (f : V →ₗ[ℝ] W) : + LinearMap.ker ((-1 : ℝ) • f) = LinearMap.ker f := by + ext u + simp only [LinearMap.mem_ker, LinearMap.smul_apply, smul_eq_zero] + constructor + · rintro (h | h) + · norm_num at h + · exact h + · intro h + exact Or.inr h diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d2-t0066/solution/solve.sh b/tasks/linear-algebra/linear-algebra-linear_map-d2-t0066/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d2-t0066/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d2-t0066/task.toml b/tasks/linear-algebra/linear-algebra-linear_map-d2-t0066/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..12b3317ee585cc668ba7e23021f71b42f7da25e3 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d2-t0066/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "linear-algebra" +tags = ["linear-algebra", "linear_map", "msc-15", "train", "lean4"] +msc = "15" +family = "linear_map" +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/linear-algebra/linear-algebra-linear_map-d2-t0066/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-linear_map-d2-t0066/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-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/linear-algebra/linear-algebra-linear_map-d2-t0066/tests/grade.py b/tasks/linear-algebra/linear-algebra-linear_map-d2-t0066/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-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/linear-algebra/linear-algebra-linear_map-d2-t0066/tests/spec.json b/tasks/linear-algebra/linear-algebra-linear_map-d2-t0066/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..bc997ac17965c2511867d15edecdb21b994f0e97 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d2-t0066/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- A nonzero scalar multiple has the same kernel. -/\ntheorem ker_smul_eq {V W : Type*} [AddCommGroup V] [Module ℝ V] [AddCommGroup W] [Module ℝ W] (f : V →ₗ[ℝ] W) :\n LinearMap.ker ((-1 : ℝ) • f) = LinearMap.ker f := by\n sorry\n", + "targets": [ + { + "name": "ker_smul_eq", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d2-t0066/tests/test.sh b/tasks/linear-algebra/linear-algebra-linear_map-d2-t0066/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-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/linear-algebra/linear-algebra-linear_map-d3-e0010/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-linear_map-d3-e0010/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-e0010/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d3-e0010/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-linear_map-d3-e0010/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..1380b38aad39bd2275594dba8f93a596ed35d76e --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-e0010/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- If p is idempotent then so is id - p, and p kills its image. -/ +theorem complement_idempotent {V : Type*} [AddCommGroup V] [Module ℝ V] (p : V →ₗ[ℝ] V) (hp : p ∘ₗ p = p) : + (LinearMap.id - p) ∘ₗ (LinearMap.id - p) = LinearMap.id - p ∧ p ∘ₗ (LinearMap.id - p) = 0 := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d3-e0010/instruction.md b/tasks/linear-algebra/linear-algebra-linear_map-d3-e0010/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a3da1221dea3ceeae5b73eff44b9dd887ec378e1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-e0010/instruction.md @@ -0,0 +1,14 @@ +# Kernels, ranges and projections + +Prove the following statement. + +Let \(p : V \to V\) be a linear map over \(\mathbb{R}\) with \(p \circ p = p\). Then \(\mathrm{id} - p\) is also idempotent, and \(p \circ (\mathrm{id} - p) = 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/linear-algebra/linear-algebra-linear_map-d3-e0010/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-linear_map-d3-e0010/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..4fb5c3b36a88a04a2bdac91c4f6d8107816b114c --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-e0010/solution/Solution.lean @@ -0,0 +1,7 @@ +import Mathlib + +/-- If p is idempotent then so is id - p, and p kills its image. -/ +theorem complement_idempotent {V : Type*} [AddCommGroup V] [Module ℝ V] (p : V →ₗ[ℝ] V) (hp : p ∘ₗ p = p) : + (LinearMap.id - p) ∘ₗ (LinearMap.id - p) = LinearMap.id - p ∧ p ∘ₗ (LinearMap.id - p) = 0 := by + have hp' : ∀ x, p (p x) = p x := fun x => LinearMap.congr_fun hp x + refine ⟨?_, ?_⟩ <;> ext u <;> simp [hp'] diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d3-e0010/solution/solve.sh b/tasks/linear-algebra/linear-algebra-linear_map-d3-e0010/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-e0010/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d3-e0010/task.toml b/tasks/linear-algebra/linear-algebra-linear_map-d3-e0010/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c3286c2342a1c8f56804917e048e927c0e0dd148 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-e0010/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "linear-algebra" +tags = ["linear-algebra", "linear_map", "msc-15", "eval", "lean4"] +msc = "15" +family = "linear_map" +split = "eval" +seed = 10010 + +[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/linear-algebra/linear-algebra-linear_map-d3-e0010/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-linear_map-d3-e0010/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-e0010/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/linear-algebra/linear-algebra-linear_map-d3-e0010/tests/grade.py b/tasks/linear-algebra/linear-algebra-linear_map-d3-e0010/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-e0010/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/linear-algebra/linear-algebra-linear_map-d3-e0010/tests/spec.json b/tasks/linear-algebra/linear-algebra-linear_map-d3-e0010/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..ad757ad3fb000034b2128e7e1b0a9ba06cc5f413 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-e0010/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- If p is idempotent then so is id - p, and p kills its image. -/\ntheorem complement_idempotent {V : Type*} [AddCommGroup V] [Module ℝ V] (p : V →ₗ[ℝ] V) (hp : p ∘ₗ p = p) :\n (LinearMap.id - p) ∘ₗ (LinearMap.id - p) = LinearMap.id - p ∧ p ∘ₗ (LinearMap.id - p) = 0 := by\n sorry\n", + "targets": [ + { + "name": "complement_idempotent", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d3-e0010/tests/test.sh b/tasks/linear-algebra/linear-algebra-linear_map-d3-e0010/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-e0010/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/linear-algebra/linear-algebra-linear_map-d3-t0010/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0010/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0010/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d3-t0010/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0010/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..3d67a018aecd6074cd477ed48930f1128c267f76 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0010/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- For idempotent p, the kernel of id - p is the range of p. -/ +theorem ker_id_sub {V : Type*} [AddCommGroup V] [Module ℚ V] (e : V →ₗ[ℚ] V) (hp : ∀ x, e (e x) = e x) : + LinearMap.ker (LinearMap.id - e) = LinearMap.range e := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d3-t0010/instruction.md b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0010/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5c6a2b391e7b3decd8f2eb574951c785d33ad488 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0010/instruction.md @@ -0,0 +1,14 @@ +# Kernels, ranges and projections + +Prove the following statement. + +Let \(e : V \to V\) be a linear map over \(\mathbb{Q}\) with \(e(e(x)) = e(x) for every vector x\). Then the kernel of \(\mathrm{id} - e\) equals the range of \(e\). + +## 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/linear-algebra/linear-algebra-linear_map-d3-t0010/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0010/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..b15573c001fa79ca06fcf4fb6af6dba2f812325d --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0010/solution/Solution.lean @@ -0,0 +1,13 @@ +import Mathlib + +/-- For idempotent p, the kernel of id - p is the range of p. -/ +theorem ker_id_sub {V : Type*} [AddCommGroup V] [Module ℚ V] (e : V →ₗ[ℚ] V) (hp : ∀ x, e (e x) = e x) : + LinearMap.ker (LinearMap.id - e) = LinearMap.range e := by + have hp' : ∀ x, e (e x) = e x := hp + ext u + constructor + · intro h + rw [LinearMap.mem_ker, LinearMap.sub_apply, LinearMap.id_apply, sub_eq_zero] at h + exact ⟨u, h.symm⟩ + · rintro ⟨v, rfl⟩ + rw [LinearMap.mem_ker, LinearMap.sub_apply, LinearMap.id_apply, hp', sub_self] diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d3-t0010/solution/solve.sh b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0010/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0010/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d3-t0010/task.toml b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0010/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..95148d9ef8ee1fdc9fe71fd5db11edc2fff0cd35 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0010/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "linear-algebra" +tags = ["linear-algebra", "linear_map", "msc-15", "train", "lean4"] +msc = "15" +family = "linear_map" +split = "train" +seed = 10 + +[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/linear-algebra/linear-algebra-linear_map-d3-t0010/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0010/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0010/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/linear-algebra/linear-algebra-linear_map-d3-t0010/tests/grade.py b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0010/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0010/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/linear-algebra/linear-algebra-linear_map-d3-t0010/tests/spec.json b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0010/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..a0334d3be5ac8acd6cd3034d6cadde236f753cfd --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0010/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- For idempotent p, the kernel of id - p is the range of p. -/\ntheorem ker_id_sub {V : Type*} [AddCommGroup V] [Module ℚ V] (e : V →ₗ[ℚ] V) (hp : ∀ x, e (e x) = e x) :\n LinearMap.ker (LinearMap.id - e) = LinearMap.range e := by\n sorry\n", + "targets": [ + { + "name": "ker_id_sub", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d3-t0010/tests/test.sh b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0010/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0010/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/linear-algebra/linear-algebra-linear_map-d3-t0034/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0034/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0034/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d3-t0034/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0034/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..e67808a9265b2b018ed80a8cf1fd56a0b5cb2635 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0034/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- For idempotent p, the kernel of id - p is the range of p. -/ +theorem ker_id_sub {V : Type*} [AddCommGroup V] [Module ℝ V] (p : V →ₗ[ℝ] V) (hp : p ∘ₗ p = p) : + LinearMap.ker (LinearMap.id - p) = LinearMap.range p := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d3-t0034/instruction.md b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0034/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9b8c7c7c542b15a374831a8d3b83c1386ac06987 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0034/instruction.md @@ -0,0 +1,14 @@ +# Kernels, ranges and projections + +Prove the following statement. + +Let \(p : V \to V\) be a linear map over \(\mathbb{R}\) with \(p \circ p = p\). Then the kernel of \(\mathrm{id} - p\) equals the range of \(p\). + +## 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/linear-algebra/linear-algebra-linear_map-d3-t0034/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0034/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..eb4f728c9b14efa43fae68fa626fc8bd4e04ba94 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0034/solution/Solution.lean @@ -0,0 +1,13 @@ +import Mathlib + +/-- For idempotent p, the kernel of id - p is the range of p. -/ +theorem ker_id_sub {V : Type*} [AddCommGroup V] [Module ℝ V] (p : V →ₗ[ℝ] V) (hp : p ∘ₗ p = p) : + LinearMap.ker (LinearMap.id - p) = LinearMap.range p := by + have hp' : ∀ x, p (p x) = p x := fun x => LinearMap.congr_fun hp x + ext u + constructor + · intro h + rw [LinearMap.mem_ker, LinearMap.sub_apply, LinearMap.id_apply, sub_eq_zero] at h + exact ⟨u, h.symm⟩ + · rintro ⟨v, rfl⟩ + rw [LinearMap.mem_ker, LinearMap.sub_apply, LinearMap.id_apply, hp', sub_self] diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d3-t0034/solution/solve.sh b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0034/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0034/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d3-t0034/task.toml b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0034/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..dc4ce4b724964d3f8f49dcf60976f9147b36aefb --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0034/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "linear-algebra" +tags = ["linear-algebra", "linear_map", "msc-15", "train", "lean4"] +msc = "15" +family = "linear_map" +split = "train" +seed = 34 + +[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/linear-algebra/linear-algebra-linear_map-d3-t0034/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0034/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0034/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/linear-algebra/linear-algebra-linear_map-d3-t0034/tests/grade.py b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0034/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0034/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/linear-algebra/linear-algebra-linear_map-d3-t0034/tests/spec.json b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0034/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..cd975367113dabc50a626dbde5910371c963db0c --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0034/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- For idempotent p, the kernel of id - p is the range of p. -/\ntheorem ker_id_sub {V : Type*} [AddCommGroup V] [Module ℝ V] (p : V →ₗ[ℝ] V) (hp : p ∘ₗ p = p) :\n LinearMap.ker (LinearMap.id - p) = LinearMap.range p := by\n sorry\n", + "targets": [ + { + "name": "ker_id_sub", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d3-t0034/tests/test.sh b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0034/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0034/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/linear-algebra/linear-algebra-linear_map-d3-t0058/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0058/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0058/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d3-t0058/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0058/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..42b79be2b0a5f8dfbd6ff9c20221aa6cc7f06d59 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0058/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- For idempotent p, the kernel of id - p is the range of p. -/ +theorem ker_id_sub {V : Type*} [AddCommGroup V] [Module ℝ V] (q : V →ₗ[ℝ] V) (hp : q ∘ₗ q = q) : + LinearMap.ker (LinearMap.id - q) = LinearMap.range q := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d3-t0058/instruction.md b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0058/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0e3d7a2652e537dd9a094181d0bedafbb04c16b0 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0058/instruction.md @@ -0,0 +1,14 @@ +# Kernels, ranges and projections + +Prove the following statement. + +Let \(q : V \to V\) be a linear map over \(\mathbb{R}\) with \(q \circ q = q\). Then the kernel of \(\mathrm{id} - q\) equals the range of \(q\). + +## 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/linear-algebra/linear-algebra-linear_map-d3-t0058/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0058/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..23a4e36e9213a9c7c1607fb66a3228502b7bd167 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0058/solution/Solution.lean @@ -0,0 +1,13 @@ +import Mathlib + +/-- For idempotent p, the kernel of id - p is the range of p. -/ +theorem ker_id_sub {V : Type*} [AddCommGroup V] [Module ℝ V] (q : V →ₗ[ℝ] V) (hp : q ∘ₗ q = q) : + LinearMap.ker (LinearMap.id - q) = LinearMap.range q := by + have hp' : ∀ x, q (q x) = q x := fun x => LinearMap.congr_fun hp x + ext u + constructor + · intro h + rw [LinearMap.mem_ker, LinearMap.sub_apply, LinearMap.id_apply, sub_eq_zero] at h + exact ⟨u, h.symm⟩ + · rintro ⟨v, rfl⟩ + rw [LinearMap.mem_ker, LinearMap.sub_apply, LinearMap.id_apply, hp', sub_self] diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d3-t0058/solution/solve.sh b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0058/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0058/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d3-t0058/task.toml b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0058/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7b837424b4e919b2e08a1a79fb742c2e8aaea12e --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0058/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "linear-algebra" +tags = ["linear-algebra", "linear_map", "msc-15", "train", "lean4"] +msc = "15" +family = "linear_map" +split = "train" +seed = 58 + +[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/linear-algebra/linear-algebra-linear_map-d3-t0058/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0058/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0058/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/linear-algebra/linear-algebra-linear_map-d3-t0058/tests/grade.py b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0058/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0058/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/linear-algebra/linear-algebra-linear_map-d3-t0058/tests/spec.json b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0058/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..4455a43a368efec0fb2988c1a397888725bb715e --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0058/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- For idempotent p, the kernel of id - p is the range of p. -/\ntheorem ker_id_sub {V : Type*} [AddCommGroup V] [Module ℝ V] (q : V →ₗ[ℝ] V) (hp : q ∘ₗ q = q) :\n LinearMap.ker (LinearMap.id - q) = LinearMap.range q := by\n sorry\n", + "targets": [ + { + "name": "ker_id_sub", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-linear_map-d3-t0058/tests/test.sh b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0058/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-linear_map-d3-t0058/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/linear-algebra/linear-algebra-matrix_pow-d1-e0015/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-e0015/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-e0015/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d1-e0015/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-e0015/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..8a4a1f5c7ad3bfe05633e2f920aa9936ef847c93 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-e0015/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Powers of a shear matrix. -/ +theorem shear_power (n : ℕ) : + (!![1, 2; 0, 1] : Matrix (Fin 2) (Fin 2) ℤ) ^ n = !![1, (n : ℤ) * 2; 0, 1] := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d1-e0015/instruction.md b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-e0015/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e003b72396a772f3de0ff2f1d72d09a863f49c1b --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-e0015/instruction.md @@ -0,0 +1,14 @@ +# Powers of 2x2 matrices + +Prove the following statement. + +For every natural number \(n\), \[\begin{pmatrix} 1 & 2 \\ 0 & 1 \end{pmatrix}^n = \begin{pmatrix} 1 & 2n \\ 0 & 1 \end{pmatrix}.\] + +## 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/linear-algebra/linear-algebra-matrix_pow-d1-e0015/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-e0015/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..f4525dc04f481e632b06901c3a9517df45437b46 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-e0015/solution/Solution.lean @@ -0,0 +1,13 @@ +import Mathlib + +/-- Powers of a shear matrix. -/ +theorem shear_power (n : ℕ) : + (!![1, 2; 0, 1] : Matrix (Fin 2) (Fin 2) ℤ) ^ n = !![1, (n : ℤ) * 2; 0, 1] := by + induction n with + | zero => + ext i j + fin_cases i <;> fin_cases j <;> simp + | succ j ih => + rw [pow_succ, ih, Matrix.mul_fin_two] + ext i j + fin_cases i <;> fin_cases j <;> simp <;> ring diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d1-e0015/solution/solve.sh b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-e0015/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-e0015/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d1-e0015/task.toml b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-e0015/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..453963f1f2b8e87de81a3cec2483ea2f97b57b33 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-e0015/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "linear-algebra" +tags = ["linear-algebra", "matrix_pow", "msc-15", "eval", "lean4"] +msc = "15" +family = "matrix_pow" +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/linear-algebra/linear-algebra-matrix_pow-d1-e0015/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-e0015/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/linear-algebra/linear-algebra-matrix_pow-d1-e0015/tests/grade.py b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-e0015/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/linear-algebra/linear-algebra-matrix_pow-d1-e0015/tests/spec.json b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-e0015/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..92bb7ba45668076a4c251aa57461f6666243fcc8 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-e0015/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- Powers of a shear matrix. -/\ntheorem shear_power (n : ℕ) :\n (!![1, 2; 0, 1] : Matrix (Fin 2) (Fin 2) ℤ) ^ n = !![1, (n : ℤ) * 2; 0, 1] := by\n sorry\n", + "targets": [ + { + "name": "shear_power", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d1-e0015/tests/test.sh b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-e0015/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/linear-algebra/linear-algebra-matrix_pow-d1-t0039/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0039/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0039/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0039/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0039/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..05dcd622ea63f1fc27ac3287c4c88934a2ab4d4c --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0039/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Powers of a lower shear matrix. -/ +theorem lower_shear_power (n : ℕ) : + (!![1, 0; 3, 1] : Matrix (Fin 2) (Fin 2) ℤ) ^ n = !![1, 0; (n : ℤ) * 3, 1] := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0039/instruction.md b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0039/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..55d6159fa019d1cc1d921ac70d76857927aa6d54 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0039/instruction.md @@ -0,0 +1,14 @@ +# Powers of 2x2 matrices + +Prove the following statement. + +For every natural number \(n\), \[\begin{pmatrix} 1 & 0 \\ 3 & 1 \end{pmatrix}^n = \begin{pmatrix} 1 & 0 \\ 3n & 1 \end{pmatrix}.\] + +## 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/linear-algebra/linear-algebra-matrix_pow-d1-t0039/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0039/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..0bb909b3b9af56edfaf3be0d562e7322a38dea45 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0039/solution/Solution.lean @@ -0,0 +1,13 @@ +import Mathlib + +/-- Powers of a lower shear matrix. -/ +theorem lower_shear_power (n : ℕ) : + (!![1, 0; 3, 1] : Matrix (Fin 2) (Fin 2) ℤ) ^ n = !![1, 0; (n : ℤ) * 3, 1] := by + induction n with + | zero => + ext i j + fin_cases i <;> fin_cases j <;> simp + | succ j ih => + rw [pow_succ, ih, Matrix.mul_fin_two] + ext i j + fin_cases i <;> fin_cases j <;> simp <;> ring diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0039/solution/solve.sh b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0039/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0039/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0039/task.toml b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0039/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a95a35431e851ee499e485509fbc3775b0b10969 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0039/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "linear-algebra" +tags = ["linear-algebra", "matrix_pow", "msc-15", "train", "lean4"] +msc = "15" +family = "matrix_pow" +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/linear-algebra/linear-algebra-matrix_pow-d1-t0039/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0039/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/linear-algebra/linear-algebra-matrix_pow-d1-t0039/tests/grade.py b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0039/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/linear-algebra/linear-algebra-matrix_pow-d1-t0039/tests/spec.json b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0039/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..2e16ae1db5a046767aa1ceb2e9c10bd004fac9ca --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0039/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- Powers of a lower shear matrix. -/\ntheorem lower_shear_power (n : ℕ) :\n (!![1, 0; 3, 1] : Matrix (Fin 2) (Fin 2) ℤ) ^ n = !![1, 0; (n : ℤ) * 3, 1] := by\n sorry\n", + "targets": [ + { + "name": "lower_shear_power", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0039/tests/test.sh b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0039/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/linear-algebra/linear-algebra-matrix_pow-d1-t0063/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0063/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0063/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0063/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0063/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..a3028008eafcb9d5eb280c67f0338eb049c3ba56 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0063/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Powers of a shear matrix. -/ +theorem shear_power (n : ℕ) : + (!![1, 4; 0, 1] : Matrix (Fin 2) (Fin 2) ℤ) ^ n = !![1, (n : ℤ) * 4; 0, 1] := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0063/instruction.md b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0063/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8cd35826f8f0a5f454e16dc3395a54131fec83ab --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0063/instruction.md @@ -0,0 +1,14 @@ +# Powers of 2x2 matrices + +Prove the following statement. + +For every natural number \(n\), \[\begin{pmatrix} 1 & 4 \\ 0 & 1 \end{pmatrix}^n = \begin{pmatrix} 1 & 4n \\ 0 & 1 \end{pmatrix}.\] + +## 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/linear-algebra/linear-algebra-matrix_pow-d1-t0063/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0063/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..5bf30531fed6cc244e0c8fb989d1bab52a17a781 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0063/solution/Solution.lean @@ -0,0 +1,13 @@ +import Mathlib + +/-- Powers of a shear matrix. -/ +theorem shear_power (n : ℕ) : + (!![1, 4; 0, 1] : Matrix (Fin 2) (Fin 2) ℤ) ^ n = !![1, (n : ℤ) * 4; 0, 1] := by + induction n with + | zero => + ext i j + fin_cases i <;> fin_cases j <;> simp + | succ j ih => + rw [pow_succ, ih, Matrix.mul_fin_two] + ext i j + fin_cases i <;> fin_cases j <;> simp <;> ring diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0063/solution/solve.sh b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0063/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0063/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0063/task.toml b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0063/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..18fcbac20e1d6fe65a7e9c04628f638e16aa452e --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0063/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "linear-algebra" +tags = ["linear-algebra", "matrix_pow", "msc-15", "train", "lean4"] +msc = "15" +family = "matrix_pow" +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/linear-algebra/linear-algebra-matrix_pow-d1-t0063/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0063/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/linear-algebra/linear-algebra-matrix_pow-d1-t0063/tests/grade.py b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0063/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/linear-algebra/linear-algebra-matrix_pow-d1-t0063/tests/spec.json b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0063/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..7a69687a73305d72e4d98d9f1f675caff8bcc0a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0063/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- Powers of a shear matrix. -/\ntheorem shear_power (n : ℕ) :\n (!![1, 4; 0, 1] : Matrix (Fin 2) (Fin 2) ℤ) ^ n = !![1, (n : ℤ) * 4; 0, 1] := by\n sorry\n", + "targets": [ + { + "name": "shear_power", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0063/tests/test.sh b/tasks/linear-algebra/linear-algebra-matrix_pow-d1-t0063/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/linear-algebra/linear-algebra-matrix_pow-d2-t0007/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0007/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0007/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0007/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0007/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..1f67535e6ca21599b586185406a7a4e736858041 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0007/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Powers of a 2x2 Jordan block. -/ +theorem jordan_power (n : ℕ) : + (!![6, 1; 0, 6] : Matrix (Fin 2) (Fin 2) ℤ) ^ (n + 1) = !![6 ^ (n + 1), ((n : ℤ) + 1) * 6 ^ n; 0, 6 ^ (n + 1)] := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0007/instruction.md b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0007/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a52d7bcb3c7591e2faaa6a3dd773457b9c6de5dc --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0007/instruction.md @@ -0,0 +1,14 @@ +# Powers of 2x2 matrices + +Prove the following statement. + +For every natural number \(n\), \[\begin{pmatrix} 6 & 1 \\ 0 & 6 \end{pmatrix}^{n+1} = \begin{pmatrix} (6)^{n+1} & (n+1)(6)^n \\ 0 & (6)^{n+1} \end{pmatrix}.\] + +## 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/linear-algebra/linear-algebra-matrix_pow-d2-t0007/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0007/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..cb465a83ee860d8d86a3cd29ba71b951475722ba --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0007/solution/Solution.lean @@ -0,0 +1,13 @@ +import Mathlib + +/-- Powers of a 2x2 Jordan block. -/ +theorem jordan_power (n : ℕ) : + (!![6, 1; 0, 6] : Matrix (Fin 2) (Fin 2) ℤ) ^ (n + 1) = !![6 ^ (n + 1), ((n : ℤ) + 1) * 6 ^ n; 0, 6 ^ (n + 1)] := by + induction n with + | zero => + ext i j + fin_cases i <;> fin_cases j <;> simp + | succ j ih => + rw [pow_succ, ih, Matrix.mul_fin_two] + ext i j + fin_cases i <;> fin_cases j <;> simp [pow_succ] <;> ring diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0007/solution/solve.sh b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0007/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0007/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0007/task.toml b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0007/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7645ef7927986df2eb0e53cf5c7ce082efac0b7f --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0007/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "linear-algebra" +tags = ["linear-algebra", "matrix_pow", "msc-15", "train", "lean4"] +msc = "15" +family = "matrix_pow" +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/linear-algebra/linear-algebra-matrix_pow-d2-t0007/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0007/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/linear-algebra/linear-algebra-matrix_pow-d2-t0007/tests/grade.py b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0007/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/linear-algebra/linear-algebra-matrix_pow-d2-t0007/tests/spec.json b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0007/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..213ccf19f276352ae4fa1c50ba1035d93ca0f8f8 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0007/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- Powers of a 2x2 Jordan block. -/\ntheorem jordan_power (n : ℕ) :\n (!![6, 1; 0, 6] : Matrix (Fin 2) (Fin 2) ℤ) ^ (n + 1) = !![6 ^ (n + 1), ((n : ℤ) + 1) * 6 ^ n; 0, 6 ^ (n + 1)] := by\n sorry\n", + "targets": [ + { + "name": "jordan_power", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0007/tests/test.sh b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0007/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/linear-algebra/linear-algebra-matrix_pow-d2-t0031/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0031/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0031/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0031/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0031/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..085183c36c35594700747d44b9c9fb36adff6d70 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0031/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Powers of a diagonal matrix. -/ +theorem diagonal_power (n : ℕ) : + (!![4, 0; 0, 7] : Matrix (Fin 2) (Fin 2) ℤ) ^ n = !![4 ^ n, 0; 0, 7 ^ n] := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0031/instruction.md b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0031/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..aeef51fdac009ce6e9146406a13d0a63b3a24240 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0031/instruction.md @@ -0,0 +1,14 @@ +# Powers of 2x2 matrices + +Prove the following statement. + +For every natural number \(n\), \[\begin{pmatrix} 4 & 0 \\ 0 & 7 \end{pmatrix}^n = \begin{pmatrix} (4)^n & 0 \\ 0 & (7)^n \end{pmatrix}.\] + +## 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/linear-algebra/linear-algebra-matrix_pow-d2-t0031/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0031/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..b38515f3e9b335331974749a09d9fa29457823a5 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0031/solution/Solution.lean @@ -0,0 +1,13 @@ +import Mathlib + +/-- Powers of a diagonal matrix. -/ +theorem diagonal_power (n : ℕ) : + (!![4, 0; 0, 7] : Matrix (Fin 2) (Fin 2) ℤ) ^ n = !![4 ^ n, 0; 0, 7 ^ n] := by + induction n with + | zero => + ext i j + fin_cases i <;> fin_cases j <;> simp + | succ j ih => + rw [pow_succ, ih, Matrix.mul_fin_two] + ext i j + fin_cases i <;> fin_cases j <;> simp <;> ring diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0031/solution/solve.sh b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0031/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0031/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0031/task.toml b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0031/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..86f2ba6423a300fe86426f97266348a279f872b8 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0031/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "linear-algebra" +tags = ["linear-algebra", "matrix_pow", "msc-15", "train", "lean4"] +msc = "15" +family = "matrix_pow" +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/linear-algebra/linear-algebra-matrix_pow-d2-t0031/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0031/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/linear-algebra/linear-algebra-matrix_pow-d2-t0031/tests/grade.py b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0031/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/linear-algebra/linear-algebra-matrix_pow-d2-t0031/tests/spec.json b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0031/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..90e7d03be94359de4aa347b220b3069b9a6e7368 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0031/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- Powers of a diagonal matrix. -/\ntheorem diagonal_power (n : ℕ) :\n (!![4, 0; 0, 7] : Matrix (Fin 2) (Fin 2) ℤ) ^ n = !![4 ^ n, 0; 0, 7 ^ n] := by\n sorry\n", + "targets": [ + { + "name": "diagonal_power", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0031/tests/test.sh b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0031/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/linear-algebra/linear-algebra-matrix_pow-d2-t0055/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0055/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0055/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0055/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0055/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..8c2c94b2f3d193c387de26ef0299fd990181813b --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0055/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Powers of a 2x2 Jordan block. -/ +theorem jordan_power (n : ℕ) : + (!![4, 1; 0, 4] : Matrix (Fin 2) (Fin 2) ℤ) ^ (n + 1) = !![4 ^ (n + 1), ((n : ℤ) + 1) * 4 ^ n; 0, 4 ^ (n + 1)] := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0055/instruction.md b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0055/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6cd964d8859ae53f6ae8a09113a5a8e7f9b8ba02 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0055/instruction.md @@ -0,0 +1,14 @@ +# Powers of 2x2 matrices + +Prove the following statement. + +For every natural number \(n\), \[\begin{pmatrix} 4 & 1 \\ 0 & 4 \end{pmatrix}^{n+1} = \begin{pmatrix} (4)^{n+1} & (n+1)(4)^n \\ 0 & (4)^{n+1} \end{pmatrix}.\] + +## 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/linear-algebra/linear-algebra-matrix_pow-d2-t0055/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0055/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..74bc3192be934745892a638900f395847edcaac3 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0055/solution/Solution.lean @@ -0,0 +1,13 @@ +import Mathlib + +/-- Powers of a 2x2 Jordan block. -/ +theorem jordan_power (n : ℕ) : + (!![4, 1; 0, 4] : Matrix (Fin 2) (Fin 2) ℤ) ^ (n + 1) = !![4 ^ (n + 1), ((n : ℤ) + 1) * 4 ^ n; 0, 4 ^ (n + 1)] := by + induction n with + | zero => + ext i j + fin_cases i <;> fin_cases j <;> simp + | succ j ih => + rw [pow_succ, ih, Matrix.mul_fin_two] + ext i j + fin_cases i <;> fin_cases j <;> simp [pow_succ] <;> ring diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0055/solution/solve.sh b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0055/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0055/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0055/task.toml b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0055/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6ccc5f7387e45c0cc8d4f5e0684d69ee50dc619b --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0055/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "linear-algebra" +tags = ["linear-algebra", "matrix_pow", "msc-15", "train", "lean4"] +msc = "15" +family = "matrix_pow" +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/linear-algebra/linear-algebra-matrix_pow-d2-t0055/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0055/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/linear-algebra/linear-algebra-matrix_pow-d2-t0055/tests/grade.py b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0055/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/linear-algebra/linear-algebra-matrix_pow-d2-t0055/tests/spec.json b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0055/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..ed5ad73467d5701383bba022c07c3f32db4f511b --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0055/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- Powers of a 2x2 Jordan block. -/\ntheorem jordan_power (n : ℕ) :\n (!![4, 1; 0, 4] : Matrix (Fin 2) (Fin 2) ℤ) ^ (n + 1) = !![4 ^ (n + 1), ((n : ℤ) + 1) * 4 ^ n; 0, 4 ^ (n + 1)] := by\n sorry\n", + "targets": [ + { + "name": "jordan_power", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0055/tests/test.sh b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0055/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/linear-algebra/linear-algebra-matrix_pow-d2-t0079/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0079/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0079/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0079/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0079/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..8c2c94b2f3d193c387de26ef0299fd990181813b --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0079/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Powers of a 2x2 Jordan block. -/ +theorem jordan_power (n : ℕ) : + (!![4, 1; 0, 4] : Matrix (Fin 2) (Fin 2) ℤ) ^ (n + 1) = !![4 ^ (n + 1), ((n : ℤ) + 1) * 4 ^ n; 0, 4 ^ (n + 1)] := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0079/instruction.md b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0079/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6cd964d8859ae53f6ae8a09113a5a8e7f9b8ba02 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0079/instruction.md @@ -0,0 +1,14 @@ +# Powers of 2x2 matrices + +Prove the following statement. + +For every natural number \(n\), \[\begin{pmatrix} 4 & 1 \\ 0 & 4 \end{pmatrix}^{n+1} = \begin{pmatrix} (4)^{n+1} & (n+1)(4)^n \\ 0 & (4)^{n+1} \end{pmatrix}.\] + +## 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/linear-algebra/linear-algebra-matrix_pow-d2-t0079/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0079/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..74bc3192be934745892a638900f395847edcaac3 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0079/solution/Solution.lean @@ -0,0 +1,13 @@ +import Mathlib + +/-- Powers of a 2x2 Jordan block. -/ +theorem jordan_power (n : ℕ) : + (!![4, 1; 0, 4] : Matrix (Fin 2) (Fin 2) ℤ) ^ (n + 1) = !![4 ^ (n + 1), ((n : ℤ) + 1) * 4 ^ n; 0, 4 ^ (n + 1)] := by + induction n with + | zero => + ext i j + fin_cases i <;> fin_cases j <;> simp + | succ j ih => + rw [pow_succ, ih, Matrix.mul_fin_two] + ext i j + fin_cases i <;> fin_cases j <;> simp [pow_succ] <;> ring diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0079/solution/solve.sh b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0079/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0079/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0079/task.toml b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0079/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..183795941103e3cc80f724d3241fbf89dcc0c5c0 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0079/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "linear-algebra" +tags = ["linear-algebra", "matrix_pow", "msc-15", "train", "lean4"] +msc = "15" +family = "matrix_pow" +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/linear-algebra/linear-algebra-matrix_pow-d2-t0079/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0079/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/linear-algebra/linear-algebra-matrix_pow-d2-t0079/tests/grade.py b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0079/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/linear-algebra/linear-algebra-matrix_pow-d2-t0079/tests/spec.json b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0079/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..ed5ad73467d5701383bba022c07c3f32db4f511b --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0079/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- Powers of a 2x2 Jordan block. -/\ntheorem jordan_power (n : ℕ) :\n (!![4, 1; 0, 4] : Matrix (Fin 2) (Fin 2) ℤ) ^ (n + 1) = !![4 ^ (n + 1), ((n : ℤ) + 1) * 4 ^ n; 0, 4 ^ (n + 1)] := by\n sorry\n", + "targets": [ + { + "name": "jordan_power", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0079/tests/test.sh b/tasks/linear-algebra/linear-algebra-matrix_pow-d2-t0079/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/linear-algebra/linear-algebra-matrix_pow-d3-e0023/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-e0023/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-e0023/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d3-e0023/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-e0023/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..9da715d7114017ee25fc5dae0dcb2fb220cbec1d --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-e0023/environment/workdir/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- Powers of a shear matrix. -/ +theorem shear_power (k : ℤ) (n : ℕ) : + (!![1, k; 0, 1] : Matrix (Fin 2) (Fin 2) ℤ) ^ n = !![1, (n : ℤ) * k; 0, 1] := by + sorry + +/-- A product of powers of two shears. -/ +theorem shear_product (n m : ℕ) : + (!![1, 5; 0, 1] : Matrix (Fin 2) (Fin 2) ℤ) ^ n * (!![1, 1; 0, 1] : Matrix (Fin 2) (Fin 2) ℤ) ^ m = !![1, (n : ℤ) * 5 + (m : ℤ) * 1; 0, 1] := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d3-e0023/instruction.md b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-e0023/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b299bf36412a13d8687750c87c074c10efef4ed2 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-e0023/instruction.md @@ -0,0 +1,14 @@ +# Powers of 2x2 matrices + +Prove the following statement. + +For every integer \(k\) and natural number \(n\), \[\begin{pmatrix} 1 & k \\ 0 & 1 \end{pmatrix}^n = \begin{pmatrix} 1 & nk \\ 0 & 1 \end{pmatrix}.\] Deduce that for all natural numbers \(n, m\), \[\begin{pmatrix} 1 & 5 \\ 0 & 1 \end{pmatrix}^n \begin{pmatrix} 1 & 1 \\ 0 & 1 \end{pmatrix}^m = \begin{pmatrix} 1 & 5n + 1m \\ 0 & 1 \end{pmatrix}.\] + +## 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/linear-algebra/linear-algebra-matrix_pow-d3-e0023/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-e0023/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..9d4c093e7d950bb70134d05f8c95524019ea1e18 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-e0023/solution/Solution.lean @@ -0,0 +1,20 @@ +import Mathlib + +/-- Powers of a shear matrix. -/ +theorem shear_power (k : ℤ) (n : ℕ) : + (!![1, k; 0, 1] : Matrix (Fin 2) (Fin 2) ℤ) ^ n = !![1, (n : ℤ) * k; 0, 1] := by + induction n with + | zero => + ext i j + fin_cases i <;> fin_cases j <;> simp + | succ j ih => + rw [pow_succ, ih, Matrix.mul_fin_two] + ext i j + fin_cases i <;> fin_cases j <;> simp <;> ring + +/-- A product of powers of two shears. -/ +theorem shear_product (n m : ℕ) : + (!![1, 5; 0, 1] : Matrix (Fin 2) (Fin 2) ℤ) ^ n * (!![1, 1; 0, 1] : Matrix (Fin 2) (Fin 2) ℤ) ^ m = !![1, (n : ℤ) * 5 + (m : ℤ) * 1; 0, 1] := by + rw [shear_power, shear_power, Matrix.mul_fin_two] + ext i j + fin_cases i <;> fin_cases j <;> simp <;> ring diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d3-e0023/solution/solve.sh b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-e0023/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-e0023/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d3-e0023/task.toml b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-e0023/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..720353390502d4d49e82b8a102df92440662ef0a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-e0023/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "linear-algebra" +tags = ["linear-algebra", "matrix_pow", "msc-15", "eval", "lean4"] +msc = "15" +family = "matrix_pow" +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/linear-algebra/linear-algebra-matrix_pow-d3-e0023/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-e0023/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/linear-algebra/linear-algebra-matrix_pow-d3-e0023/tests/grade.py b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-e0023/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/linear-algebra/linear-algebra-matrix_pow-d3-e0023/tests/spec.json b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-e0023/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..25df2738e2117cd960bd5091ccc42cea0a1a2c22 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-e0023/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\n/-- Powers of a shear matrix. -/\ntheorem shear_power (k : ℤ) (n : ℕ) :\n (!![1, k; 0, 1] : Matrix (Fin 2) (Fin 2) ℤ) ^ n = !![1, (n : ℤ) * k; 0, 1] := by\n sorry\n\n/-- A product of powers of two shears. -/\ntheorem shear_product (n m : ℕ) :\n (!![1, 5; 0, 1] : Matrix (Fin 2) (Fin 2) ℤ) ^ n * (!![1, 1; 0, 1] : Matrix (Fin 2) (Fin 2) ℤ) ^ m = !![1, (n : ℤ) * 5 + (m : ℤ) * 1; 0, 1] := by\n sorry\n", + "targets": [ + { + "name": "shear_power", + "weight": 0.4 + }, + { + "name": "shear_product", + "weight": 0.6 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d3-e0023/tests/test.sh b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-e0023/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/linear-algebra/linear-algebra-matrix_pow-d3-t0023/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0023/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0023/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0023/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0023/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..7e68e50bc82f8be3907d4b7952036a6888994a10 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0023/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Powers of an affine map matrix, with a geometric sum. -/ +theorem affine_power (n : ℕ) : + (!![(-3 : ℤ), (-1 : ℤ); 0, 1] : Matrix (Fin 2) (Fin 2) ℤ) ^ n = !![(-3 : ℤ) ^ n, (-1 : ℤ) * ∑ i ∈ Finset.range n, (-3 : ℤ) ^ i; 0, 1] := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0023/instruction.md b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0023/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..424152ad870fa28ca6791b6d3f2573b258102d69 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0023/instruction.md @@ -0,0 +1,14 @@ +# Powers of 2x2 matrices + +Prove the following statement. + +For every natural number \(n\), \[\begin{pmatrix} -3 & -1 \\ 0 & 1 \end{pmatrix}^n = \begin{pmatrix} (-3)^n & -1 \sum_{i=0}^{n-1} (-3)^i \\ 0 & 1 \end{pmatrix}.\] 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/linear-algebra/linear-algebra-matrix_pow-d3-t0023/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0023/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..f1c58241fe9396677adb3f7fa5312949bb2b6272 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0023/solution/Solution.lean @@ -0,0 +1,13 @@ +import Mathlib + +/-- Powers of an affine map matrix, with a geometric sum. -/ +theorem affine_power (n : ℕ) : + (!![(-3 : ℤ), (-1 : ℤ); 0, 1] : Matrix (Fin 2) (Fin 2) ℤ) ^ n = !![(-3 : ℤ) ^ n, (-1 : ℤ) * ∑ i ∈ Finset.range n, (-3 : ℤ) ^ i; 0, 1] := by + induction n with + | zero => + ext i j + fin_cases i <;> fin_cases j <;> simp + | succ j ih => + rw [pow_succ, ih, Matrix.mul_fin_two] + ext i j + fin_cases i <;> fin_cases j <;> simp [Finset.sum_range_succ, pow_succ] <;> ring diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0023/solution/solve.sh b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0023/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0023/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0023/task.toml b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0023/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..69592c6c22eab5dfddc750228404a81dda1d1db3 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0023/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "linear-algebra" +tags = ["linear-algebra", "matrix_pow", "msc-15", "train", "lean4"] +msc = "15" +family = "matrix_pow" +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/linear-algebra/linear-algebra-matrix_pow-d3-t0023/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0023/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/linear-algebra/linear-algebra-matrix_pow-d3-t0023/tests/grade.py b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0023/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/linear-algebra/linear-algebra-matrix_pow-d3-t0023/tests/spec.json b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0023/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..30f27d889a883042317e3d779df81212f8a01afe --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0023/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- Powers of an affine map matrix, with a geometric sum. -/\ntheorem affine_power (n : ℕ) :\n (!![(-3 : ℤ), (-1 : ℤ); 0, 1] : Matrix (Fin 2) (Fin 2) ℤ) ^ n = !![(-3 : ℤ) ^ n, (-1 : ℤ) * ∑ i ∈ Finset.range n, (-3 : ℤ) ^ i; 0, 1] := by\n sorry\n", + "targets": [ + { + "name": "affine_power", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0023/tests/test.sh b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0023/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/linear-algebra/linear-algebra-matrix_pow-d3-t0083/environment/Dockerfile b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0083/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0083/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0083/environment/workdir/Solution.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0083/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..e96f6ea5acfbc0758349d2d67d06f01921030079 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0083/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- Powers of an affine map matrix, with a geometric sum. -/ +theorem affine_power (n : ℕ) : + (!![2, 4; 0, 1] : Matrix (Fin 2) (Fin 2) ℤ) ^ n = !![2 ^ n, 4 * ∑ i ∈ Finset.range n, 2 ^ i; 0, 1] := by + sorry diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0083/instruction.md b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0083/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c83304c82ef50573c4044015568c74e2c0a029dc --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0083/instruction.md @@ -0,0 +1,14 @@ +# Powers of 2x2 matrices + +Prove the following statement. + +For every natural number \(n\), \[\begin{pmatrix} 2 & 4 \\ 0 & 1 \end{pmatrix}^n = \begin{pmatrix} (2)^n & 4 \sum_{i=0}^{n-1} (2)^i \\ 0 & 1 \end{pmatrix}.\] 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/linear-algebra/linear-algebra-matrix_pow-d3-t0083/solution/Solution.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0083/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..719a00ac950c90c2fbf823cb6e6ca961ad9fd37b --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0083/solution/Solution.lean @@ -0,0 +1,13 @@ +import Mathlib + +/-- Powers of an affine map matrix, with a geometric sum. -/ +theorem affine_power (n : ℕ) : + (!![2, 4; 0, 1] : Matrix (Fin 2) (Fin 2) ℤ) ^ n = !![2 ^ n, 4 * ∑ i ∈ Finset.range n, 2 ^ i; 0, 1] := by + induction n with + | zero => + ext i j + fin_cases i <;> fin_cases j <;> simp + | succ j ih => + rw [pow_succ, ih, Matrix.mul_fin_two] + ext i j + fin_cases i <;> fin_cases j <;> simp [Finset.sum_range_succ, pow_succ] <;> ring diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0083/solution/solve.sh b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0083/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0083/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0083/task.toml b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0083/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..463fb01b626de8116c9d816442e7cce5bf70221b --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0083/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "linear-algebra" +tags = ["linear-algebra", "matrix_pow", "msc-15", "train", "lean4"] +msc = "15" +family = "matrix_pow" +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/linear-algebra/linear-algebra-matrix_pow-d3-t0083/tests/Verify.lean b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0083/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/linear-algebra/linear-algebra-matrix_pow-d3-t0083/tests/grade.py b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0083/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/linear-algebra/linear-algebra-matrix_pow-d3-t0083/tests/spec.json b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0083/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..498b0e620c98774f2b4d07f19a9db2d30484d4c9 --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0083/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- Powers of an affine map matrix, with a geometric sum. -/\ntheorem affine_power (n : ℕ) :\n (!![2, 4; 0, 1] : Matrix (Fin 2) (Fin 2) ℤ) ^ n = !![2 ^ n, 4 * ∑ i ∈ Finset.range n, 2 ^ i; 0, 1] := by\n sorry\n", + "targets": [ + { + "name": "affine_power", + "weight": 1.0 + } + ] +} diff --git a/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0083/tests/test.sh b/tasks/linear-algebra/linear-algebra-matrix_pow-d3-t0083/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/linear-algebra/linear-algebra-matrix_pow-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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0000/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0000/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0000/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0000/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0000/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..00595b469fe7fdde7f94077cb3b056ce57170882 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0000/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The polynomial is congruent to the stated residue. -/ +theorem congr_poly (x : ℤ) (h : x ≡ 5 [ZMOD 6]) : + 6 * x ^ 2 + 3 * x + 5 ≡ 2 [ZMOD 6] := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0000/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0000/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7c8ea92ff80517b0c60ead364e40592af0d7678a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0000/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Let \(x\) be an integer with \(x \equiv 5 \pmod{6}\). Prove that \(6x^2 + 3x + 5 \equiv 2 \pmod{6}\). + +## 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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0000/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0000/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..d70e63ca0e272fd1c28632e995d7bc3e44715fff --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0000/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The polynomial is congruent to the stated residue. -/ +theorem congr_poly (x : ℤ) (h : x ≡ 5 [ZMOD 6]) : + 6 * x ^ 2 + 3 * x + 5 ≡ 2 [ZMOD 6] := by + have h1 := (((h.pow 2).mul_left 6).add ((h).mul_left 3)).add_right 5 + refine h1.trans ?_ + norm_num [Int.ModEq] diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0000/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0000/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0000/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0000/task.toml b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0000/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d078d92078fc4dfba0fed7ac6cfece199fc64e66 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0000/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "congruence_chain", "msc-11", "eval", "lean4"] +msc = "11" +family = "congruence_chain" +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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0000/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0000/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0000/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0000/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0000/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0000/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..d7b08a2096fc8ff4335f50508a7cddaff64e4694 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0000/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The polynomial is congruent to the stated residue. -/\ntheorem congr_poly (x : ℤ) (h : x ≡ 5 [ZMOD 6]) :\n 6 * x ^ 2 + 3 * x + 5 ≡ 2 [ZMOD 6] := by\n sorry\n", + "targets": [ + { + "name": "congr_poly", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0000/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0000/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0012/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0012/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0012/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0012/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0012/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..32e94dd5d5debe4ecaaab352cd852b5c93d73636 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0012/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The polynomial is congruent to the stated residue. -/ +theorem congr_poly (x : ℤ) (h : x ≡ 1 [ZMOD 7]) : + 6 * x ^ 2 + 7 * x + 4 ≡ 3 [ZMOD 7] := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0012/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0012/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1829cbc6819dd1b02c142985f9381e1f88005837 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0012/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Let \(x\) be an integer with \(x \equiv 1 \pmod{7}\). Prove that \(6x^2 + 7x + 4 \equiv 3 \pmod{7}\). + +## 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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0012/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0012/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..b36b364473ba900a28d2ecaf245ac6a52aba3006 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0012/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The polynomial is congruent to the stated residue. -/ +theorem congr_poly (x : ℤ) (h : x ≡ 1 [ZMOD 7]) : + 6 * x ^ 2 + 7 * x + 4 ≡ 3 [ZMOD 7] := by + have h1 := (((h.pow 2).mul_left 6).add ((h).mul_left 7)).add_right 4 + refine h1.trans ?_ + norm_num [Int.ModEq] diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0012/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0012/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0012/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0012/task.toml b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0012/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d175e761675b93b09d2d6adbfdd10b162f2ec855 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0012/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "congruence_chain", "msc-11", "eval", "lean4"] +msc = "11" +family = "congruence_chain" +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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0012/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0012/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0012/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0012/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0012/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0012/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..19566cdd618ec424b1276586cb21c3df026c8ee0 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0012/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The polynomial is congruent to the stated residue. -/\ntheorem congr_poly (x : ℤ) (h : x ≡ 1 [ZMOD 7]) :\n 6 * x ^ 2 + 7 * x + 4 ≡ 3 [ZMOD 7] := by\n sorry\n", + "targets": [ + { + "name": "congr_poly", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0012/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-e0012/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0000/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0000/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0000/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0000/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0000/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..57090256b1d417f8f09053036491973befae3cb1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0000/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The polynomial is congruent to the stated residue. -/ +theorem congr_poly (x : ℤ) (h : x ≡ 0 [ZMOD 8]) : + x ^ 2 + 5 * x + 1 ≡ 1 [ZMOD 8] := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0000/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0000/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..db5f0f9835df025bc95c84091b8b837b853b3c44 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0000/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Let \(x\) be an integer with \(x \equiv 0 \pmod{8}\). Prove that \(x^2 + 5x + 1 \equiv 1 \pmod{8}\). + +## 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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0000/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0000/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..b7552314be57963a24238aaf46f9a424d030113e --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0000/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The polynomial is congruent to the stated residue. -/ +theorem congr_poly (x : ℤ) (h : x ≡ 0 [ZMOD 8]) : + x ^ 2 + 5 * x + 1 ≡ 1 [ZMOD 8] := by + have h1 := ((h.pow 2).add ((h).mul_left 5)).add_right 1 + refine h1.trans ?_ + norm_num [Int.ModEq] diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0000/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0000/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0000/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0000/task.toml b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0000/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e8fd9b07ab57827c57f92536431cfd8ac61a2b17 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0000/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "congruence_chain", "msc-11", "train", "lean4"] +msc = "11" +family = "congruence_chain" +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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0000/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0000/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0000/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0000/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0000/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0000/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..16b5798f519cad0906af51acd42d80d9f7987c89 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0000/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The polynomial is congruent to the stated residue. -/\ntheorem congr_poly (x : ℤ) (h : x ≡ 0 [ZMOD 8]) :\n x ^ 2 + 5 * x + 1 ≡ 1 [ZMOD 8] := by\n sorry\n", + "targets": [ + { + "name": "congr_poly", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0000/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0000/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0012/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0012/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0012/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0012/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0012/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..ef3111da86ba3477273d17870745df9e15643faa --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0012/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The polynomial is congruent to the stated residue. -/ +theorem congr_poly (x : ℤ) (h : x ≡ 0 [ZMOD 10]) : + 5 * x ^ 2 + x + 6 ≡ 6 [ZMOD 10] := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0012/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0012/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..675c9528de9ca396ae1915ba371cfa87ed7cd86d --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0012/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Let \(x\) be an integer with \(x \equiv 0 \pmod{10}\). Prove that \(5x^2 + x + 6 \equiv 6 \pmod{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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0012/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0012/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..b2a49c5234ecf885f6d75b5407dddd5a5a1454d7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0012/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The polynomial is congruent to the stated residue. -/ +theorem congr_poly (x : ℤ) (h : x ≡ 0 [ZMOD 10]) : + 5 * x ^ 2 + x + 6 ≡ 6 [ZMOD 10] := by + have h1 := (((h.pow 2).mul_left 5).add (h)).add_right 6 + refine h1.trans ?_ + norm_num [Int.ModEq] diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0012/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0012/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0012/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0012/task.toml b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0012/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cc815409619edbaa04dcc8db352ff6616cb27a29 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0012/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "congruence_chain", "msc-11", "train", "lean4"] +msc = "11" +family = "congruence_chain" +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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0012/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0012/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0012/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0012/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0012/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0012/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..8cde0ffa861ccd5448cadc88b195422c2fd92927 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0012/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The polynomial is congruent to the stated residue. -/\ntheorem congr_poly (x : ℤ) (h : x ≡ 0 [ZMOD 10]) :\n 5 * x ^ 2 + x + 6 ≡ 6 [ZMOD 10] := by\n sorry\n", + "targets": [ + { + "name": "congr_poly", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0012/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0012/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0024/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0024/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0024/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0024/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0024/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..6e44a0778365da00385d2bb4220c6acd428ba659 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0024/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The polynomial is congruent to the stated residue. -/ +theorem congr_poly (x : ℤ) (h : x ≡ 2 [ZMOD 6]) : + x ^ 2 + 4 * x + 2 ≡ 2 [ZMOD 6] := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0024/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0024/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7a05c754c90a49b151aad3cfc9413b9d28bb11d7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0024/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Let \(x\) be an integer with \(x \equiv 2 \pmod{6}\). Prove that \(x^2 + 4x + 2 \equiv 2 \pmod{6}\). + +## 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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0024/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0024/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..9b97dd536eceb0c6851e84f26d54eb1f8bbc75d8 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0024/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The polynomial is congruent to the stated residue. -/ +theorem congr_poly (x : ℤ) (h : x ≡ 2 [ZMOD 6]) : + x ^ 2 + 4 * x + 2 ≡ 2 [ZMOD 6] := by + have h1 := ((h.pow 2).add ((h).mul_left 4)).add_right 2 + refine h1.trans ?_ + norm_num [Int.ModEq] diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0024/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0024/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0024/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0024/task.toml b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0024/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f2caf732339505765acc18d4a99257571c75ca68 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0024/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "congruence_chain", "msc-11", "train", "lean4"] +msc = "11" +family = "congruence_chain" +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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0024/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0024/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0024/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0024/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0024/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0024/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..7b93b2e6d9fcdc6da453b18f3c939e0b1d165132 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0024/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The polynomial is congruent to the stated residue. -/\ntheorem congr_poly (x : ℤ) (h : x ≡ 2 [ZMOD 6]) :\n x ^ 2 + 4 * x + 2 ≡ 2 [ZMOD 6] := by\n sorry\n", + "targets": [ + { + "name": "congr_poly", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0024/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0024/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0036/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0036/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0036/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0036/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0036/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..eaa139416025cf396d6837419386cfa9cc7e5b4a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0036/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The polynomial is congruent to the stated residue. -/ +theorem congr_poly (x : ℤ) (h : x ≡ 3 [ZMOD 5]) : + x ^ 2 + 2 * x + 5 ≡ 0 [ZMOD 5] := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0036/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0036/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..af82b0e25e1d9cef3036563c67adc08ad5b9eae7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0036/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Let \(x\) be an integer with \(x \equiv 3 \pmod{5}\). Prove that \(x^2 + 2x + 5 \equiv 0 \pmod{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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0036/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0036/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..d8d02d5248c123508ac08d7f41af800f52a67d69 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0036/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The polynomial is congruent to the stated residue. -/ +theorem congr_poly (x : ℤ) (h : x ≡ 3 [ZMOD 5]) : + x ^ 2 + 2 * x + 5 ≡ 0 [ZMOD 5] := by + have h1 := ((h.pow 2).add ((h).mul_left 2)).add_right 5 + refine h1.trans ?_ + norm_num [Int.ModEq] diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0036/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0036/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0036/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0036/task.toml b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0036/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d570d66e2c88ba1fb194a908bdc64e0988e92e17 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0036/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "congruence_chain", "msc-11", "train", "lean4"] +msc = "11" +family = "congruence_chain" +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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0036/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0036/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0036/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0036/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0036/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0036/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..a4351881dd35ae61cdc794ed8d59578f036a36d7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0036/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The polynomial is congruent to the stated residue. -/\ntheorem congr_poly (x : ℤ) (h : x ≡ 3 [ZMOD 5]) :\n x ^ 2 + 2 * x + 5 ≡ 0 [ZMOD 5] := by\n sorry\n", + "targets": [ + { + "name": "congr_poly", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0036/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0036/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0048/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0048/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0048/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0048/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0048/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..98ebc122dd4b6d8120a0e9217e7725faff508844 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0048/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The polynomial is congruent to the stated residue. -/ +theorem congr_poly (x : ℤ) (h : x ≡ 4 [ZMOD 12]) : + 5 * x ^ 2 + 3 * x + 3 ≡ 11 [ZMOD 12] := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0048/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0048/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..691f84bacde74e34be470c058d92be92eedffe58 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0048/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Let \(x\) be an integer with \(x \equiv 4 \pmod{12}\). Prove that \(5x^2 + 3x + 3 \equiv 11 \pmod{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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0048/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0048/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..d2aea4d11853ae6e09e2c7eafd26edacc6389f8e --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0048/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The polynomial is congruent to the stated residue. -/ +theorem congr_poly (x : ℤ) (h : x ≡ 4 [ZMOD 12]) : + 5 * x ^ 2 + 3 * x + 3 ≡ 11 [ZMOD 12] := by + have h1 := (((h.pow 2).mul_left 5).add ((h).mul_left 3)).add_right 3 + refine h1.trans ?_ + norm_num [Int.ModEq] diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0048/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0048/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0048/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0048/task.toml b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0048/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e189d53421b4fc5f85e83957e12a22cc7c3cc03b --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0048/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "congruence_chain", "msc-11", "train", "lean4"] +msc = "11" +family = "congruence_chain" +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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0048/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0048/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0048/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0048/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0048/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0048/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..2347093a7ec20b87d04c253051a46fd13b498c0d --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0048/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The polynomial is congruent to the stated residue. -/\ntheorem congr_poly (x : ℤ) (h : x ≡ 4 [ZMOD 12]) :\n 5 * x ^ 2 + 3 * x + 3 ≡ 11 [ZMOD 12] := by\n sorry\n", + "targets": [ + { + "name": "congr_poly", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0048/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d1-t0048/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0040/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0040/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0040/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0040/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0040/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..a06a504e930647e9ee3a83dbe3538df83d1a6163 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0040/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The expression is congruent to the stated residue. -/ +theorem congr_poly2 (x y : ℤ) (hx : x ≡ 5 [ZMOD 8]) (hy : y ≡ 0 [ZMOD 8]) : + 2 * (x * y) + 6 * y ^ 2 + 4 * x ≡ 4 [ZMOD 8] := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0040/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0040/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..67739d52ee959f56d5beedbf95bbe219d39b2972 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0040/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Let \(x\) and \(y\) be integers with \(x \equiv 5 \pmod{8}\) and \(y \equiv 0 \pmod{8}\). Prove that \(2xy + 6y^2 + 4x \equiv 4 \pmod{8}\). + +## 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/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0040/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0040/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..c4a6c7833cb653a160aff1bafd09bdd528459e54 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0040/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The expression is congruent to the stated residue. -/ +theorem congr_poly2 (x y : ℤ) (hx : x ≡ 5 [ZMOD 8]) (hy : y ≡ 0 [ZMOD 8]) : + 2 * (x * y) + 6 * y ^ 2 + 4 * x ≡ 4 [ZMOD 8] := by + have h1 := (((hx.mul hy).mul_left 2).add ((hy.pow 2).mul_left 6)).add ((hx).mul_left 4) + refine h1.trans ?_ + norm_num [Int.ModEq] diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0040/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0040/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0040/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0040/task.toml b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0040/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..83b03ba377b1c5be5466dc84973cbdaf6571f4b2 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0040/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "congruence_chain", "msc-11", "train", "lean4"] +msc = "11" +family = "congruence_chain" +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/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0040/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0040/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0040/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0040/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0040/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0040/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..6b8073516e0027ef22add083f938915d8c3c5b0b --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0040/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The expression is congruent to the stated residue. -/\ntheorem congr_poly2 (x y : ℤ) (hx : x ≡ 5 [ZMOD 8]) (hy : y ≡ 0 [ZMOD 8]) :\n 2 * (x * y) + 6 * y ^ 2 + 4 * x ≡ 4 [ZMOD 8] := by\n sorry\n", + "targets": [ + { + "name": "congr_poly2", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0040/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0040/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0052/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0052/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0052/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0052/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0052/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..198bed0907f315e81157714173bd7791ce415caf --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0052/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The expression is congruent to the stated residue. -/ +theorem congr_poly2 (x y : ℤ) (hx : x ≡ 6 [ZMOD 9]) (hy : y ≡ 1 [ZMOD 9]) : + (x * y) + 5 * y ^ 2 + 3 * x ≡ 2 [ZMOD 9] := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0052/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0052/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..91877f511467fcc49f508623e50ca72b193bd964 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0052/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Let \(x\) and \(y\) be integers with \(x \equiv 6 \pmod{9}\) and \(y \equiv 1 \pmod{9}\). Prove that \(xy + 5y^2 + 3x \equiv 2 \pmod{9}\). + +## 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/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0052/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0052/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..ea61c9561ea9e01bf6cf342fa0af96d3c721207a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0052/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The expression is congruent to the stated residue. -/ +theorem congr_poly2 (x y : ℤ) (hx : x ≡ 6 [ZMOD 9]) (hy : y ≡ 1 [ZMOD 9]) : + (x * y) + 5 * y ^ 2 + 3 * x ≡ 2 [ZMOD 9] := by + have h1 := ((hx.mul hy).add ((hy.pow 2).mul_left 5)).add ((hx).mul_left 3) + refine h1.trans ?_ + norm_num [Int.ModEq] diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0052/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0052/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0052/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0052/task.toml b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0052/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6ebd0b472f6cdf298ba249416e74c483cc3f371e --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0052/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "congruence_chain", "msc-11", "train", "lean4"] +msc = "11" +family = "congruence_chain" +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/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0052/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0052/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0052/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0052/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0052/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0052/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..0fc8b07ed909434b0a59a978e4afd385d56e9bca --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0052/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The expression is congruent to the stated residue. -/\ntheorem congr_poly2 (x y : ℤ) (hx : x ≡ 6 [ZMOD 9]) (hy : y ≡ 1 [ZMOD 9]) :\n (x * y) + 5 * y ^ 2 + 3 * x ≡ 2 [ZMOD 9] := by\n sorry\n", + "targets": [ + { + "name": "congr_poly2", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0052/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0052/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0064/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0064/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0064/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0064/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0064/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..b7d52e0a71e41eaee88f504a8626122fadda143b --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0064/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The expression is congruent to the stated residue. -/ +theorem congr_poly2 (x y : ℤ) (hx : x ≡ 0 [ZMOD 10]) (hy : y ≡ 6 [ZMOD 10]) : + 2 * (x * y) + y ^ 2 + 7 * x ≡ 6 [ZMOD 10] := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0064/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0064/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2acccd730c4e31c4df8588b5f0423f64578843ef --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0064/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Let \(x\) and \(y\) be integers with \(x \equiv 0 \pmod{10}\) and \(y \equiv 6 \pmod{10}\). Prove that \(2xy + y^2 + 7x \equiv 6 \pmod{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/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0064/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0064/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..460a982b3d7ffe1137c18f5541c989a35ebd9055 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0064/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The expression is congruent to the stated residue. -/ +theorem congr_poly2 (x y : ℤ) (hx : x ≡ 0 [ZMOD 10]) (hy : y ≡ 6 [ZMOD 10]) : + 2 * (x * y) + y ^ 2 + 7 * x ≡ 6 [ZMOD 10] := by + have h1 := (((hx.mul hy).mul_left 2).add (hy.pow 2)).add ((hx).mul_left 7) + refine h1.trans ?_ + norm_num [Int.ModEq] diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0064/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0064/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0064/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0064/task.toml b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0064/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5f26c918380212ad985ad799315ec0fddea04f31 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0064/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "congruence_chain", "msc-11", "train", "lean4"] +msc = "11" +family = "congruence_chain" +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/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0064/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0064/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0064/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0064/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0064/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0064/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..9e38a685c9f13bd0c4b7e2346d36ca0b12599e15 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0064/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The expression is congruent to the stated residue. -/\ntheorem congr_poly2 (x y : ℤ) (hx : x ≡ 0 [ZMOD 10]) (hy : y ≡ 6 [ZMOD 10]) :\n 2 * (x * y) + y ^ 2 + 7 * x ≡ 6 [ZMOD 10] := by\n sorry\n", + "targets": [ + { + "name": "congr_poly2", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0064/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0064/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0076/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0076/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0076/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0076/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0076/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..0cd55806781221576bca9b6ad622a4925af88e5a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0076/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The expression is congruent to the stated residue. -/ +theorem congr_poly2 (x y : ℤ) (hx : x ≡ 0 [ZMOD 13]) (hy : y ≡ 9 [ZMOD 13]) : + 5 * (x * y) + 2 * y ^ 2 + 2 * x ≡ 6 [ZMOD 13] := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0076/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0076/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..50b48ab1d858e73acf51b08c55775e0717e77b1d --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0076/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Let \(x\) and \(y\) be integers with \(x \equiv 0 \pmod{13}\) and \(y \equiv 9 \pmod{13}\). Prove that \(5xy + 2y^2 + 2x \equiv 6 \pmod{13}\). + +## 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/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0076/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0076/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..5e387439a1a032811e2e38e7e7c2b3b5b67361ba --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0076/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The expression is congruent to the stated residue. -/ +theorem congr_poly2 (x y : ℤ) (hx : x ≡ 0 [ZMOD 13]) (hy : y ≡ 9 [ZMOD 13]) : + 5 * (x * y) + 2 * y ^ 2 + 2 * x ≡ 6 [ZMOD 13] := by + have h1 := (((hx.mul hy).mul_left 5).add ((hy.pow 2).mul_left 2)).add ((hx).mul_left 2) + refine h1.trans ?_ + norm_num [Int.ModEq] diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0076/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0076/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0076/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0076/task.toml b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0076/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..495ccc8ca63e4c8c709ecc2a7604aeef470c88ff --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0076/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "congruence_chain", "msc-11", "train", "lean4"] +msc = "11" +family = "congruence_chain" +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/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0076/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0076/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0076/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0076/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0076/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0076/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..18a7fe46e3f1b337453801625ef4d6413533be5e --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0076/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The expression is congruent to the stated residue. -/\ntheorem congr_poly2 (x y : ℤ) (hx : x ≡ 0 [ZMOD 13]) (hy : y ≡ 9 [ZMOD 13]) :\n 5 * (x * y) + 2 * y ^ 2 + 2 * x ≡ 6 [ZMOD 13] := by\n sorry\n", + "targets": [ + { + "name": "congr_poly2", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0076/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d2-t0076/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d3-e0008/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-e0008/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-e0008/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-e0008/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-e0008/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..96bc856ede7ee9dd73634aa2fb93f6faaef86762 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-e0008/environment/workdir/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- A large power of x has the stated residue. -/ +theorem congr_pow (x : ℤ) (h : x ≡ 3 [ZMOD 10]) : + x ^ 18 ≡ 9 [ZMOD 10] := by + sorry + +/-- The combined expression has the stated residue. -/ +theorem congr_product (x y : ℤ) (hx : x ≡ 3 [ZMOD 10]) (hy : y ≡ 4 [ZMOD 10]) : + x ^ 18 * y ^ 12 + 4 ≡ 8 [ZMOD 10] := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-e0008/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-e0008/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..58a3f62c2d83a2ac6fa3fdf5904ec215605676d6 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-e0008/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Let \(x\) and \(y\) be integers with \(x \equiv 3 \pmod{10}\) and \(y \equiv 4 \pmod{10}\). Prove that \(x^{18} \equiv 9 \pmod{10}\), and then that \(x^{18} y^{12} + 4 \equiv 8 \pmod{10}\). + +## 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/modular-arithmetic/modular-arithmetic-congruence_chain-d3-e0008/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-e0008/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..8cad0f043441a750af649a1d57839bbfd5e70dda --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-e0008/solution/Solution.lean @@ -0,0 +1,17 @@ +import Mathlib + +/-- A large power of x has the stated residue. -/ +theorem congr_pow (x : ℤ) (h : x ≡ 3 [ZMOD 10]) : + x ^ 18 ≡ 9 [ZMOD 10] := by + refine (h.pow 18).trans ?_ + norm_num [Int.ModEq] + +/-- The combined expression has the stated residue. -/ +theorem congr_product (x y : ℤ) (hx : x ≡ 3 [ZMOD 10]) (hy : y ≡ 4 [ZMOD 10]) : + x ^ 18 * y ^ 12 + 4 ≡ 8 [ZMOD 10] := by + have h1 := congr_pow x hx + have h2 : y ^ 12 ≡ 6 [ZMOD 10] := by + refine (hy.pow 12).trans ?_ + norm_num [Int.ModEq] + refine ((h1.mul h2).add_right 4).trans ?_ + norm_num [Int.ModEq] diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-e0008/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-e0008/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-e0008/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-e0008/task.toml b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-e0008/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..523e89aeef805415c65d4c2465801122629e9f0e --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-e0008/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "congruence_chain", "msc-11", "eval", "lean4"] +msc = "11" +family = "congruence_chain" +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/modular-arithmetic/modular-arithmetic-congruence_chain-d3-e0008/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-e0008/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d3-e0008/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-e0008/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d3-e0008/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-e0008/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..5f7027c8931b995ec0a20f581faf0283c13e7b12 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-e0008/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\n/-- A large power of x has the stated residue. -/\ntheorem congr_pow (x : ℤ) (h : x ≡ 3 [ZMOD 10]) :\n x ^ 18 ≡ 9 [ZMOD 10] := by\n sorry\n\n/-- The combined expression has the stated residue. -/\ntheorem congr_product (x y : ℤ) (hx : x ≡ 3 [ZMOD 10]) (hy : y ≡ 4 [ZMOD 10]) :\n x ^ 18 * y ^ 12 + 4 ≡ 8 [ZMOD 10] := by\n sorry\n", + "targets": [ + { + "name": "congr_pow", + "weight": 1.0 + }, + { + "name": "congr_product", + "weight": 2.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-e0008/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-e0008/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d3-t0008/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-t0008/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-t0008/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-t0008/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-t0008/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..cfdb0a812aa9f3c71f32718bf8c446940dcd99a8 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-t0008/environment/workdir/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- A large power of x has the stated residue. -/ +theorem congr_pow (x : ℤ) (h : x ≡ 6 [ZMOD 8]) : + x ^ 38 ≡ 0 [ZMOD 8] := by + sorry + +/-- The combined expression has the stated residue. -/ +theorem congr_product (x y : ℤ) (hx : x ≡ 6 [ZMOD 8]) (hy : y ≡ 7 [ZMOD 8]) : + x ^ 38 * y ^ 13 + 3 ≡ 3 [ZMOD 8] := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-t0008/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-t0008/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..851b6742fcd03cf2a634ac23cd2b4107e404020b --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-t0008/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Let \(x\) and \(y\) be integers with \(x \equiv 6 \pmod{8}\) and \(y \equiv 7 \pmod{8}\). Prove that \(x^{38} \equiv 0 \pmod{8}\), and then that \(x^{38} y^{13} + 3 \equiv 3 \pmod{8}\). + +## 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/modular-arithmetic/modular-arithmetic-congruence_chain-d3-t0008/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-t0008/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..7d1cc8374d87290699b6d22b9b2e3c18e00ddad1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-t0008/solution/Solution.lean @@ -0,0 +1,17 @@ +import Mathlib + +/-- A large power of x has the stated residue. -/ +theorem congr_pow (x : ℤ) (h : x ≡ 6 [ZMOD 8]) : + x ^ 38 ≡ 0 [ZMOD 8] := by + refine (h.pow 38).trans ?_ + norm_num [Int.ModEq] + +/-- The combined expression has the stated residue. -/ +theorem congr_product (x y : ℤ) (hx : x ≡ 6 [ZMOD 8]) (hy : y ≡ 7 [ZMOD 8]) : + x ^ 38 * y ^ 13 + 3 ≡ 3 [ZMOD 8] := by + have h1 := congr_pow x hx + have h2 : y ^ 13 ≡ 7 [ZMOD 8] := by + refine (hy.pow 13).trans ?_ + norm_num [Int.ModEq] + refine ((h1.mul h2).add_right 3).trans ?_ + norm_num [Int.ModEq] diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-t0008/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-t0008/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-t0008/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-t0008/task.toml b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-t0008/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b54423b2d1dd049991b0999ee08d3c200c6d2911 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-t0008/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "congruence_chain", "msc-11", "train", "lean4"] +msc = "11" +family = "congruence_chain" +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/modular-arithmetic/modular-arithmetic-congruence_chain-d3-t0008/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-t0008/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d3-t0008/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-t0008/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-congruence_chain-d3-t0008/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-t0008/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..2ebb2ca416237f348dea72c6313abf5b75356f0c --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-t0008/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\n/-- A large power of x has the stated residue. -/\ntheorem congr_pow (x : ℤ) (h : x ≡ 6 [ZMOD 8]) :\n x ^ 38 ≡ 0 [ZMOD 8] := by\n sorry\n\n/-- The combined expression has the stated residue. -/\ntheorem congr_product (x y : ℤ) (hx : x ≡ 6 [ZMOD 8]) (hy : y ≡ 7 [ZMOD 8]) :\n x ^ 38 * y ^ 13 + 3 ≡ 3 [ZMOD 8] := by\n sorry\n", + "targets": [ + { + "name": "congr_pow", + "weight": 1.0 + }, + { + "name": "congr_product", + "weight": 2.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-t0008/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-d3-t0008/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-congruence_chain-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/modular-arithmetic/modular-arithmetic-divisibility-d1-t0061/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0061/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0061/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0061/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0061/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..0092ea7380624938cbad51d775152df3693e8244 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0061/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The integer divides the polynomial value. -/ +theorem dvd_poly (n : ℤ) : + (3 : ℤ) ∣ 31 * n ^ 7 - 28 * n := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0061/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0061/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7452427feab9dbcbdea6f58a1bf0f8198f7406f4 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0061/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every integer \(n\), the number \(3\) divides \(31n^7 - 28n\). + +## 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/modular-arithmetic/modular-arithmetic-divisibility-d1-t0061/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0061/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..36651ac8459d88fe975d8378ede72317c01d775c --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0061/solution/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The integer divides the polynomial value. -/ +theorem dvd_poly (n : ℤ) : + (3 : ℤ) ∣ 31 * n ^ 7 - 28 * n := by + have h : ((31 * n ^ 7 - 28 * n : ℤ) : ZMod 3) = 0 := by + push_cast + generalize (n : ZMod 3) = x + revert x + decide +kernel + exact (ZMod.intCast_zmod_eq_zero_iff_dvd _ _).1 h diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0061/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0061/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0061/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0061/task.toml b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0061/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f4ad88df5d2a731d3246998481e9a4611e41fe0b --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0061/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "divisibility", "msc-11", "train", "lean4"] +msc = "11" +family = "divisibility" +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/modular-arithmetic/modular-arithmetic-divisibility-d1-t0061/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0061/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-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/modular-arithmetic/modular-arithmetic-divisibility-d1-t0061/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0061/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-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/modular-arithmetic/modular-arithmetic-divisibility-d1-t0061/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0061/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..e13da244ae8d2d62abe08e057f3e4ababa2a5f3b --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0061/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The integer divides the polynomial value. -/\ntheorem dvd_poly (n : ℤ) :\n (3 : ℤ) ∣ 31 * n ^ 7 - 28 * n := by\n sorry\n", + "targets": [ + { + "name": "dvd_poly", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0061/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0061/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-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/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..1c77b442326ab321204a5e475207dee241c88d3d --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The integer divides the polynomial value. -/ +theorem dvd_poly (n : ℤ) : + (6 : ℤ) ∣ n ^ 3 + 17 * n := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..12d14049720cc296da5eb31ce02c78e41c44f3f8 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every integer \(n\), the number \(6\) divides \(n^3 + 17n\). + +## 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/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..57562fe09918fc172d1e345a97dc8f7e9d12be8a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/solution/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The integer divides the polynomial value. -/ +theorem dvd_poly (n : ℤ) : + (6 : ℤ) ∣ n ^ 3 + 17 * n := by + have h : ((n ^ 3 + 17 * n : ℤ) : ZMod 6) = 0 := by + push_cast + generalize (n : ZMod 6) = x + revert x + decide +kernel + exact (ZMod.intCast_zmod_eq_zero_iff_dvd _ _).1 h diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/task.toml b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1fab7425bb2a96d7f1fe9763929b132960603378 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "divisibility", "msc-11", "train", "lean4"] +msc = "11" +family = "divisibility" +split = "train" +seed = 73 + +[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/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/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/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/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/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..93e64b623ae9f9db22d70eb2859e2964788fe8bd --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The integer divides the polynomial value. -/\ntheorem dvd_poly (n : ℤ) :\n (6 : ℤ) ∣ n ^ 3 + 17 * n := by\n sorry\n", + "targets": [ + { + "name": "dvd_poly", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d1-t0073/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/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..33b7905b9d46e1c52ea3dacabdfd459a98859be7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The integer divides the polynomial value. -/ +theorem dvd_poly (n : ℤ) : + (42 : ℤ) ∣ 25 * n ^ 7 + 101 * n := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bd30c3c37d5d664f9347ab5b5c29f2215383ce28 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every integer \(n\), the number \(42\) divides \(25n^7 + 101n\). + +## 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/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..fb42c4a5e455d7f57d9c48f8f617dcd0442ddbf4 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/solution/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The integer divides the polynomial value. -/ +theorem dvd_poly (n : ℤ) : + (42 : ℤ) ∣ 25 * n ^ 7 + 101 * n := by + have h : ((25 * n ^ 7 + 101 * n : ℤ) : ZMod 42) = 0 := by + push_cast + generalize (n : ZMod 42) = x + revert x + decide +kernel + exact (ZMod.intCast_zmod_eq_zero_iff_dvd _ _).1 h diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/task.toml b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6ff1eaef5f7063fb8dbafdf32615418aa70d2434 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "divisibility", "msc-11", "eval", "lean4"] +msc = "11" +family = "divisibility" +split = "eval" +seed = 10005 + +[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/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/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/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/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/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..08f4158ede5aef6fe054d516c8ff0133ca08d05c --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The integer divides the polynomial value. -/\ntheorem dvd_poly (n : ℤ) :\n (42 : ℤ) ∣ 25 * n ^ 7 + 101 * n := by\n sorry\n", + "targets": [ + { + "name": "dvd_poly", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0005/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/modular-arithmetic/modular-arithmetic-divisibility-d2-e0017/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0017/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0017/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0017/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0017/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..0a0db10335bd79d2529e7cefb7f6e5f48b25651e --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0017/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The integer divides the polynomial value. -/ +theorem dvd_poly (n : ℤ) : + (6 : ℤ) ∣ 29 * n ^ 3 - 35 * n := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0017/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0017/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..436bcae3c993a7a71cc09e7e5ae05050fa3b1ca1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0017/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every integer \(n\), the number \(6\) divides \(29n^3 - 35n\). + +## 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/modular-arithmetic/modular-arithmetic-divisibility-d2-e0017/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0017/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..463012b1aaa3af9df23f693921a25a00061d2331 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0017/solution/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The integer divides the polynomial value. -/ +theorem dvd_poly (n : ℤ) : + (6 : ℤ) ∣ 29 * n ^ 3 - 35 * n := by + have h : ((29 * n ^ 3 - 35 * n : ℤ) : ZMod 6) = 0 := by + push_cast + generalize (n : ZMod 6) = x + revert x + decide +kernel + exact (ZMod.intCast_zmod_eq_zero_iff_dvd _ _).1 h diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0017/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0017/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0017/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0017/task.toml b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0017/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cc4d33be9d0d11ff3d8362e28a77cb99479ee655 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0017/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "divisibility", "msc-11", "eval", "lean4"] +msc = "11" +family = "divisibility" +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/modular-arithmetic/modular-arithmetic-divisibility-d2-e0017/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0017/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-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/modular-arithmetic/modular-arithmetic-divisibility-d2-e0017/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0017/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-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/modular-arithmetic/modular-arithmetic-divisibility-d2-e0017/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0017/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..2a4810f1921236543294e75633155eca7210772e --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0017/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The integer divides the polynomial value. -/\ntheorem dvd_poly (n : ℤ) :\n (6 : ℤ) ∣ 29 * n ^ 3 - 35 * n := by\n sorry\n", + "targets": [ + { + "name": "dvd_poly", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0017/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-e0017/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-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/modular-arithmetic/modular-arithmetic-divisibility-d2-t0005/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0005/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0005/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0005/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0005/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..809206fd9a71438ff582765b8e886691728a6380 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0005/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The integer divides the polynomial value. -/ +theorem dvd_poly (n : ℤ) : + (6 : ℤ) ∣ 19 * n ^ 3 - 7 * n := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0005/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0005/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..21aeb453407644610125d04e39a926c424e7af75 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0005/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every integer \(n\), the number \(6\) divides \(19n^3 - 7n\). + +## 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/modular-arithmetic/modular-arithmetic-divisibility-d2-t0005/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0005/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..1bc3a1d6df2e56279a5d7f47110ed037c1806931 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0005/solution/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The integer divides the polynomial value. -/ +theorem dvd_poly (n : ℤ) : + (6 : ℤ) ∣ 19 * n ^ 3 - 7 * n := by + have h : ((19 * n ^ 3 - 7 * n : ℤ) : ZMod 6) = 0 := by + push_cast + generalize (n : ZMod 6) = x + revert x + decide +kernel + exact (ZMod.intCast_zmod_eq_zero_iff_dvd _ _).1 h diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0005/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0005/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0005/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0005/task.toml b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0005/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..dcb63d00038fedb61a6d613c1b35e0d8243a8f65 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0005/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "divisibility", "msc-11", "train", "lean4"] +msc = "11" +family = "divisibility" +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/modular-arithmetic/modular-arithmetic-divisibility-d2-t0005/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0005/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-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/modular-arithmetic/modular-arithmetic-divisibility-d2-t0005/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0005/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-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/modular-arithmetic/modular-arithmetic-divisibility-d2-t0005/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0005/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..dc7f8b58503a50d277328b5fb7810f550dc97679 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0005/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The integer divides the polynomial value. -/\ntheorem dvd_poly (n : ℤ) :\n (6 : ℤ) ∣ 19 * n ^ 3 - 7 * n := by\n sorry\n", + "targets": [ + { + "name": "dvd_poly", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0005/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0005/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-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/modular-arithmetic/modular-arithmetic-divisibility-d2-t0017/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0017/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0017/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0017/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0017/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..a3573d77aa2008768a1606620e4a929bbfba19ad --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0017/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The integer divides the polynomial value. -/ +theorem dvd_poly (n : ℤ) : + (6 : ℤ) ∣ 13 * n ^ 3 - 25 * n := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0017/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0017/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..93578bd6048ad2cf3ebdc2a6ba6312d2af3a4638 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0017/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every integer \(n\), the number \(6\) divides \(13n^3 - 25n\). + +## 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/modular-arithmetic/modular-arithmetic-divisibility-d2-t0017/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0017/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..aa87594492aea33cf85c0f995d351bc3ba556792 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0017/solution/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The integer divides the polynomial value. -/ +theorem dvd_poly (n : ℤ) : + (6 : ℤ) ∣ 13 * n ^ 3 - 25 * n := by + have h : ((13 * n ^ 3 - 25 * n : ℤ) : ZMod 6) = 0 := by + push_cast + generalize (n : ZMod 6) = x + revert x + decide +kernel + exact (ZMod.intCast_zmod_eq_zero_iff_dvd _ _).1 h diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0017/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0017/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0017/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0017/task.toml b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0017/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8869dd8c91a809c12598192721278a2829723a48 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0017/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "divisibility", "msc-11", "train", "lean4"] +msc = "11" +family = "divisibility" +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/modular-arithmetic/modular-arithmetic-divisibility-d2-t0017/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0017/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-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/modular-arithmetic/modular-arithmetic-divisibility-d2-t0017/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0017/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-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/modular-arithmetic/modular-arithmetic-divisibility-d2-t0017/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0017/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..335d669b30a443f8202e1a2c5a4d4b980204253e --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0017/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The integer divides the polynomial value. -/\ntheorem dvd_poly (n : ℤ) :\n (6 : ℤ) ∣ 13 * n ^ 3 - 25 * n := by\n sorry\n", + "targets": [ + { + "name": "dvd_poly", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0017/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0017/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-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/modular-arithmetic/modular-arithmetic-divisibility-d2-t0029/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0029/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0029/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0029/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0029/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..c90c18eea160b1753cf1f2fce6ca4449b70e45ec --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0029/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The integer divides the polynomial value. -/ +theorem dvd_poly (n : ℤ) : + (30 : ℤ) ∣ 29 * n ^ 5 + 31 * n := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0029/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0029/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..672e998b09255602d14fe6dc74f8de7dddd165a3 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0029/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every integer \(n\), the number \(30\) divides \(29n^5 + 31n\). + +## 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/modular-arithmetic/modular-arithmetic-divisibility-d2-t0029/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0029/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..fec93c4f947fb04c5a7aea127b76a8eb4b752763 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0029/solution/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The integer divides the polynomial value. -/ +theorem dvd_poly (n : ℤ) : + (30 : ℤ) ∣ 29 * n ^ 5 + 31 * n := by + have h : ((29 * n ^ 5 + 31 * n : ℤ) : ZMod 30) = 0 := by + push_cast + generalize (n : ZMod 30) = x + revert x + decide +kernel + exact (ZMod.intCast_zmod_eq_zero_iff_dvd _ _).1 h diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0029/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0029/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0029/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0029/task.toml b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0029/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3cd5b7674636bea2e3d4b8f0d2075d939f7f0172 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0029/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "divisibility", "msc-11", "train", "lean4"] +msc = "11" +family = "divisibility" +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/modular-arithmetic/modular-arithmetic-divisibility-d2-t0029/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0029/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-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/modular-arithmetic/modular-arithmetic-divisibility-d2-t0029/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0029/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-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/modular-arithmetic/modular-arithmetic-divisibility-d2-t0029/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0029/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..3996a286c571cf686f9472399f47a9fd49e77ec2 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0029/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The integer divides the polynomial value. -/\ntheorem dvd_poly (n : ℤ) :\n (30 : ℤ) ∣ 29 * n ^ 5 + 31 * n := by\n sorry\n", + "targets": [ + { + "name": "dvd_poly", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0029/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d2-t0029/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-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/modular-arithmetic/modular-arithmetic-divisibility-d3-e0021/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-e0021/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-e0021/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-e0021/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-e0021/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..793d54d841c7520dad14b9f0da14e759a34a0215 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-e0021/environment/workdir/Solution.lean @@ -0,0 +1,21 @@ +import Mathlib + +/-- The prime 2 divides the polynomial value. -/ +theorem dvd_by_2 (n : ℤ) : + (2 : ℤ) ∣ n ^ 7 - n := by + sorry + +/-- The prime 3 divides the polynomial value. -/ +theorem dvd_by_3 (n : ℤ) : + (3 : ℤ) ∣ n ^ 7 - n := by + sorry + +/-- The prime 7 divides the polynomial value. -/ +theorem dvd_by_7 (n : ℤ) : + (7 : ℤ) ∣ n ^ 7 - n := by + sorry + +/-- The product of the primes divides the polynomial value. -/ +theorem dvd_poly (n : ℤ) : + (42 : ℤ) ∣ n ^ 7 - n := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-e0021/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-e0021/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..62072a7a99a2a85a07bdfee2eba8898bdae43811 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-e0021/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every integer \(n\), the number \(42\) divides \(n^7 - n\). Prove it first for each prime factor of \(42\), then combine. + +## What to do + +`Solution.lean` in the working directory states 4 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 4 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/modular-arithmetic/modular-arithmetic-divisibility-d3-e0021/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-e0021/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..27cf201e1161c96e7b46a12f4db81717b2ab41ae --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-e0021/solution/Solution.lean @@ -0,0 +1,40 @@ +import Mathlib + +/-- The prime 2 divides the polynomial value. -/ +theorem dvd_by_2 (n : ℤ) : + (2 : ℤ) ∣ n ^ 7 - n := by + have h : ((n ^ 7 - n : ℤ) : ZMod 2) = 0 := by + push_cast + generalize (n : ZMod 2) = x + revert x + decide +kernel + exact (ZMod.intCast_zmod_eq_zero_iff_dvd _ _).1 h + +/-- The prime 3 divides the polynomial value. -/ +theorem dvd_by_3 (n : ℤ) : + (3 : ℤ) ∣ n ^ 7 - n := by + have h : ((n ^ 7 - n : ℤ) : ZMod 3) = 0 := by + push_cast + generalize (n : ZMod 3) = x + revert x + decide +kernel + exact (ZMod.intCast_zmod_eq_zero_iff_dvd _ _).1 h + +/-- The prime 7 divides the polynomial value. -/ +theorem dvd_by_7 (n : ℤ) : + (7 : ℤ) ∣ n ^ 7 - n := by + have h : ((n ^ 7 - n : ℤ) : ZMod 7) = 0 := by + push_cast + generalize (n : ZMod 7) = x + revert x + decide +kernel + exact (ZMod.intCast_zmod_eq_zero_iff_dvd _ _).1 h + +/-- The product of the primes divides the polynomial value. -/ +theorem dvd_poly (n : ℤ) : + (42 : ℤ) ∣ n ^ 7 - n := by + have h2 := dvd_by_2 n + have h3 := dvd_by_3 n + have h7 := dvd_by_7 n + generalize n ^ 7 - n = e at h2 h3 h7 ⊢ + omega diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-e0021/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-e0021/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-e0021/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-e0021/task.toml b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-e0021/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8c00319b052fc6de159ff2091ab0cdcc672457b3 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-e0021/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "divisibility", "msc-11", "eval", "lean4"] +msc = "11" +family = "divisibility" +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/modular-arithmetic/modular-arithmetic-divisibility-d3-e0021/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-e0021/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-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/modular-arithmetic/modular-arithmetic-divisibility-d3-e0021/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-e0021/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-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/modular-arithmetic/modular-arithmetic-divisibility-d3-e0021/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-e0021/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..d94c94d116fa5ee9c57e73216517506b8d9a24f9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-e0021/tests/spec.json @@ -0,0 +1,21 @@ +{ + "reference": "import Mathlib\n\n/-- The prime 2 divides the polynomial value. -/\ntheorem dvd_by_2 (n : ℤ) :\n (2 : ℤ) ∣ n ^ 7 - n := by\n sorry\n\n/-- The prime 3 divides the polynomial value. -/\ntheorem dvd_by_3 (n : ℤ) :\n (3 : ℤ) ∣ n ^ 7 - n := by\n sorry\n\n/-- The prime 7 divides the polynomial value. -/\ntheorem dvd_by_7 (n : ℤ) :\n (7 : ℤ) ∣ n ^ 7 - n := by\n sorry\n\n/-- The product of the primes divides the polynomial value. -/\ntheorem dvd_poly (n : ℤ) :\n (42 : ℤ) ∣ n ^ 7 - n := by\n sorry\n", + "targets": [ + { + "name": "dvd_by_2", + "weight": 1.0 + }, + { + "name": "dvd_by_3", + "weight": 1.0 + }, + { + "name": "dvd_by_7", + "weight": 1.0 + }, + { + "name": "dvd_poly", + "weight": 3.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-e0021/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-e0021/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-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/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..6ead52de6560c1b3c59da60ea2c8f6ece5d975e4 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/environment/workdir/Solution.lean @@ -0,0 +1,21 @@ +import Mathlib + +/-- The prime 2 divides the polynomial value. -/ +theorem dvd_by_2 (n : ℤ) : + (2 : ℤ) ∣ 17 * n ^ 7 - 143 * n := by + sorry + +/-- The prime 3 divides the polynomial value. -/ +theorem dvd_by_3 (n : ℤ) : + (3 : ℤ) ∣ 17 * n ^ 7 - 143 * n := by + sorry + +/-- The prime 7 divides the polynomial value. -/ +theorem dvd_by_7 (n : ℤ) : + (7 : ℤ) ∣ 17 * n ^ 7 - 143 * n := by + sorry + +/-- The product of the primes divides the polynomial value. -/ +theorem dvd_poly (n : ℤ) : + (42 : ℤ) ∣ 17 * n ^ 7 - 143 * n := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b34fc9ee5aabc0589e7a96acf31801a9a8073862 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every integer \(n\), the number \(42\) divides \(17n^7 - 143n\). Prove it first for each prime factor of \(42\), then combine. + +## What to do + +`Solution.lean` in the working directory states 4 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 4 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/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..e639b6859a8fb9ae39c738f62f6d479d166c17e6 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/solution/Solution.lean @@ -0,0 +1,40 @@ +import Mathlib + +/-- The prime 2 divides the polynomial value. -/ +theorem dvd_by_2 (n : ℤ) : + (2 : ℤ) ∣ 17 * n ^ 7 - 143 * n := by + have h : ((17 * n ^ 7 - 143 * n : ℤ) : ZMod 2) = 0 := by + push_cast + generalize (n : ZMod 2) = x + revert x + decide +kernel + exact (ZMod.intCast_zmod_eq_zero_iff_dvd _ _).1 h + +/-- The prime 3 divides the polynomial value. -/ +theorem dvd_by_3 (n : ℤ) : + (3 : ℤ) ∣ 17 * n ^ 7 - 143 * n := by + have h : ((17 * n ^ 7 - 143 * n : ℤ) : ZMod 3) = 0 := by + push_cast + generalize (n : ZMod 3) = x + revert x + decide +kernel + exact (ZMod.intCast_zmod_eq_zero_iff_dvd _ _).1 h + +/-- The prime 7 divides the polynomial value. -/ +theorem dvd_by_7 (n : ℤ) : + (7 : ℤ) ∣ 17 * n ^ 7 - 143 * n := by + have h : ((17 * n ^ 7 - 143 * n : ℤ) : ZMod 7) = 0 := by + push_cast + generalize (n : ZMod 7) = x + revert x + decide +kernel + exact (ZMod.intCast_zmod_eq_zero_iff_dvd _ _).1 h + +/-- The product of the primes divides the polynomial value. -/ +theorem dvd_poly (n : ℤ) : + (42 : ℤ) ∣ 17 * n ^ 7 - 143 * n := by + have h2 := dvd_by_2 n + have h3 := dvd_by_3 n + have h7 := dvd_by_7 n + generalize 17 * n ^ 7 - 143 * n = e at h2 h3 h7 ⊢ + omega diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/task.toml b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1767b7baff867d34c8a7e7d31aec3e197eb217ac --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "divisibility", "msc-11", "train", "lean4"] +msc = "11" +family = "divisibility" +split = "train" +seed = 21 + +[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/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/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/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/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/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..a148a8e5206adc5dffca3b969796e85955468d2b --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/tests/spec.json @@ -0,0 +1,21 @@ +{ + "reference": "import Mathlib\n\n/-- The prime 2 divides the polynomial value. -/\ntheorem dvd_by_2 (n : ℤ) :\n (2 : ℤ) ∣ 17 * n ^ 7 - 143 * n := by\n sorry\n\n/-- The prime 3 divides the polynomial value. -/\ntheorem dvd_by_3 (n : ℤ) :\n (3 : ℤ) ∣ 17 * n ^ 7 - 143 * n := by\n sorry\n\n/-- The prime 7 divides the polynomial value. -/\ntheorem dvd_by_7 (n : ℤ) :\n (7 : ℤ) ∣ 17 * n ^ 7 - 143 * n := by\n sorry\n\n/-- The product of the primes divides the polynomial value. -/\ntheorem dvd_poly (n : ℤ) :\n (42 : ℤ) ∣ 17 * n ^ 7 - 143 * n := by\n sorry\n", + "targets": [ + { + "name": "dvd_by_2", + "weight": 1.0 + }, + { + "name": "dvd_by_3", + "weight": 1.0 + }, + { + "name": "dvd_by_7", + "weight": 1.0 + }, + { + "name": "dvd_poly", + "weight": 3.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0021/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/modular-arithmetic/modular-arithmetic-divisibility-d3-t0033/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0033/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0033/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0033/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0033/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..87d582eb1d4b59f445c7e719e9b64f735cc424e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0033/environment/workdir/Solution.lean @@ -0,0 +1,21 @@ +import Mathlib + +/-- The prime 2 divides the polynomial value. -/ +theorem dvd_by_2 (n : ℤ) : + (2 : ℤ) ∣ 11 * n ^ 5 - 71 * n := by + sorry + +/-- The prime 3 divides the polynomial value. -/ +theorem dvd_by_3 (n : ℤ) : + (3 : ℤ) ∣ 11 * n ^ 5 - 71 * n := by + sorry + +/-- The prime 5 divides the polynomial value. -/ +theorem dvd_by_5 (n : ℤ) : + (5 : ℤ) ∣ 11 * n ^ 5 - 71 * n := by + sorry + +/-- The product of the primes divides the polynomial value. -/ +theorem dvd_poly (n : ℤ) : + (30 : ℤ) ∣ 11 * n ^ 5 - 71 * n := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0033/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0033/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..73c638fd152b4ea86135bc058f09bc2302a9a353 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0033/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every integer \(n\), the number \(30\) divides \(11n^5 - 71n\). Prove it first for each prime factor of \(30\), then combine. + +## What to do + +`Solution.lean` in the working directory states 4 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 4 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/modular-arithmetic/modular-arithmetic-divisibility-d3-t0033/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0033/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..289225a19d54fcaf2d336ac4d8c915499198a9d4 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0033/solution/Solution.lean @@ -0,0 +1,40 @@ +import Mathlib + +/-- The prime 2 divides the polynomial value. -/ +theorem dvd_by_2 (n : ℤ) : + (2 : ℤ) ∣ 11 * n ^ 5 - 71 * n := by + have h : ((11 * n ^ 5 - 71 * n : ℤ) : ZMod 2) = 0 := by + push_cast + generalize (n : ZMod 2) = x + revert x + decide +kernel + exact (ZMod.intCast_zmod_eq_zero_iff_dvd _ _).1 h + +/-- The prime 3 divides the polynomial value. -/ +theorem dvd_by_3 (n : ℤ) : + (3 : ℤ) ∣ 11 * n ^ 5 - 71 * n := by + have h : ((11 * n ^ 5 - 71 * n : ℤ) : ZMod 3) = 0 := by + push_cast + generalize (n : ZMod 3) = x + revert x + decide +kernel + exact (ZMod.intCast_zmod_eq_zero_iff_dvd _ _).1 h + +/-- The prime 5 divides the polynomial value. -/ +theorem dvd_by_5 (n : ℤ) : + (5 : ℤ) ∣ 11 * n ^ 5 - 71 * n := by + have h : ((11 * n ^ 5 - 71 * n : ℤ) : ZMod 5) = 0 := by + push_cast + generalize (n : ZMod 5) = x + revert x + decide +kernel + exact (ZMod.intCast_zmod_eq_zero_iff_dvd _ _).1 h + +/-- The product of the primes divides the polynomial value. -/ +theorem dvd_poly (n : ℤ) : + (30 : ℤ) ∣ 11 * n ^ 5 - 71 * n := by + have h2 := dvd_by_2 n + have h3 := dvd_by_3 n + have h5 := dvd_by_5 n + generalize 11 * n ^ 5 - 71 * n = e at h2 h3 h5 ⊢ + omega diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0033/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0033/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0033/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0033/task.toml b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0033/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a09049ff7d42f519da0e4408e590049e02de0f36 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0033/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "divisibility", "msc-11", "train", "lean4"] +msc = "11" +family = "divisibility" +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/modular-arithmetic/modular-arithmetic-divisibility-d3-t0033/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0033/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-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/modular-arithmetic/modular-arithmetic-divisibility-d3-t0033/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0033/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-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/modular-arithmetic/modular-arithmetic-divisibility-d3-t0033/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0033/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..068c0767bb0c401fd51fd32c2fc8239d38b9904a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0033/tests/spec.json @@ -0,0 +1,21 @@ +{ + "reference": "import Mathlib\n\n/-- The prime 2 divides the polynomial value. -/\ntheorem dvd_by_2 (n : ℤ) :\n (2 : ℤ) ∣ 11 * n ^ 5 - 71 * n := by\n sorry\n\n/-- The prime 3 divides the polynomial value. -/\ntheorem dvd_by_3 (n : ℤ) :\n (3 : ℤ) ∣ 11 * n ^ 5 - 71 * n := by\n sorry\n\n/-- The prime 5 divides the polynomial value. -/\ntheorem dvd_by_5 (n : ℤ) :\n (5 : ℤ) ∣ 11 * n ^ 5 - 71 * n := by\n sorry\n\n/-- The product of the primes divides the polynomial value. -/\ntheorem dvd_poly (n : ℤ) :\n (30 : ℤ) ∣ 11 * n ^ 5 - 71 * n := by\n sorry\n", + "targets": [ + { + "name": "dvd_by_2", + "weight": 1.0 + }, + { + "name": "dvd_by_3", + "weight": 1.0 + }, + { + "name": "dvd_by_5", + "weight": 1.0 + }, + { + "name": "dvd_poly", + "weight": 3.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0033/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0033/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-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/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..b68a262c0b33f679b24063b05bf9bd8bd64cb678 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/environment/workdir/Solution.lean @@ -0,0 +1,21 @@ +import Mathlib + +/-- The prime 2 divides the polynomial value. -/ +theorem dvd_by_2 (n : ℤ) : + (2 : ℤ) ∣ 31 * n ^ 5 - 121 * n := by + sorry + +/-- The prime 3 divides the polynomial value. -/ +theorem dvd_by_3 (n : ℤ) : + (3 : ℤ) ∣ 31 * n ^ 5 - 121 * n := by + sorry + +/-- The prime 5 divides the polynomial value. -/ +theorem dvd_by_5 (n : ℤ) : + (5 : ℤ) ∣ 31 * n ^ 5 - 121 * n := by + sorry + +/-- The product of the primes divides the polynomial value. -/ +theorem dvd_poly (n : ℤ) : + (30 : ℤ) ∣ 31 * n ^ 5 - 121 * n := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..860c3227dc4f9051c0fa4f615beeb1cbd49b4f90 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every integer \(n\), the number \(30\) divides \(31n^5 - 121n\). Prove it first for each prime factor of \(30\), then combine. + +## What to do + +`Solution.lean` in the working directory states 4 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 4 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/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..82ccab66f2e25b08db4ce10b6249d455e1181271 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/solution/Solution.lean @@ -0,0 +1,40 @@ +import Mathlib + +/-- The prime 2 divides the polynomial value. -/ +theorem dvd_by_2 (n : ℤ) : + (2 : ℤ) ∣ 31 * n ^ 5 - 121 * n := by + have h : ((31 * n ^ 5 - 121 * n : ℤ) : ZMod 2) = 0 := by + push_cast + generalize (n : ZMod 2) = x + revert x + decide +kernel + exact (ZMod.intCast_zmod_eq_zero_iff_dvd _ _).1 h + +/-- The prime 3 divides the polynomial value. -/ +theorem dvd_by_3 (n : ℤ) : + (3 : ℤ) ∣ 31 * n ^ 5 - 121 * n := by + have h : ((31 * n ^ 5 - 121 * n : ℤ) : ZMod 3) = 0 := by + push_cast + generalize (n : ZMod 3) = x + revert x + decide +kernel + exact (ZMod.intCast_zmod_eq_zero_iff_dvd _ _).1 h + +/-- The prime 5 divides the polynomial value. -/ +theorem dvd_by_5 (n : ℤ) : + (5 : ℤ) ∣ 31 * n ^ 5 - 121 * n := by + have h : ((31 * n ^ 5 - 121 * n : ℤ) : ZMod 5) = 0 := by + push_cast + generalize (n : ZMod 5) = x + revert x + decide +kernel + exact (ZMod.intCast_zmod_eq_zero_iff_dvd _ _).1 h + +/-- The product of the primes divides the polynomial value. -/ +theorem dvd_poly (n : ℤ) : + (30 : ℤ) ∣ 31 * n ^ 5 - 121 * n := by + have h2 := dvd_by_2 n + have h3 := dvd_by_3 n + have h5 := dvd_by_5 n + generalize 31 * n ^ 5 - 121 * n = e at h2 h3 h5 ⊢ + omega diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/task.toml b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1b8d3600b7d39359a7f69ae405aa3167d181a023 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "divisibility", "msc-11", "train", "lean4"] +msc = "11" +family = "divisibility" +split = "train" +seed = 45 + +[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/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/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/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/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/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..2b50ed9c689df021e44d5a1a594e2d0c06a0bb70 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/tests/spec.json @@ -0,0 +1,21 @@ +{ + "reference": "import Mathlib\n\n/-- The prime 2 divides the polynomial value. -/\ntheorem dvd_by_2 (n : ℤ) :\n (2 : ℤ) ∣ 31 * n ^ 5 - 121 * n := by\n sorry\n\n/-- The prime 3 divides the polynomial value. -/\ntheorem dvd_by_3 (n : ℤ) :\n (3 : ℤ) ∣ 31 * n ^ 5 - 121 * n := by\n sorry\n\n/-- The prime 5 divides the polynomial value. -/\ntheorem dvd_by_5 (n : ℤ) :\n (5 : ℤ) ∣ 31 * n ^ 5 - 121 * n := by\n sorry\n\n/-- The product of the primes divides the polynomial value. -/\ntheorem dvd_poly (n : ℤ) :\n (30 : ℤ) ∣ 31 * n ^ 5 - 121 * n := by\n sorry\n", + "targets": [ + { + "name": "dvd_by_2", + "weight": 1.0 + }, + { + "name": "dvd_by_3", + "weight": 1.0 + }, + { + "name": "dvd_by_5", + "weight": 1.0 + }, + { + "name": "dvd_poly", + "weight": 3.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0045/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/modular-arithmetic/modular-arithmetic-divisibility-d3-t0057/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0057/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0057/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0057/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0057/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..b1731dc5cccc8f0b7dc86e44b8b930b91ee7d4c3 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0057/environment/workdir/Solution.lean @@ -0,0 +1,21 @@ +import Mathlib + +/-- The prime 2 divides the polynomial value. -/ +theorem dvd_by_2 (n : ℤ) : + (2 : ℤ) ∣ 23 * n ^ 7 + 61 * n := by + sorry + +/-- The prime 3 divides the polynomial value. -/ +theorem dvd_by_3 (n : ℤ) : + (3 : ℤ) ∣ 23 * n ^ 7 + 61 * n := by + sorry + +/-- The prime 7 divides the polynomial value. -/ +theorem dvd_by_7 (n : ℤ) : + (7 : ℤ) ∣ 23 * n ^ 7 + 61 * n := by + sorry + +/-- The product of the primes divides the polynomial value. -/ +theorem dvd_poly (n : ℤ) : + (42 : ℤ) ∣ 23 * n ^ 7 + 61 * n := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0057/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0057/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0087c843ef71adccdb714d734253770110711e66 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0057/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every integer \(n\), the number \(42\) divides \(23n^7 + 61n\). Prove it first for each prime factor of \(42\), then combine. + +## What to do + +`Solution.lean` in the working directory states 4 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 4 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/modular-arithmetic/modular-arithmetic-divisibility-d3-t0057/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0057/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..16b214c57297ae742f8c2509ee7a94e3482d2a90 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0057/solution/Solution.lean @@ -0,0 +1,40 @@ +import Mathlib + +/-- The prime 2 divides the polynomial value. -/ +theorem dvd_by_2 (n : ℤ) : + (2 : ℤ) ∣ 23 * n ^ 7 + 61 * n := by + have h : ((23 * n ^ 7 + 61 * n : ℤ) : ZMod 2) = 0 := by + push_cast + generalize (n : ZMod 2) = x + revert x + decide +kernel + exact (ZMod.intCast_zmod_eq_zero_iff_dvd _ _).1 h + +/-- The prime 3 divides the polynomial value. -/ +theorem dvd_by_3 (n : ℤ) : + (3 : ℤ) ∣ 23 * n ^ 7 + 61 * n := by + have h : ((23 * n ^ 7 + 61 * n : ℤ) : ZMod 3) = 0 := by + push_cast + generalize (n : ZMod 3) = x + revert x + decide +kernel + exact (ZMod.intCast_zmod_eq_zero_iff_dvd _ _).1 h + +/-- The prime 7 divides the polynomial value. -/ +theorem dvd_by_7 (n : ℤ) : + (7 : ℤ) ∣ 23 * n ^ 7 + 61 * n := by + have h : ((23 * n ^ 7 + 61 * n : ℤ) : ZMod 7) = 0 := by + push_cast + generalize (n : ZMod 7) = x + revert x + decide +kernel + exact (ZMod.intCast_zmod_eq_zero_iff_dvd _ _).1 h + +/-- The product of the primes divides the polynomial value. -/ +theorem dvd_poly (n : ℤ) : + (42 : ℤ) ∣ 23 * n ^ 7 + 61 * n := by + have h2 := dvd_by_2 n + have h3 := dvd_by_3 n + have h7 := dvd_by_7 n + generalize 23 * n ^ 7 + 61 * n = e at h2 h3 h7 ⊢ + omega diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0057/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0057/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0057/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0057/task.toml b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0057/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fae853a2d11639bfa43c5a963a90ee7cab72dd01 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0057/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "divisibility", "msc-11", "train", "lean4"] +msc = "11" +family = "divisibility" +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/modular-arithmetic/modular-arithmetic-divisibility-d3-t0057/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0057/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-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/modular-arithmetic/modular-arithmetic-divisibility-d3-t0057/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0057/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-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/modular-arithmetic/modular-arithmetic-divisibility-d3-t0057/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0057/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..be06dc47a356b8802d8601901d0f62d5736e7d08 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0057/tests/spec.json @@ -0,0 +1,21 @@ +{ + "reference": "import Mathlib\n\n/-- The prime 2 divides the polynomial value. -/\ntheorem dvd_by_2 (n : ℤ) :\n (2 : ℤ) ∣ 23 * n ^ 7 + 61 * n := by\n sorry\n\n/-- The prime 3 divides the polynomial value. -/\ntheorem dvd_by_3 (n : ℤ) :\n (3 : ℤ) ∣ 23 * n ^ 7 + 61 * n := by\n sorry\n\n/-- The prime 7 divides the polynomial value. -/\ntheorem dvd_by_7 (n : ℤ) :\n (7 : ℤ) ∣ 23 * n ^ 7 + 61 * n := by\n sorry\n\n/-- The product of the primes divides the polynomial value. -/\ntheorem dvd_poly (n : ℤ) :\n (42 : ℤ) ∣ 23 * n ^ 7 + 61 * n := by\n sorry\n", + "targets": [ + { + "name": "dvd_by_2", + "weight": 1.0 + }, + { + "name": "dvd_by_3", + "weight": 1.0 + }, + { + "name": "dvd_by_7", + "weight": 1.0 + }, + { + "name": "dvd_poly", + "weight": 3.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0057/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0057/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-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/modular-arithmetic/modular-arithmetic-divisibility-d3-t0069/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0069/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0069/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0069/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0069/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..78e3ad27317982a89cab6e486f310773d1e7f30f --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0069/environment/workdir/Solution.lean @@ -0,0 +1,21 @@ +import Mathlib + +/-- The prime 2 divides the polynomial value. -/ +theorem dvd_by_2 (n : ℤ) : + (2 : ℤ) ∣ 17 * n ^ 7 + 109 * n := by + sorry + +/-- The prime 3 divides the polynomial value. -/ +theorem dvd_by_3 (n : ℤ) : + (3 : ℤ) ∣ 17 * n ^ 7 + 109 * n := by + sorry + +/-- The prime 7 divides the polynomial value. -/ +theorem dvd_by_7 (n : ℤ) : + (7 : ℤ) ∣ 17 * n ^ 7 + 109 * n := by + sorry + +/-- The product of the primes divides the polynomial value. -/ +theorem dvd_poly (n : ℤ) : + (42 : ℤ) ∣ 17 * n ^ 7 + 109 * n := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0069/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0069/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5ac4af5adc376bd8800e9cec789c7e92d97a257d --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0069/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every integer \(n\), the number \(42\) divides \(17n^7 + 109n\). Prove it first for each prime factor of \(42\), then combine. + +## What to do + +`Solution.lean` in the working directory states 4 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 4 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/modular-arithmetic/modular-arithmetic-divisibility-d3-t0069/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0069/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..0e079c7c3f4d6b56c29b874eca320ce2b9f412f9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0069/solution/Solution.lean @@ -0,0 +1,40 @@ +import Mathlib + +/-- The prime 2 divides the polynomial value. -/ +theorem dvd_by_2 (n : ℤ) : + (2 : ℤ) ∣ 17 * n ^ 7 + 109 * n := by + have h : ((17 * n ^ 7 + 109 * n : ℤ) : ZMod 2) = 0 := by + push_cast + generalize (n : ZMod 2) = x + revert x + decide +kernel + exact (ZMod.intCast_zmod_eq_zero_iff_dvd _ _).1 h + +/-- The prime 3 divides the polynomial value. -/ +theorem dvd_by_3 (n : ℤ) : + (3 : ℤ) ∣ 17 * n ^ 7 + 109 * n := by + have h : ((17 * n ^ 7 + 109 * n : ℤ) : ZMod 3) = 0 := by + push_cast + generalize (n : ZMod 3) = x + revert x + decide +kernel + exact (ZMod.intCast_zmod_eq_zero_iff_dvd _ _).1 h + +/-- The prime 7 divides the polynomial value. -/ +theorem dvd_by_7 (n : ℤ) : + (7 : ℤ) ∣ 17 * n ^ 7 + 109 * n := by + have h : ((17 * n ^ 7 + 109 * n : ℤ) : ZMod 7) = 0 := by + push_cast + generalize (n : ZMod 7) = x + revert x + decide +kernel + exact (ZMod.intCast_zmod_eq_zero_iff_dvd _ _).1 h + +/-- The product of the primes divides the polynomial value. -/ +theorem dvd_poly (n : ℤ) : + (42 : ℤ) ∣ 17 * n ^ 7 + 109 * n := by + have h2 := dvd_by_2 n + have h3 := dvd_by_3 n + have h7 := dvd_by_7 n + generalize 17 * n ^ 7 + 109 * n = e at h2 h3 h7 ⊢ + omega diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0069/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0069/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0069/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0069/task.toml b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0069/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a8f592727506897c6d543b858d17140f79359cdc --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0069/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "divisibility", "msc-11", "train", "lean4"] +msc = "11" +family = "divisibility" +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/modular-arithmetic/modular-arithmetic-divisibility-d3-t0069/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0069/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-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/modular-arithmetic/modular-arithmetic-divisibility-d3-t0069/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0069/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-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/modular-arithmetic/modular-arithmetic-divisibility-d3-t0069/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0069/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..ef0b7920ef7530a8b54e75f8b1700014e33a36ad --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0069/tests/spec.json @@ -0,0 +1,21 @@ +{ + "reference": "import Mathlib\n\n/-- The prime 2 divides the polynomial value. -/\ntheorem dvd_by_2 (n : ℤ) :\n (2 : ℤ) ∣ 17 * n ^ 7 + 109 * n := by\n sorry\n\n/-- The prime 3 divides the polynomial value. -/\ntheorem dvd_by_3 (n : ℤ) :\n (3 : ℤ) ∣ 17 * n ^ 7 + 109 * n := by\n sorry\n\n/-- The prime 7 divides the polynomial value. -/\ntheorem dvd_by_7 (n : ℤ) :\n (7 : ℤ) ∣ 17 * n ^ 7 + 109 * n := by\n sorry\n\n/-- The product of the primes divides the polynomial value. -/\ntheorem dvd_poly (n : ℤ) :\n (42 : ℤ) ∣ 17 * n ^ 7 + 109 * n := by\n sorry\n", + "targets": [ + { + "name": "dvd_by_2", + "weight": 1.0 + }, + { + "name": "dvd_by_3", + "weight": 1.0 + }, + { + "name": "dvd_by_7", + "weight": 1.0 + }, + { + "name": "dvd_poly", + "weight": 3.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0069/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-divisibility-d3-t0069/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-divisibility-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/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..992ea1df4940dd20b70dbbc340602b11da0eb655 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The two linear forms are coprime. -/ +theorem coprime_int (n : ℤ) : + IsCoprime (5 * n + 2) (8 * n + 3) := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..886315a9564273b52c11698af1aa5a0f0da4f00c --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every integer \(n\), the integers \(5n + 2\) and \(8n + 3\) are coprime, in the sense that \(u(5n + 2) + v(8n + 3) = 1\) for some integers \(u, v\). + +## 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/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..6be397de97dca991aea479762ec73e76542efe7a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/solution/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The two linear forms are coprime. -/ +theorem coprime_int (n : ℤ) : + IsCoprime (5 * n + 2) (8 * n + 3) := by + exact ⟨8, (-5), by ring⟩ diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/task.toml b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a8086fa3456ac646fcb4199b01c7d8b94c5d3827 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "gcd_coprime", "msc-11", "eval", "lean4"] +msc = "11" +family = "gcd_coprime" +split = "eval" +seed = 10002 + +[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/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..2d38d059a2573d8b99375fc7d7d0c4ca871282af --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The two linear forms are coprime. -/\ntheorem coprime_int (n : ℤ) :\n IsCoprime (5 * n + 2) (8 * n + 3) := by\n sorry\n", + "targets": [ + { + "name": "coprime_int", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-e0002/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..95d02675c06fee42e1b5022ac3e5b087becc9004 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The two linear forms are coprime. -/ +theorem coprime_int (n : ℤ) : + IsCoprime (n + 8) (3 * n + 25) := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ba255cbfde8e39dc1bb4b52b68e5bb2d36505718 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every integer \(n\), the integers \(n + 8\) and \(3n + 25\) are coprime, in the sense that \(u(n + 8) + v(3n + 25) = 1\) for some integers \(u, v\). + +## 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/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..4197da33c9f82ed4b1042235102a18199c522cf7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/solution/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The two linear forms are coprime. -/ +theorem coprime_int (n : ℤ) : + IsCoprime (n + 8) (3 * n + 25) := by + exact ⟨(-3), 1, by ring⟩ diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/task.toml b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bab42b3b3e492a172db272c1aec1885d3933cf2c --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "gcd_coprime", "msc-11", "train", "lean4"] +msc = "11" +family = "gcd_coprime" +split = "train" +seed = 2 + +[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/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..0ca32cbad73d089b4420dac09cf6beacba46c011 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The two linear forms are coprime. -/\ntheorem coprime_int (n : ℤ) :\n IsCoprime (n + 8) (3 * n + 25) := by\n sorry\n", + "targets": [ + { + "name": "coprime_int", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0002/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..7869300c4f11e90c77ef64150bd1bf8e87269f8f --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The two linear forms are coprime. -/ +theorem coprime_int (n : ℤ) : + IsCoprime (2 * n + 3) (5 * n + 7) := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c260780a2ed78fa45777f33540603fd16bc810e4 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every integer \(n\), the integers \(2n + 3\) and \(5n + 7\) are coprime, in the sense that \(u(2n + 3) + v(5n + 7) = 1\) for some integers \(u, v\). + +## 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/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..4bed1f977bc671c79fca831cc057ac8b56322593 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/solution/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The two linear forms are coprime. -/ +theorem coprime_int (n : ℤ) : + IsCoprime (2 * n + 3) (5 * n + 7) := by + exact ⟨5, (-2), by ring⟩ diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/task.toml b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5d4151e97edf70d456b9a3bfd14736dca17a8117 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "gcd_coprime", "msc-11", "train", "lean4"] +msc = "11" +family = "gcd_coprime" +split = "train" +seed = 26 + +[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/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..2c4c6b9b0d1c6eb8006a6a266d8fc52be2442479 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The two linear forms are coprime. -/\ntheorem coprime_int (n : ℤ) :\n IsCoprime (2 * n + 3) (5 * n + 7) := by\n sorry\n", + "targets": [ + { + "name": "coprime_int", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0026/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..2092af35e47894f429f3c57cfd496efbe49dcf38 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The two linear forms are coprime. -/ +theorem coprime_int (n : ℤ) : + IsCoprime (2 * n + 7) (9 * n + 31) := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9dc0c040729af35ae61814d7d89228facbf03fe3 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every integer \(n\), the integers \(2n + 7\) and \(9n + 31\) are coprime, in the sense that \(u(2n + 7) + v(9n + 31) = 1\) for some integers \(u, v\). + +## 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/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..0eaf9de3a11cd5717e42cb199345f5c6b239a374 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/solution/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The two linear forms are coprime. -/ +theorem coprime_int (n : ℤ) : + IsCoprime (2 * n + 7) (9 * n + 31) := by + exact ⟨9, (-2), by ring⟩ diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/task.toml b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..332db6cf396d0591a2a63f6a063062ee49aba99d --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "gcd_coprime", "msc-11", "train", "lean4"] +msc = "11" +family = "gcd_coprime" +split = "train" +seed = 50 + +[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/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..c9b504cb368b47fc696407d936664dbeee707b44 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The two linear forms are coprime. -/\ntheorem coprime_int (n : ℤ) :\n IsCoprime (2 * n + 7) (9 * n + 31) := by\n sorry\n", + "targets": [ + { + "name": "coprime_int", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0050/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..33b93754334d3912e470ce45d75a2e503d0c0102 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The two linear forms are coprime. -/ +theorem coprime_int (n : ℤ) : + IsCoprime (2 * n + 9) (3 * n + 14) := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d58c193a180e062f08ab0d9ba0b95fc8530d1fb1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every integer \(n\), the integers \(2n + 9\) and \(3n + 14\) are coprime, in the sense that \(u(2n + 9) + v(3n + 14) = 1\) for some integers \(u, v\). + +## 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/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..203dbd3ec494897b334c26acead21e49df00025f --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/solution/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The two linear forms are coprime. -/ +theorem coprime_int (n : ℤ) : + IsCoprime (2 * n + 9) (3 * n + 14) := by + exact ⟨(-3), 2, by ring⟩ diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/task.toml b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..476c15f69c82a3fede48a93cff750ebd38f82d43 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "gcd_coprime", "msc-11", "train", "lean4"] +msc = "11" +family = "gcd_coprime" +split = "train" +seed = 74 + +[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/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..bef74d0d8917ffd91427be7a9381ff2eb868f662 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The two linear forms are coprime. -/\ntheorem coprime_int (n : ℤ) :\n IsCoprime (2 * n + 9) (3 * n + 14) := by\n sorry\n", + "targets": [ + { + "name": "coprime_int", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d1-t0074/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..640c342e4a798d18e01a32cd87baf172b6d31d4f --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The two linear forms are coprime. -/ +theorem coprime_nat (n : ℕ) : + Nat.Coprime (2 * n + 5) (9 * n + 23) := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2a7f4b9aa0112a97310b322fbd73bf494d13c389 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every natural number \(n\), the numbers \(2n + 5\) and \(9n + 23\) are coprime. + +## 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/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..632dd5b9b227e2efc63f522dfd42b0e00b086d68 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The two linear forms are coprime. -/ +theorem coprime_nat (n : ℕ) : + Nat.Coprime (2 * n + 5) (9 * n + 23) := by + rw [← Nat.isCoprime_iff_coprime] + push_cast + exact ⟨(-9), 2, by ring⟩ diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/task.toml b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4b5ce625e2911d63842844a09913ce03f803f3ba --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "gcd_coprime", "msc-11", "eval", "lean4"] +msc = "11" +family = "gcd_coprime" +split = "eval" +seed = 10018 + +[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/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..a3f01a0cac73a699a24b61237fe04bedfde76ad1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The two linear forms are coprime. -/\ntheorem coprime_nat (n : ℕ) :\n Nat.Coprime (2 * n + 5) (9 * n + 23) := by\n sorry\n", + "targets": [ + { + "name": "coprime_nat", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-e0018/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..ecd13bccc3c56e95dd9af6e686d124f4814149c4 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The two linear forms are coprime. -/ +theorem coprime_nat (n : ℕ) : + Nat.Coprime (n + 5) (9 * n + 46) := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d0135d125ec9b76e2d62092f335b5e057523b4b7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every natural number \(n\), the numbers \(n + 5\) and \(9n + 46\) are coprime. + +## 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/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..e6d75ea158f758212cfd62cad6db43e15a818eda --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The two linear forms are coprime. -/ +theorem coprime_nat (n : ℕ) : + Nat.Coprime (n + 5) (9 * n + 46) := by + rw [← Nat.isCoprime_iff_coprime] + push_cast + exact ⟨(-9), 1, by ring⟩ diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/task.toml b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..457f00f3f4e07b523d9e4b00d4daf74eda4229ea --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "gcd_coprime", "msc-11", "train", "lean4"] +msc = "11" +family = "gcd_coprime" +split = "train" +seed = 18 + +[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/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..be8782c316b474c9e05021c1ef247a99d238d64e --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The two linear forms are coprime. -/\ntheorem coprime_nat (n : ℕ) :\n Nat.Coprime (n + 5) (9 * n + 46) := by\n sorry\n", + "targets": [ + { + "name": "coprime_nat", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0018/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..037af570399f74070539b57fdd567e36eed54a82 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The two linear forms are coprime. -/ +theorem coprime_nat (n : ℕ) : + Nat.Coprime (3 * n + 7) (4 * n + 9) := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c29f6356d7f235a408af433acb9ff0ec7a3ca659 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every natural number \(n\), the numbers \(3n + 7\) and \(4n + 9\) are coprime. + +## 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/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..25d139842665024aef5afc6abac8fad5e318f7f6 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The two linear forms are coprime. -/ +theorem coprime_nat (n : ℕ) : + Nat.Coprime (3 * n + 7) (4 * n + 9) := by + rw [← Nat.isCoprime_iff_coprime] + push_cast + exact ⟨4, (-3), by ring⟩ diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/task.toml b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4e9e6c4bbf029639cd38fa22f65fa945271ad417 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "gcd_coprime", "msc-11", "train", "lean4"] +msc = "11" +family = "gcd_coprime" +split = "train" +seed = 42 + +[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/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..d117ba8b15ac64223da9897475b3693f3237755c --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The two linear forms are coprime. -/\ntheorem coprime_nat (n : ℕ) :\n Nat.Coprime (3 * n + 7) (4 * n + 9) := by\n sorry\n", + "targets": [ + { + "name": "coprime_nat", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0042/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0066/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0066/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0066/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0066/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0066/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..49c4ea0685b11a0eef7eaf4ae289d6cd19e9530a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0066/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The two linear forms are coprime. -/ +theorem coprime_nat (n : ℕ) : + Nat.Coprime (4 * n + 5) (n + 1) := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0066/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0066/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d786586c8a279205014d3d218e9a98c37005a07a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0066/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every natural number \(n\), the numbers \(4n + 5\) and \(n + 1\) are coprime. + +## 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/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0066/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0066/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..55e4a358f51e70f4b408e381a547be694aadde71 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0066/solution/Solution.lean @@ -0,0 +1,8 @@ +import Mathlib + +/-- The two linear forms are coprime. -/ +theorem coprime_nat (n : ℕ) : + Nat.Coprime (4 * n + 5) (n + 1) := by + rw [← Nat.isCoprime_iff_coprime] + push_cast + exact ⟨1, (-4), by ring⟩ diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0066/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0066/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0066/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0066/task.toml b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0066/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5f32340ca1429f6bf785cae400e31b1a3e443aae --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0066/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "gcd_coprime", "msc-11", "train", "lean4"] +msc = "11" +family = "gcd_coprime" +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/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0066/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0066/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-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/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0066/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0066/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-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/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0066/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0066/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..530c5cedf4ee0b9483a22453b2a5241029269b30 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0066/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The two linear forms are coprime. -/\ntheorem coprime_nat (n : ℕ) :\n Nat.Coprime (4 * n + 5) (n + 1) := by\n sorry\n", + "targets": [ + { + "name": "coprime_nat", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0066/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d2-t0066/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-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/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..9527d71a1cc6d594650c12bd0abbe0ed47f6927f --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/environment/workdir/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The gcd divides the determinant. -/ +theorem gcd_dvd_det (n : ℕ) : + Nat.gcd (5 * n + 7) (6 * n + 9) ∣ 3 := by + sorry + +/-- The gcd is 1 or the prime determinant. -/ +theorem gcd_one_or_prime (n : ℕ) : + Nat.gcd (5 * n + 7) (6 * n + 9) = 1 ∨ Nat.gcd (5 * n + 7) (6 * n + 9) = 3 := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d95e269c7a694a6426e9518fe71d9e1bd9e1f331 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Let \(n\) be a natural number and \(g = \gcd(5n + 7, 6n + 9)\). Prove that \(g\) divides \(3\), and conclude that \(g = 1\) or \(g = 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/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..59c4cc8a066735ad89c0d625996cb98c59a861fd --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/solution/Solution.lean @@ -0,0 +1,16 @@ +import Mathlib + +/-- The gcd divides the determinant. -/ +theorem gcd_dvd_det (n : ℕ) : + Nat.gcd (5 * n + 7) (6 * n + 9) ∣ 3 := by + have h1 : Nat.gcd (5 * n + 7) (6 * n + 9) ∣ 5 * n + 7 := Nat.gcd_dvd_left _ _ + have h2 : Nat.gcd (5 * n + 7) (6 * n + 9) ∣ 6 * n + 9 := Nat.gcd_dvd_right _ _ + have h3 := Nat.dvd_sub (Dvd.dvd.mul_left h2 5) (Dvd.dvd.mul_left h1 6) + have e : 5 * (6 * n + 9) - 6 * (5 * n + 7) = 3 := by omega + rw [e] at h3 + exact h3 + +/-- The gcd is 1 or the prime determinant. -/ +theorem gcd_one_or_prime (n : ℕ) : + Nat.gcd (5 * n + 7) (6 * n + 9) = 1 ∨ Nat.gcd (5 * n + 7) (6 * n + 9) = 3 := by + exact (Nat.dvd_prime (by norm_num)).1 (gcd_dvd_det n) diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/task.toml b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..97a81799a18c31116709cb49710180cd1e15712d --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "gcd_coprime", "msc-11", "eval", "lean4"] +msc = "11" +family = "gcd_coprime" +split = "eval" +seed = 10010 + +[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/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..30ae0fdeb9bc7bf383fce2401d6fa67def0471ed --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\n/-- The gcd divides the determinant. -/\ntheorem gcd_dvd_det (n : ℕ) :\n Nat.gcd (5 * n + 7) (6 * n + 9) ∣ 3 := by\n sorry\n\n/-- The gcd is 1 or the prime determinant. -/\ntheorem gcd_one_or_prime (n : ℕ) :\n Nat.gcd (5 * n + 7) (6 * n + 9) = 1 ∨ Nat.gcd (5 * n + 7) (6 * n + 9) = 3 := by\n sorry\n", + "targets": [ + { + "name": "gcd_dvd_det", + "weight": 1.0 + }, + { + "name": "gcd_one_or_prime", + "weight": 2.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-e0010/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..5125727fe7ed3ed5f957636a748f5081db368d1f --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/environment/workdir/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The gcd divides the determinant. -/ +theorem gcd_dvd_det (n : ℕ) : + Nat.gcd (2 * n + 4) (3 * n + 7) ∣ 2 := by + sorry + +/-- The gcd is 1 or the prime determinant. -/ +theorem gcd_one_or_prime (n : ℕ) : + Nat.gcd (2 * n + 4) (3 * n + 7) = 1 ∨ Nat.gcd (2 * n + 4) (3 * n + 7) = 2 := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1b8c5fb8d57a38ffe47d36db44b8202fe91de330 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Let \(n\) be a natural number and \(g = \gcd(2n + 4, 3n + 7)\). Prove that \(g\) divides \(2\), and conclude that \(g = 1\) or \(g = 2\). + +## 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/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..c761bc451c7dc4a328e8618c88e9cdcce2972141 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/solution/Solution.lean @@ -0,0 +1,16 @@ +import Mathlib + +/-- The gcd divides the determinant. -/ +theorem gcd_dvd_det (n : ℕ) : + Nat.gcd (2 * n + 4) (3 * n + 7) ∣ 2 := by + have h1 : Nat.gcd (2 * n + 4) (3 * n + 7) ∣ 2 * n + 4 := Nat.gcd_dvd_left _ _ + have h2 : Nat.gcd (2 * n + 4) (3 * n + 7) ∣ 3 * n + 7 := Nat.gcd_dvd_right _ _ + have h3 := Nat.dvd_sub (Dvd.dvd.mul_left h2 2) (Dvd.dvd.mul_left h1 3) + have e : 2 * (3 * n + 7) - 3 * (2 * n + 4) = 2 := by omega + rw [e] at h3 + exact h3 + +/-- The gcd is 1 or the prime determinant. -/ +theorem gcd_one_or_prime (n : ℕ) : + Nat.gcd (2 * n + 4) (3 * n + 7) = 1 ∨ Nat.gcd (2 * n + 4) (3 * n + 7) = 2 := by + exact (Nat.dvd_prime (by norm_num)).1 (gcd_dvd_det n) diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/task.toml b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7b787ee0e57935ee15261f6e00f5ff665e4502d5 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "gcd_coprime", "msc-11", "train", "lean4"] +msc = "11" +family = "gcd_coprime" +split = "train" +seed = 10 + +[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/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..9bb4df6bb3cd3e5418f7690e8cc36fa87947e818 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\n/-- The gcd divides the determinant. -/\ntheorem gcd_dvd_det (n : ℕ) :\n Nat.gcd (2 * n + 4) (3 * n + 7) ∣ 2 := by\n sorry\n\n/-- The gcd is 1 or the prime determinant. -/\ntheorem gcd_one_or_prime (n : ℕ) :\n Nat.gcd (2 * n + 4) (3 * n + 7) = 1 ∨ Nat.gcd (2 * n + 4) (3 * n + 7) = 2 := by\n sorry\n", + "targets": [ + { + "name": "gcd_dvd_det", + "weight": 1.0 + }, + { + "name": "gcd_one_or_prime", + "weight": 2.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0010/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..516eada504c638d26e8f1d02248801d9e659c01f --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/environment/workdir/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The gcd divides the determinant. -/ +theorem gcd_dvd_det (n : ℕ) : + Nat.gcd (n + 5) (3 * n + 4) ∣ 11 := by + sorry + +/-- The gcd is 1 or the prime determinant. -/ +theorem gcd_one_or_prime (n : ℕ) : + Nat.gcd (n + 5) (3 * n + 4) = 1 ∨ Nat.gcd (n + 5) (3 * n + 4) = 11 := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0f89d3dda1e591c8b5f22f0503012fac24df06f5 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Let \(n\) be a natural number and \(g = \gcd(n + 5, 3n + 4)\). Prove that \(g\) divides \(11\), and conclude that \(g = 1\) or \(g = 11\). + +## 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/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..6368ebb15fef44ffe36254fcca36c3de47387db6 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/solution/Solution.lean @@ -0,0 +1,16 @@ +import Mathlib + +/-- The gcd divides the determinant. -/ +theorem gcd_dvd_det (n : ℕ) : + Nat.gcd (n + 5) (3 * n + 4) ∣ 11 := by + have h1 : Nat.gcd (n + 5) (3 * n + 4) ∣ n + 5 := Nat.gcd_dvd_left _ _ + have h2 : Nat.gcd (n + 5) (3 * n + 4) ∣ 3 * n + 4 := Nat.gcd_dvd_right _ _ + have h3 := Nat.dvd_sub (Dvd.dvd.mul_left h1 3) (Dvd.dvd.mul_left h2 1) + have e : 3 * (n + 5) - 1 * (3 * n + 4) = 11 := by omega + rw [e] at h3 + exact h3 + +/-- The gcd is 1 or the prime determinant. -/ +theorem gcd_one_or_prime (n : ℕ) : + Nat.gcd (n + 5) (3 * n + 4) = 1 ∨ Nat.gcd (n + 5) (3 * n + 4) = 11 := by + exact (Nat.dvd_prime (by norm_num)).1 (gcd_dvd_det n) diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/task.toml b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7c2d96b69e653746a56f25aa78f0b8a0a460197b --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "gcd_coprime", "msc-11", "train", "lean4"] +msc = "11" +family = "gcd_coprime" +split = "train" +seed = 34 + +[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/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..016e353fa1faa44243b42e80390d19946940f825 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\n/-- The gcd divides the determinant. -/\ntheorem gcd_dvd_det (n : ℕ) :\n Nat.gcd (n + 5) (3 * n + 4) ∣ 11 := by\n sorry\n\n/-- The gcd is 1 or the prime determinant. -/\ntheorem gcd_one_or_prime (n : ℕ) :\n Nat.gcd (n + 5) (3 * n + 4) = 1 ∨ Nat.gcd (n + 5) (3 * n + 4) = 11 := by\n sorry\n", + "targets": [ + { + "name": "gcd_dvd_det", + "weight": 1.0 + }, + { + "name": "gcd_one_or_prime", + "weight": 2.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0034/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..70e9a9acbdb206b0abc890fac905de38a935e38a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/environment/workdir/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The gcd divides the determinant. -/ +theorem gcd_dvd_det (n : ℕ) : + Nat.gcd (5 * n + 6) (3 * n + 4) ∣ 2 := by + sorry + +/-- The gcd is 1 or the prime determinant. -/ +theorem gcd_one_or_prime (n : ℕ) : + Nat.gcd (5 * n + 6) (3 * n + 4) = 1 ∨ Nat.gcd (5 * n + 6) (3 * n + 4) = 2 := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..475fcb6e88e631974955379cde46f29c98d6522f --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Let \(n\) be a natural number and \(g = \gcd(5n + 6, 3n + 4)\). Prove that \(g\) divides \(2\), and conclude that \(g = 1\) or \(g = 2\). + +## 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/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..07d3ce420a9aeeed13b91875e9eefab7b3418190 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/solution/Solution.lean @@ -0,0 +1,16 @@ +import Mathlib + +/-- The gcd divides the determinant. -/ +theorem gcd_dvd_det (n : ℕ) : + Nat.gcd (5 * n + 6) (3 * n + 4) ∣ 2 := by + have h1 : Nat.gcd (5 * n + 6) (3 * n + 4) ∣ 5 * n + 6 := Nat.gcd_dvd_left _ _ + have h2 : Nat.gcd (5 * n + 6) (3 * n + 4) ∣ 3 * n + 4 := Nat.gcd_dvd_right _ _ + have h3 := Nat.dvd_sub (Dvd.dvd.mul_left h2 5) (Dvd.dvd.mul_left h1 3) + have e : 5 * (3 * n + 4) - 3 * (5 * n + 6) = 2 := by omega + rw [e] at h3 + exact h3 + +/-- The gcd is 1 or the prime determinant. -/ +theorem gcd_one_or_prime (n : ℕ) : + Nat.gcd (5 * n + 6) (3 * n + 4) = 1 ∨ Nat.gcd (5 * n + 6) (3 * n + 4) = 2 := by + exact (Nat.dvd_prime (by norm_num)).1 (gcd_dvd_det n) diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/task.toml b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e709815e71a350f040d34a25ad26373a10444f45 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "gcd_coprime", "msc-11", "train", "lean4"] +msc = "11" +family = "gcd_coprime" +split = "train" +seed = 58 + +[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/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/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/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..49f60c64b15e20c0fdba79ce357b1c166bdc4589 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/tests/spec.json @@ -0,0 +1,13 @@ +{ + "reference": "import Mathlib\n\n/-- The gcd divides the determinant. -/\ntheorem gcd_dvd_det (n : ℕ) :\n Nat.gcd (5 * n + 6) (3 * n + 4) ∣ 2 := by\n sorry\n\n/-- The gcd is 1 or the prime determinant. -/\ntheorem gcd_one_or_prime (n : ℕ) :\n Nat.gcd (5 * n + 6) (3 * n + 4) = 1 ∨ Nat.gcd (5 * n + 6) (3 * n + 4) = 2 := by\n sorry\n", + "targets": [ + { + "name": "gcd_dvd_det", + "weight": 1.0 + }, + { + "name": "gcd_one_or_prime", + "weight": 2.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-gcd_coprime-d3-t0058/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/modular-arithmetic/modular-arithmetic-power_residues-d1-e0015/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-e0015/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-e0015/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-e0015/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-e0015/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..8edc8871b83ffe6c9bca580cef47b5fcdc90171f --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-e0015/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The remainder of the expression is one of the listed values. -/ +theorem residues_of_power (n : ℕ) : + (4 * n ^ 2 + 3) % 5 = 2 ∨ (4 * n ^ 2 + 3) % 5 = 3 ∨ (4 * n ^ 2 + 3) % 5 = 4 := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-e0015/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-e0015/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c25fbfb8deeb78f2a4f821c190d7ef490daa437a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-e0015/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every natural number \(n\), the remainder of \(4n^2 + 3\) on division by \(5\) is one of \(2, 3, 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/modular-arithmetic/modular-arithmetic-power_residues-d1-e0015/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-e0015/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..2cb8b5f34aa4032ce06c4a4a096b1f9502d32094 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-e0015/solution/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The remainder of the expression is one of the listed values. -/ +theorem residues_of_power (n : ℕ) : + (4 * n ^ 2 + 3) % 5 = 2 ∨ (4 * n ^ 2 + 3) % 5 = 3 ∨ (4 * n ^ 2 + 3) % 5 = 4 := by + have key : (4 * n ^ 2 + 3) % 5 = (4 * (n % 5) ^ 2 + 3) % 5 := + ((((Nat.mod_modEq n 5).symm.pow 2)).mul_left 4).add_right 3 + have h := Nat.mod_lt n (show 0 < 5 by norm_num) + rw [key] + generalize n % 5 = r at h ⊢ + interval_cases r <;> decide diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-e0015/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-e0015/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-e0015/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-e0015/task.toml b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-e0015/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8f5ab574bf2327bde6fdcfb862578a9cca8b7d41 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-e0015/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "power_residues", "msc-11", "eval", "lean4"] +msc = "11" +family = "power_residues" +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/modular-arithmetic/modular-arithmetic-power_residues-d1-e0015/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-e0015/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d1-e0015/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-e0015/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d1-e0015/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-e0015/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..473ab630ac97c4f3e131259a3ac14bb1079a8880 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-e0015/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The remainder of the expression is one of the listed values. -/\ntheorem residues_of_power (n : ℕ) :\n (4 * n ^ 2 + 3) % 5 = 2 ∨ (4 * n ^ 2 + 3) % 5 = 3 ∨ (4 * n ^ 2 + 3) % 5 = 4 := by\n sorry\n", + "targets": [ + { + "name": "residues_of_power", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-e0015/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-e0015/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d1-t0015/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0015/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0015/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0015/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0015/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..e8fceb5e95442fe7cbf6f536e4f9d6f0b1d34325 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0015/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The remainder of the expression is one of the listed values. -/ +theorem residues_of_power (n : ℕ) : + (2 * n ^ 2 + 4) % 8 = 4 ∨ (2 * n ^ 2 + 4) % 8 = 6 := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0015/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0015/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cb6a798c650764a1e764eef7908acfcccfc36afd --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0015/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every natural number \(n\), the remainder of \(2n^2 + 4\) on division by \(8\) is one of \(4, 6\). + +## 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/modular-arithmetic/modular-arithmetic-power_residues-d1-t0015/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0015/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..312de6d84d3f307eb33a2de8834c6d3570a20284 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0015/solution/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The remainder of the expression is one of the listed values. -/ +theorem residues_of_power (n : ℕ) : + (2 * n ^ 2 + 4) % 8 = 4 ∨ (2 * n ^ 2 + 4) % 8 = 6 := by + have key : (2 * n ^ 2 + 4) % 8 = (2 * (n % 8) ^ 2 + 4) % 8 := + ((((Nat.mod_modEq n 8).symm.pow 2)).mul_left 2).add_right 4 + have h := Nat.mod_lt n (show 0 < 8 by norm_num) + rw [key] + generalize n % 8 = r at h ⊢ + interval_cases r <;> decide diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0015/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0015/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0015/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0015/task.toml b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0015/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1f54cb0f09bc1c7af691bc51f3ace3b4afef275a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0015/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "power_residues", "msc-11", "train", "lean4"] +msc = "11" +family = "power_residues" +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/modular-arithmetic/modular-arithmetic-power_residues-d1-t0015/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0015/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d1-t0015/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0015/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d1-t0015/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0015/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..acd7cf3b2252d79bcc5f2ea009b4ee0be1bab9ae --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0015/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The remainder of the expression is one of the listed values. -/\ntheorem residues_of_power (n : ℕ) :\n (2 * n ^ 2 + 4) % 8 = 4 ∨ (2 * n ^ 2 + 4) % 8 = 6 := by\n sorry\n", + "targets": [ + { + "name": "residues_of_power", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0015/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0015/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d1-t0039/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0039/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0039/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0039/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0039/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..82091d9be314a5e5a018090b3da19efbf05577bb --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0039/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The remainder of the expression is one of the listed values. -/ +theorem residues_of_power (n : ℕ) : + (3 * n ^ 2 + 2) % 7 = 0 ∨ (3 * n ^ 2 + 2) % 7 = 1 ∨ (3 * n ^ 2 + 2) % 7 = 2 ∨ (3 * n ^ 2 + 2) % 7 = 5 := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0039/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0039/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cea76915aeca74df541e3396ce2c5bb1ef8e6312 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0039/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every natural number \(n\), the remainder of \(3n^2 + 2\) on division by \(7\) is one of \(0, 1, 2, 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/modular-arithmetic/modular-arithmetic-power_residues-d1-t0039/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0039/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..d882d553b86dafa1a266eddd9a0eb6404d9f52e1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0039/solution/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The remainder of the expression is one of the listed values. -/ +theorem residues_of_power (n : ℕ) : + (3 * n ^ 2 + 2) % 7 = 0 ∨ (3 * n ^ 2 + 2) % 7 = 1 ∨ (3 * n ^ 2 + 2) % 7 = 2 ∨ (3 * n ^ 2 + 2) % 7 = 5 := by + have key : (3 * n ^ 2 + 2) % 7 = (3 * (n % 7) ^ 2 + 2) % 7 := + ((((Nat.mod_modEq n 7).symm.pow 2)).mul_left 3).add_right 2 + have h := Nat.mod_lt n (show 0 < 7 by norm_num) + rw [key] + generalize n % 7 = r at h ⊢ + interval_cases r <;> decide diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0039/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0039/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0039/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0039/task.toml b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0039/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f72ad3c27bf4bed3bfb334f37f98a2a19594126c --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0039/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "power_residues", "msc-11", "train", "lean4"] +msc = "11" +family = "power_residues" +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/modular-arithmetic/modular-arithmetic-power_residues-d1-t0039/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0039/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d1-t0039/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0039/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d1-t0039/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0039/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..4db4fa67c0e0acea745ea495d7c546ebcea51933 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0039/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The remainder of the expression is one of the listed values. -/\ntheorem residues_of_power (n : ℕ) :\n (3 * n ^ 2 + 2) % 7 = 0 ∨ (3 * n ^ 2 + 2) % 7 = 1 ∨ (3 * n ^ 2 + 2) % 7 = 2 ∨ (3 * n ^ 2 + 2) % 7 = 5 := by\n sorry\n", + "targets": [ + { + "name": "residues_of_power", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0039/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0039/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d1-t0063/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0063/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0063/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0063/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0063/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..cffb2f8191701e6de7f8899bd5d7e0a652d581df --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0063/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The remainder of the expression is one of the listed values. -/ +theorem residues_of_power (n : ℕ) : + (n ^ 2 + 2) % 9 = 0 ∨ (n ^ 2 + 2) % 9 = 2 ∨ (n ^ 2 + 2) % 9 = 3 ∨ (n ^ 2 + 2) % 9 = 6 := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0063/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0063/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7272d2d93fb6c43ec5cb1a0f50913900bd1ccbc3 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0063/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every natural number \(n\), the remainder of \(n^2 + 2\) on division by \(9\) is one of \(0, 2, 3, 6\). + +## 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/modular-arithmetic/modular-arithmetic-power_residues-d1-t0063/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0063/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..1150925cc0851f66677451b234cd16bdb25b4770 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0063/solution/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The remainder of the expression is one of the listed values. -/ +theorem residues_of_power (n : ℕ) : + (n ^ 2 + 2) % 9 = 0 ∨ (n ^ 2 + 2) % 9 = 2 ∨ (n ^ 2 + 2) % 9 = 3 ∨ (n ^ 2 + 2) % 9 = 6 := by + have key : (n ^ 2 + 2) % 9 = ((n % 9) ^ 2 + 2) % 9 := + (((Nat.mod_modEq n 9).symm.pow 2)).add_right 2 + have h := Nat.mod_lt n (show 0 < 9 by norm_num) + rw [key] + generalize n % 9 = r at h ⊢ + interval_cases r <;> decide diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0063/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0063/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0063/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0063/task.toml b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0063/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9962b9a5ee2abb7744e180f8cc5f3246211374a2 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0063/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "easy" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "power_residues", "msc-11", "train", "lean4"] +msc = "11" +family = "power_residues" +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/modular-arithmetic/modular-arithmetic-power_residues-d1-t0063/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0063/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d1-t0063/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0063/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d1-t0063/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0063/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..ba23d3ed6efb744ba28a9b0992e41cd078c6bc04 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0063/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The remainder of the expression is one of the listed values. -/\ntheorem residues_of_power (n : ℕ) :\n (n ^ 2 + 2) % 9 = 0 ∨ (n ^ 2 + 2) % 9 = 2 ∨ (n ^ 2 + 2) % 9 = 3 ∨ (n ^ 2 + 2) % 9 = 6 := by\n sorry\n", + "targets": [ + { + "name": "residues_of_power", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0063/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d1-t0063/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d2-e0007/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-e0007/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-e0007/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-e0007/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-e0007/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..86a269568723b67ca115c8e991e7cc9167d9f10a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-e0007/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The remainder of the expression is one of the listed values. -/ +theorem residues_of_power (n : ℕ) : + (4 * n ^ 3 + 4) % 9 = 0 ∨ (4 * n ^ 3 + 4) % 9 = 4 ∨ (4 * n ^ 3 + 4) % 9 = 8 := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-e0007/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-e0007/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4455377708955e372d1e004e0c9edf9fb122e781 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-e0007/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every natural number \(n\), the remainder of \(4n^3 + 4\) on division by \(9\) is one of \(0, 4, 8\). + +## 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/modular-arithmetic/modular-arithmetic-power_residues-d2-e0007/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-e0007/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..95fe2d93bbf2a83c98f33a512ee2724414819a3b --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-e0007/solution/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The remainder of the expression is one of the listed values. -/ +theorem residues_of_power (n : ℕ) : + (4 * n ^ 3 + 4) % 9 = 0 ∨ (4 * n ^ 3 + 4) % 9 = 4 ∨ (4 * n ^ 3 + 4) % 9 = 8 := by + have key : (4 * n ^ 3 + 4) % 9 = (4 * (n % 9) ^ 3 + 4) % 9 := + ((((Nat.mod_modEq n 9).symm.pow 3)).mul_left 4).add_right 4 + have h := Nat.mod_lt n (show 0 < 9 by norm_num) + rw [key] + generalize n % 9 = r at h ⊢ + interval_cases r <;> decide diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-e0007/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-e0007/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-e0007/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-e0007/task.toml b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-e0007/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f6fc248a0a5d8fa2f2f7b2ffe27bb1accb7ece41 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-e0007/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "power_residues", "msc-11", "eval", "lean4"] +msc = "11" +family = "power_residues" +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/modular-arithmetic/modular-arithmetic-power_residues-d2-e0007/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-e0007/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d2-e0007/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-e0007/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d2-e0007/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-e0007/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..4c4baa006ae4de0d871e09ea532f798464fbd4ea --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-e0007/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The remainder of the expression is one of the listed values. -/\ntheorem residues_of_power (n : ℕ) :\n (4 * n ^ 3 + 4) % 9 = 0 ∨ (4 * n ^ 3 + 4) % 9 = 4 ∨ (4 * n ^ 3 + 4) % 9 = 8 := by\n sorry\n", + "targets": [ + { + "name": "residues_of_power", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-e0007/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-e0007/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d2-t0007/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0007/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0007/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0007/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0007/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..8f3082b5d894b37923f06e11e6c576d319e100e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0007/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The remainder of the expression is one of the listed values. -/ +theorem residues_of_power (n : ℕ) : + (7 * n ^ 3 + 7) % 13 = 0 ∨ (7 * n ^ 3 + 7) % 13 = 1 ∨ (7 * n ^ 3 + 7) % 13 = 3 ∨ (7 * n ^ 3 + 7) % 13 = 7 ∨ (7 * n ^ 3 + 7) % 13 = 11 := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0007/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0007/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ad1d5809db647f77bf08c46cfd57d490ec527255 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0007/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every natural number \(n\), the remainder of \(7n^3 + 7\) on division by \(13\) is one of \(0, 1, 3, 7, 11\). + +## 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/modular-arithmetic/modular-arithmetic-power_residues-d2-t0007/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0007/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..78f048da350fbcc8956a24f7f9280ba5693399c3 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0007/solution/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The remainder of the expression is one of the listed values. -/ +theorem residues_of_power (n : ℕ) : + (7 * n ^ 3 + 7) % 13 = 0 ∨ (7 * n ^ 3 + 7) % 13 = 1 ∨ (7 * n ^ 3 + 7) % 13 = 3 ∨ (7 * n ^ 3 + 7) % 13 = 7 ∨ (7 * n ^ 3 + 7) % 13 = 11 := by + have key : (7 * n ^ 3 + 7) % 13 = (7 * (n % 13) ^ 3 + 7) % 13 := + ((((Nat.mod_modEq n 13).symm.pow 3)).mul_left 7).add_right 7 + have h := Nat.mod_lt n (show 0 < 13 by norm_num) + rw [key] + generalize n % 13 = r at h ⊢ + interval_cases r <;> decide diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0007/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0007/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0007/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0007/task.toml b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0007/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..519553afe2381fd4b05c283f83bc7dbc8e594401 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0007/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "power_residues", "msc-11", "train", "lean4"] +msc = "11" +family = "power_residues" +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/modular-arithmetic/modular-arithmetic-power_residues-d2-t0007/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0007/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d2-t0007/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0007/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d2-t0007/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0007/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..abbdc7ef4212e7f6a888f85cc71f6e20f20f93aa --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0007/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The remainder of the expression is one of the listed values. -/\ntheorem residues_of_power (n : ℕ) :\n (7 * n ^ 3 + 7) % 13 = 0 ∨ (7 * n ^ 3 + 7) % 13 = 1 ∨ (7 * n ^ 3 + 7) % 13 = 3 ∨ (7 * n ^ 3 + 7) % 13 = 7 ∨ (7 * n ^ 3 + 7) % 13 = 11 := by\n sorry\n", + "targets": [ + { + "name": "residues_of_power", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0007/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0007/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d2-t0031/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0031/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0031/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0031/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0031/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..0b2b72bc04d1ab4f10de97c698d639968ae58fe6 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0031/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The remainder of the expression is one of the listed values. -/ +theorem residues_of_power (n : ℕ) : + (4 * n ^ 4 + 8) % 9 = 0 ∨ (4 * n ^ 4 + 8) % 9 = 3 ∨ (4 * n ^ 4 + 8) % 9 = 6 ∨ (4 * n ^ 4 + 8) % 9 = 8 := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0031/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0031/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0418207a411dce8318e51db970ad82b5f34c1fbc --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0031/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every natural number \(n\), the remainder of \(4n^4 + 8\) on division by \(9\) is one of \(0, 3, 6, 8\). + +## 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/modular-arithmetic/modular-arithmetic-power_residues-d2-t0031/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0031/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..f94e620180096b712d0bc09f1bbcd23dcbfb6fc4 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0031/solution/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The remainder of the expression is one of the listed values. -/ +theorem residues_of_power (n : ℕ) : + (4 * n ^ 4 + 8) % 9 = 0 ∨ (4 * n ^ 4 + 8) % 9 = 3 ∨ (4 * n ^ 4 + 8) % 9 = 6 ∨ (4 * n ^ 4 + 8) % 9 = 8 := by + have key : (4 * n ^ 4 + 8) % 9 = (4 * (n % 9) ^ 4 + 8) % 9 := + ((((Nat.mod_modEq n 9).symm.pow 4)).mul_left 4).add_right 8 + have h := Nat.mod_lt n (show 0 < 9 by norm_num) + rw [key] + generalize n % 9 = r at h ⊢ + interval_cases r <;> decide diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0031/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0031/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0031/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0031/task.toml b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0031/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1dd6ed1c17896200b8e20c20754942543ebed662 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0031/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "power_residues", "msc-11", "train", "lean4"] +msc = "11" +family = "power_residues" +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/modular-arithmetic/modular-arithmetic-power_residues-d2-t0031/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0031/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d2-t0031/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0031/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d2-t0031/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0031/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..6b472ae039bef49ed3eb4fed0ae42ee83c14ad56 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0031/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The remainder of the expression is one of the listed values. -/\ntheorem residues_of_power (n : ℕ) :\n (4 * n ^ 4 + 8) % 9 = 0 ∨ (4 * n ^ 4 + 8) % 9 = 3 ∨ (4 * n ^ 4 + 8) % 9 = 6 ∨ (4 * n ^ 4 + 8) % 9 = 8 := by\n sorry\n", + "targets": [ + { + "name": "residues_of_power", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0031/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0031/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d2-t0055/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0055/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0055/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0055/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0055/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..428c8a666c5bdf76983a90b1a8f5f67ecc8762cd --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0055/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The remainder of the expression is one of the listed values. -/ +theorem residues_of_power (n : ℕ) : + (7 * n ^ 4 + 3) % 11 = 0 ∨ (7 * n ^ 4 + 3) % 11 = 2 ∨ (7 * n ^ 4 + 3) % 11 = 3 ∨ (7 * n ^ 4 + 3) % 11 = 5 ∨ (7 * n ^ 4 + 3) % 11 = 9 ∨ (7 * n ^ 4 + 3) % 11 = 10 := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0055/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0055/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f6613119083ca842725adae2d01ecb23fc4d5c11 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0055/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every natural number \(n\), the remainder of \(7n^4 + 3\) on division by \(11\) is one of \(0, 2, 3, 5, 9, 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/modular-arithmetic/modular-arithmetic-power_residues-d2-t0055/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0055/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..f2040b12846e05e000f5d8b10c1e556703a2714f --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0055/solution/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The remainder of the expression is one of the listed values. -/ +theorem residues_of_power (n : ℕ) : + (7 * n ^ 4 + 3) % 11 = 0 ∨ (7 * n ^ 4 + 3) % 11 = 2 ∨ (7 * n ^ 4 + 3) % 11 = 3 ∨ (7 * n ^ 4 + 3) % 11 = 5 ∨ (7 * n ^ 4 + 3) % 11 = 9 ∨ (7 * n ^ 4 + 3) % 11 = 10 := by + have key : (7 * n ^ 4 + 3) % 11 = (7 * (n % 11) ^ 4 + 3) % 11 := + ((((Nat.mod_modEq n 11).symm.pow 4)).mul_left 7).add_right 3 + have h := Nat.mod_lt n (show 0 < 11 by norm_num) + rw [key] + generalize n % 11 = r at h ⊢ + interval_cases r <;> decide diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0055/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0055/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0055/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0055/task.toml b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0055/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7ebf894607ec124ea73c87cc5aa4ae31ddb9b296 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0055/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "power_residues", "msc-11", "train", "lean4"] +msc = "11" +family = "power_residues" +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/modular-arithmetic/modular-arithmetic-power_residues-d2-t0055/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0055/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d2-t0055/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0055/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d2-t0055/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0055/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..3502dcb6c9ebed375f181e7427c91daebc026bde --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0055/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The remainder of the expression is one of the listed values. -/\ntheorem residues_of_power (n : ℕ) :\n (7 * n ^ 4 + 3) % 11 = 0 ∨ (7 * n ^ 4 + 3) % 11 = 2 ∨ (7 * n ^ 4 + 3) % 11 = 3 ∨ (7 * n ^ 4 + 3) % 11 = 5 ∨ (7 * n ^ 4 + 3) % 11 = 9 ∨ (7 * n ^ 4 + 3) % 11 = 10 := by\n sorry\n", + "targets": [ + { + "name": "residues_of_power", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0055/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0055/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d2-t0079/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0079/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0079/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0079/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0079/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..d9f7013b3235f4c8cee3dee50f4a23021bf473ca --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0079/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The remainder of the expression is one of the listed values. -/ +theorem residues_of_power (n : ℕ) : + (9 * n ^ 4 + 5) % 11 = 3 ∨ (9 * n ^ 4 + 5) % 11 = 5 ∨ (9 * n ^ 4 + 5) % 11 = 6 ∨ (9 * n ^ 4 + 5) % 11 = 8 ∨ (9 * n ^ 4 + 5) % 11 = 9 ∨ (9 * n ^ 4 + 5) % 11 = 10 := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0079/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0079/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9d97be8e09f5ba8cfcec0cc1f3ddef54338b2918 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0079/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for every natural number \(n\), the remainder of \(9n^4 + 5\) on division by \(11\) is one of \(3, 5, 6, 8, 9, 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/modular-arithmetic/modular-arithmetic-power_residues-d2-t0079/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0079/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..0f4ba9184a42cf4501988e126857bea973a2bf35 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0079/solution/Solution.lean @@ -0,0 +1,11 @@ +import Mathlib + +/-- The remainder of the expression is one of the listed values. -/ +theorem residues_of_power (n : ℕ) : + (9 * n ^ 4 + 5) % 11 = 3 ∨ (9 * n ^ 4 + 5) % 11 = 5 ∨ (9 * n ^ 4 + 5) % 11 = 6 ∨ (9 * n ^ 4 + 5) % 11 = 8 ∨ (9 * n ^ 4 + 5) % 11 = 9 ∨ (9 * n ^ 4 + 5) % 11 = 10 := by + have key : (9 * n ^ 4 + 5) % 11 = (9 * (n % 11) ^ 4 + 5) % 11 := + ((((Nat.mod_modEq n 11).symm.pow 4)).mul_left 9).add_right 5 + have h := Nat.mod_lt n (show 0 < 11 by norm_num) + rw [key] + generalize n % 11 = r at h ⊢ + interval_cases r <;> decide diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0079/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0079/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0079/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0079/task.toml b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0079/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ec6fa6fd621c463cbea600e1a20a0ac5c69e7814 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0079/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "medium" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "power_residues", "msc-11", "train", "lean4"] +msc = "11" +family = "power_residues" +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/modular-arithmetic/modular-arithmetic-power_residues-d2-t0079/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0079/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d2-t0079/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0079/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d2-t0079/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0079/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..0dc33b00237f0c6649b042954f722a47eca2d674 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0079/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The remainder of the expression is one of the listed values. -/\ntheorem residues_of_power (n : ℕ) :\n (9 * n ^ 4 + 5) % 11 = 3 ∨ (9 * n ^ 4 + 5) % 11 = 5 ∨ (9 * n ^ 4 + 5) % 11 = 6 ∨ (9 * n ^ 4 + 5) % 11 = 8 ∨ (9 * n ^ 4 + 5) % 11 = 9 ∨ (9 * n ^ 4 + 5) % 11 = 10 := by\n sorry\n", + "targets": [ + { + "name": "residues_of_power", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0079/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d2-t0079/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d3-e0023/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-e0023/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-e0023/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-e0023/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-e0023/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..48e2ee27117c3001a2aab71669b789c29fa94e48 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-e0023/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The expression never leaves the stated remainder. -/ +theorem residue_never_attained (a b : ℕ) : + (a ^ 2 + 3 * b ^ 2 + 1) % 8 ≠ 7 := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-e0023/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-e0023/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..94c4d01fe6fffcdc999457c7ee169c72c90cd8ae --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-e0023/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for all natural numbers \(a\) and \(b\), the number \(a^2 + 3b^2 + 1\) never leaves remainder \(7\) on division by \(8\). + +## 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/modular-arithmetic/modular-arithmetic-power_residues-d3-e0023/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-e0023/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..1d5629e94a5f1b0add86d3945bb4d3e4ee848d64 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-e0023/solution/Solution.lean @@ -0,0 +1,13 @@ +import Mathlib + +/-- The expression never leaves the stated remainder. -/ +theorem residue_never_attained (a b : ℕ) : + (a ^ 2 + 3 * b ^ 2 + 1) % 8 ≠ 7 := by + have key : (a ^ 2 + 3 * b ^ 2 + 1) % 8 = ((a % 8) ^ 2 + 3 * (b % 8) ^ 2 + 1) % 8 := + ((((Nat.mod_modEq a 8).symm.pow 2)).add ((((Nat.mod_modEq b 8).symm.pow 2)).mul_left 3)).add_right 1 + have ha := Nat.mod_lt a (show 0 < 8 by norm_num) + have hb := Nat.mod_lt b (show 0 < 8 by norm_num) + rw [key] + generalize a % 8 = x at ha ⊢ + generalize b % 8 = y at hb ⊢ + interval_cases x <;> interval_cases y <;> decide diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-e0023/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-e0023/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-e0023/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-e0023/task.toml b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-e0023/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8492854896b8becf56f3a763864e467c1fdb68d6 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-e0023/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "power_residues", "msc-11", "eval", "lean4"] +msc = "11" +family = "power_residues" +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/modular-arithmetic/modular-arithmetic-power_residues-d3-e0023/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-e0023/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d3-e0023/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-e0023/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d3-e0023/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-e0023/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..29f497dccb5451b545207d073fc6ff524e9d2152 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-e0023/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The expression never leaves the stated remainder. -/\ntheorem residue_never_attained (a b : ℕ) :\n (a ^ 2 + 3 * b ^ 2 + 1) % 8 ≠ 7 := by\n sorry\n", + "targets": [ + { + "name": "residue_never_attained", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-e0023/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-e0023/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d3-t0023/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0023/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0023/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0023/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0023/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..88a4baad77f45e2c9fe228ed5d71766ca1f6e04b --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0023/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The expression never leaves the stated remainder. -/ +theorem residue_never_attained (a b : ℕ) : + (3 * a ^ 2 + b ^ 2 + 2) % 8 ≠ 0 := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0023/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0023/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..35a869046c7a8c8f4c7011ac95f7df38443d6064 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0023/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for all natural numbers \(a\) and \(b\), the number \(3a^2 + b^2 + 2\) never leaves remainder \(0\) on division by \(8\). + +## 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/modular-arithmetic/modular-arithmetic-power_residues-d3-t0023/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0023/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..071c3c820467f908c37b6574e700f1455efa44eb --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0023/solution/Solution.lean @@ -0,0 +1,13 @@ +import Mathlib + +/-- The expression never leaves the stated remainder. -/ +theorem residue_never_attained (a b : ℕ) : + (3 * a ^ 2 + b ^ 2 + 2) % 8 ≠ 0 := by + have key : (3 * a ^ 2 + b ^ 2 + 2) % 8 = (3 * (a % 8) ^ 2 + (b % 8) ^ 2 + 2) % 8 := + (((((Nat.mod_modEq a 8).symm.pow 2)).mul_left 3).add (((Nat.mod_modEq b 8).symm.pow 2))).add_right 2 + have ha := Nat.mod_lt a (show 0 < 8 by norm_num) + have hb := Nat.mod_lt b (show 0 < 8 by norm_num) + rw [key] + generalize a % 8 = x at ha ⊢ + generalize b % 8 = y at hb ⊢ + interval_cases x <;> interval_cases y <;> decide diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0023/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0023/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0023/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0023/task.toml b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0023/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..85056c8dadc43c7fc45a628b5416dfc1f144a115 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0023/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "power_residues", "msc-11", "train", "lean4"] +msc = "11" +family = "power_residues" +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/modular-arithmetic/modular-arithmetic-power_residues-d3-t0023/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0023/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d3-t0023/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0023/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d3-t0023/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0023/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..8c8e13440e098587c806331a34fde172936ff4ae --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0023/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The expression never leaves the stated remainder. -/\ntheorem residue_never_attained (a b : ℕ) :\n (3 * a ^ 2 + b ^ 2 + 2) % 8 ≠ 0 := by\n sorry\n", + "targets": [ + { + "name": "residue_never_attained", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0023/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0023/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d3-t0047/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0047/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0047/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0047/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0047/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..ce61662ed5462049214d3b4a850d7f606ac88ea0 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0047/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The expression never leaves the stated remainder. -/ +theorem residue_never_attained (a b : ℕ) : + (a ^ 2 + 3 * b ^ 2 + 3) % 4 ≠ 1 := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0047/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0047/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8d70386130d87e8be9ddd048fb0fcf7522db5ae6 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0047/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for all natural numbers \(a\) and \(b\), the number \(a^2 + 3b^2 + 3\) never leaves remainder \(1\) on division by \(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/modular-arithmetic/modular-arithmetic-power_residues-d3-t0047/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0047/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..c4fc01ef85f13c9308d824730b51e16c47a23087 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0047/solution/Solution.lean @@ -0,0 +1,13 @@ +import Mathlib + +/-- The expression never leaves the stated remainder. -/ +theorem residue_never_attained (a b : ℕ) : + (a ^ 2 + 3 * b ^ 2 + 3) % 4 ≠ 1 := by + have key : (a ^ 2 + 3 * b ^ 2 + 3) % 4 = ((a % 4) ^ 2 + 3 * (b % 4) ^ 2 + 3) % 4 := + ((((Nat.mod_modEq a 4).symm.pow 2)).add ((((Nat.mod_modEq b 4).symm.pow 2)).mul_left 3)).add_right 3 + have ha := Nat.mod_lt a (show 0 < 4 by norm_num) + have hb := Nat.mod_lt b (show 0 < 4 by norm_num) + rw [key] + generalize a % 4 = x at ha ⊢ + generalize b % 4 = y at hb ⊢ + interval_cases x <;> interval_cases y <;> decide diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0047/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0047/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0047/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0047/task.toml b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0047/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bd5a6e2c1992efa7bdae3e6da51a4872950473aa --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0047/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "power_residues", "msc-11", "train", "lean4"] +msc = "11" +family = "power_residues" +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/modular-arithmetic/modular-arithmetic-power_residues-d3-t0047/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0047/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d3-t0047/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0047/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d3-t0047/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0047/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..8b47e1bdac54e39e85b109c73f4138c529258895 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0047/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The expression never leaves the stated remainder. -/\ntheorem residue_never_attained (a b : ℕ) :\n (a ^ 2 + 3 * b ^ 2 + 3) % 4 ≠ 1 := by\n sorry\n", + "targets": [ + { + "name": "residue_never_attained", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0047/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0047/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d3-t0071/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0071/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0071/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0071/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0071/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..1a917eacc461359d0f553ba01af1e95b7827a9fc --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0071/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The expression never leaves the stated remainder. -/ +theorem residue_never_attained (a b : ℕ) : + (3 * a ^ 2 + 2 * b ^ 2 + 5) % 9 ≠ 0 := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0071/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0071/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..16782a66d135cb882daaf2e62728c838baa984dc --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0071/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for all natural numbers \(a\) and \(b\), the number \(3a^2 + 2b^2 + 5\) never leaves remainder \(0\) on division by \(9\). + +## 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/modular-arithmetic/modular-arithmetic-power_residues-d3-t0071/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0071/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..86066700aa8fa6934d448973a45c38add98bd10e --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0071/solution/Solution.lean @@ -0,0 +1,13 @@ +import Mathlib + +/-- The expression never leaves the stated remainder. -/ +theorem residue_never_attained (a b : ℕ) : + (3 * a ^ 2 + 2 * b ^ 2 + 5) % 9 ≠ 0 := by + have key : (3 * a ^ 2 + 2 * b ^ 2 + 5) % 9 = (3 * (a % 9) ^ 2 + 2 * (b % 9) ^ 2 + 5) % 9 := + (((((Nat.mod_modEq a 9).symm.pow 2)).mul_left 3).add ((((Nat.mod_modEq b 9).symm.pow 2)).mul_left 2)).add_right 5 + have ha := Nat.mod_lt a (show 0 < 9 by norm_num) + have hb := Nat.mod_lt b (show 0 < 9 by norm_num) + rw [key] + generalize a % 9 = x at ha ⊢ + generalize b % 9 = y at hb ⊢ + interval_cases x <;> interval_cases y <;> decide diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0071/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0071/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0071/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0071/task.toml b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0071/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..85b079b9cff4c6ef143cd7a780f23475d05e9c94 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0071/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "power_residues", "msc-11", "train", "lean4"] +msc = "11" +family = "power_residues" +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/modular-arithmetic/modular-arithmetic-power_residues-d3-t0071/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0071/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d3-t0071/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0071/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d3-t0071/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0071/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..44424d60dd3171220b043298bcf17ee0bc75fbb5 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0071/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The expression never leaves the stated remainder. -/\ntheorem residue_never_attained (a b : ℕ) :\n (3 * a ^ 2 + 2 * b ^ 2 + 5) % 9 ≠ 0 := by\n sorry\n", + "targets": [ + { + "name": "residue_never_attained", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0071/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0071/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d3-t0083/environment/Dockerfile b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0083/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d205e4e509e27565b0b394ac0caf379bc83524a1 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0083/environment/Dockerfile @@ -0,0 +1,3 @@ +FROM lean-arena +WORKDIR /app +COPY workdir/ /app/ diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0083/environment/workdir/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0083/environment/workdir/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..b461e63d8ce0304d51d3e78c80ef7d4136f6ff15 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0083/environment/workdir/Solution.lean @@ -0,0 +1,6 @@ +import Mathlib + +/-- The expression never leaves the stated remainder. -/ +theorem residue_never_attained (a b : ℕ) : + (2 * a ^ 2 + 2 * b ^ 2 + 2) % 9 ≠ 5 := by + sorry diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0083/instruction.md b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0083/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..33948433174f0fb49fa6b492d9793af4f130aad2 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0083/instruction.md @@ -0,0 +1,12 @@ +# Prove a fact about divisibility and residues + +Prove that for all natural numbers \(a\) and \(b\), the number \(2a^2 + 2b^2 + 2\) never leaves remainder \(5\) on division by \(9\). + +## 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/modular-arithmetic/modular-arithmetic-power_residues-d3-t0083/solution/Solution.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0083/solution/Solution.lean new file mode 100644 index 0000000000000000000000000000000000000000..588a7a9f2c6bf1ac4324ce9828c66bf5b5437830 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0083/solution/Solution.lean @@ -0,0 +1,13 @@ +import Mathlib + +/-- The expression never leaves the stated remainder. -/ +theorem residue_never_attained (a b : ℕ) : + (2 * a ^ 2 + 2 * b ^ 2 + 2) % 9 ≠ 5 := by + have key : (2 * a ^ 2 + 2 * b ^ 2 + 2) % 9 = (2 * (a % 9) ^ 2 + 2 * (b % 9) ^ 2 + 2) % 9 := + (((((Nat.mod_modEq a 9).symm.pow 2)).mul_left 2).add ((((Nat.mod_modEq b 9).symm.pow 2)).mul_left 2)).add_right 2 + have ha := Nat.mod_lt a (show 0 < 9 by norm_num) + have hb := Nat.mod_lt b (show 0 < 9 by norm_num) + rw [key] + generalize a % 9 = x at ha ⊢ + generalize b % 9 = y at hb ⊢ + interval_cases x <;> interval_cases y <;> decide diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0083/solution/solve.sh b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0083/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b3f52d5f1892ce8e7279a2afa35d39094f971237 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0083/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -e +cp /solution/Solution.lean /app/Solution.lean diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0083/task.toml b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0083/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1c7f445e75054aa97cfe4917a343e5704b8c65e6 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0083/task.toml @@ -0,0 +1,25 @@ +version = "1.0" + +[metadata] +author_name = "Renaissance Labs" +author_email = "unknown" +difficulty = "hard" +category = "modular-arithmetic" +tags = ["modular-arithmetic", "power_residues", "msc-11", "train", "lean4"] +msc = "11" +family = "power_residues" +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/modular-arithmetic/modular-arithmetic-power_residues-d3-t0083/tests/Verify.lean b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0083/tests/Verify.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fa146726ab53f1507be3681f82bab84fc1097e7 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d3-t0083/tests/grade.py b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0083/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab05ea58ae77e2559c3044dd77c7be559206b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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/modular-arithmetic/modular-arithmetic-power_residues-d3-t0083/tests/spec.json b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0083/tests/spec.json new file mode 100644 index 0000000000000000000000000000000000000000..8aab5ef892f1fed1aa7d1620ebfe1b9bda7905b9 --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0083/tests/spec.json @@ -0,0 +1,9 @@ +{ + "reference": "import Mathlib\n\n/-- The expression never leaves the stated remainder. -/\ntheorem residue_never_attained (a b : ℕ) :\n (2 * a ^ 2 + 2 * b ^ 2 + 2) % 9 ≠ 5 := by\n sorry\n", + "targets": [ + { + "name": "residue_never_attained", + "weight": 1.0 + } + ] +} diff --git a/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0083/tests/test.sh b/tasks/modular-arithmetic/modular-arithmetic-power_residues-d3-t0083/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b366909050f1dd7ef36e114efc8ef6e55c11834a --- /dev/null +++ b/tasks/modular-arithmetic/modular-arithmetic-power_residues-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