birgermoell commited on
Commit
d3791e3
·
verified ·
1 Parent(s): eec79f6

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/environment/Dockerfile +3 -0
  2. tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/environment/workdir/Solution.lean +5 -0
  3. tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/instruction.md +14 -0
  4. tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/solution/Solution.lean +6 -0
  5. tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/solution/solve.sh +3 -0
  6. tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/task.toml +25 -0
  7. tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/tests/Verify.lean +135 -0
  8. tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/tests/grade.py +127 -0
  9. tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/tests/spec.json +9 -0
  10. tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/tests/test.sh +3 -0
  11. tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/environment/Dockerfile +3 -0
  12. tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/environment/workdir/Solution.lean +5 -0
  13. tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/instruction.md +14 -0
  14. tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/solution/Solution.lean +6 -0
  15. tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/solution/solve.sh +3 -0
  16. tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/task.toml +25 -0
  17. tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/tests/Verify.lean +135 -0
  18. tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/tests/grade.py +127 -0
  19. tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/tests/spec.json +9 -0
  20. tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/tests/test.sh +3 -0
  21. tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/environment/Dockerfile +3 -0
  22. tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/environment/workdir/Solution.lean +5 -0
  23. tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/instruction.md +14 -0
  24. tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/solution/Solution.lean +6 -0
  25. tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/solution/solve.sh +3 -0
  26. tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/task.toml +25 -0
  27. tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/tests/Verify.lean +135 -0
  28. tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/tests/grade.py +127 -0
  29. tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/tests/spec.json +9 -0
  30. tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/tests/test.sh +3 -0
  31. tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/environment/Dockerfile +3 -0
  32. tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/environment/workdir/Solution.lean +6 -0
  33. tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/instruction.md +14 -0
  34. tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/solution/Solution.lean +8 -0
  35. tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/solution/solve.sh +3 -0
  36. tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/task.toml +25 -0
  37. tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/tests/Verify.lean +135 -0
  38. tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/tests/grade.py +127 -0
  39. tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/tests/spec.json +9 -0
  40. tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/tests/test.sh +3 -0
  41. tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/environment/Dockerfile +3 -0
  42. tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/environment/workdir/Solution.lean +5 -0
  43. tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/instruction.md +14 -0
  44. tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/solution/Solution.lean +6 -0
  45. tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/solution/solve.sh +3 -0
  46. tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/task.toml +25 -0
  47. tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/tests/Verify.lean +135 -0
  48. tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/tests/grade.py +127 -0
  49. tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/tests/spec.json +9 -0
  50. tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/tests/test.sh +3 -0
tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/environment/Dockerfile ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ FROM lean-arena
2
+ WORKDIR /app
3
+ COPY workdir/ /app/
tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/environment/workdir/Solution.lean ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ import Mathlib
2
+
3
+ /-- The determinant of the product is the product of the determinants. -/
4
+ theorem det_of_product : Matrix.det (!![4, 1; 1, -3] * !![3, 1; 1, 1] : Matrix (Fin 2) (Fin 2) ℤ) = (-26 : ℤ) := by
5
+ sorry
tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/instruction.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Determinant and trace of 2x2 matrices
2
+
3
+ Prove the following statement.
4
+
5
+ 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.
6
+
7
+ ## What to do
8
+
9
+ `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.
10
+
11
+ - Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions.
12
+ - 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.
13
+ - A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`.
14
+ - The reward is 1 if the theorem is proved and 0 otherwise.
tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/solution/Solution.lean ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ import Mathlib
2
+
3
+ /-- The determinant of the product is the product of the determinants. -/
4
+ theorem det_of_product : Matrix.det (!![4, 1; 1, -3] * !![3, 1; 1, 1] : Matrix (Fin 2) (Fin 2) ℤ) = (-26 : ℤ) := by
5
+ rw [Matrix.det_mul, Matrix.det_fin_two_of, Matrix.det_fin_two_of]
6
+ norm_num
tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/solution/solve.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ set -e
3
+ cp /solution/Solution.lean /app/Solution.lean
tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/task.toml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [metadata]
4
+ author_name = "Renaissance Labs"
5
+ author_email = "unknown"
6
+ difficulty = "easy"
7
+ category = "linear-algebra"
8
+ tags = ["linear-algebra", "det_trace", "msc-15", "eval", "lean4"]
9
+ msc = "15"
10
+ family = "det_trace"
11
+ split = "eval"
12
+ seed = 10000
13
+
14
+ [verifier]
15
+ timeout_sec = 900.0
16
+
17
+ [agent]
18
+ timeout_sec = 1800.0
19
+
20
+ [environment]
21
+ build_timeout_sec = 1800.0
22
+ cpus = 2
23
+ memory_mb = 6144
24
+ storage_mb = 10240
25
+ allow_internet = false
tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/tests/Verify.lean ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /-
2
+ Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for.
3
+
4
+ lean --run Verify.lean [--free a,b] [--native] <ReferenceModule> <SubmissionModule> <target>...
5
+
6
+ `--free a,b` names definitions the task asks the solver to write: their type must match the
7
+ reference, their value is the solver's own. `--native` additionally accepts the axioms that
8
+ `native_decide` introduces; it is used only for hidden test theorems the grader itself proves.
9
+
10
+ Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only
11
+ `Lean`, never the submission, so nothing the submission declares (notation, macros, instances)
12
+ can change how the check itself is read. It reads the reference module's constants from its .olean, imports the
13
+ submission as an environment, and compares kernel terms:
14
+
15
+ 1. every non-target constant the reference module declares (the task's own definitions) must be
16
+ present in the submission with the same kind, type and value;
17
+ 2. every target must be present with exactly the reference type;
18
+ 3. the proof of every target may depend only on the three standard axioms.
19
+
20
+ It prints one JSON object per target and exits 0. The caller turns that into a reward.
21
+ -/
22
+ import Lean
23
+ open Lean
24
+
25
+ def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound]
26
+
27
+ /-- All axioms a constant depends on, found by walking every constant it mentions. -/
28
+ partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do
29
+ let mut seen : NameSet := {}
30
+ let mut todo : Array Name := #[root]
31
+ let mut out : Array Name := #[]
32
+ while h : todo.size > 0 do
33
+ let c := todo[todo.size - 1]
34
+ todo := todo.pop
35
+ if seen.contains c then continue
36
+ seen := seen.insert c
37
+ match env.find? c with
38
+ | none => out := out.push (`missing ++ c)
39
+ | some info =>
40
+ let mut es : Array Expr := #[info.type]
41
+ match info with
42
+ | .axiomInfo _ => out := out.push c
43
+ | .defnInfo v => es := es.push v.value
44
+ | .thmInfo v => es := es.push v.value
45
+ | .opaqueInfo v => es := es.push v.value
46
+ | .ctorInfo v => todo := todo.push v.induct
47
+ | .inductInfo v => for k in v.ctors do todo := todo.push k
48
+ | .recInfo v => for r in v.rules do es := es.push r.rhs
49
+ | .quotInfo _ => pure ()
50
+ for e in es do
51
+ for k in e.getUsedConstants do
52
+ if !seen.contains k then todo := todo.push k
53
+ return out
54
+
55
+ def kindOf : ConstantInfo → String
56
+ | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem"
57
+ | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive"
58
+ | .ctorInfo _ => "constructor" | .recInfo _ => "recursor"
59
+
60
+ def valueOf : ConstantInfo → Option Expr
61
+ | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value
62
+ | _ => none
63
+
64
+ def sameDecl (a b : ConstantInfo) : Bool :=
65
+ kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b
66
+
67
+ def jstr (s : String) : String := (Json.str s).compress
68
+
69
+ def isNativeAxiom (n : Name) : Bool :=
70
+ n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler ||
71
+ n.components.any (fun c => c == `native_decide)
72
+
73
+ def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c)
74
+
75
+ partial def parseFlags (args : List String) (free : List Name) (native : Bool) :
76
+ List Name × Bool × List String :=
77
+ match args with
78
+ | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native
79
+ | "--native" :: rest => parseFlags rest free true
80
+ | rest => (free, native, rest)
81
+
82
+ def main (args : List String) : IO UInt32 := do
83
+ let (free, native, args) := parseFlags args [] false
84
+ match args with
85
+ | refMod :: solMod :: targets =>
86
+ initSearchPath (← findSysroot)
87
+ let refName := refMod.toName
88
+ let solName := solMod.toName
89
+ let targetNames := targets.map String.toName
90
+ -- The reference is read straight from its .olean: that file holds exactly the constants the
91
+ -- reference module declares, which is all the comparison needs. Only the submission is imported
92
+ -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two.
93
+ let (refData, _) ← readModuleData (← findOLean refName)
94
+ let mut refMap : Std.HashMap Name ConstantInfo := {}
95
+ for i in [0:refData.constNames.size] do
96
+ refMap := refMap.insert refData.constNames[i]! refData.constants[i]!
97
+ let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0)
98
+ -- 1. the task's own definitions are unchanged
99
+ let mut tampered : Array Name := #[]
100
+ for c in refData.constNames do
101
+ if targetNames.contains c then continue
102
+ let some r := refMap[c]? | continue
103
+ if free.contains c then
104
+ match solEnv.find? c with
105
+ | some s =>
106
+ if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c
107
+ | none => tampered := tampered.push c
108
+ continue
109
+ if isUnder free c then continue
110
+ match solEnv.find? c with
111
+ | some s => if !sameDecl r s then tampered := tampered.push c
112
+ | none => tampered := tampered.push c
113
+ for t in targetNames do
114
+ let mut ok := true
115
+ let mut why := ""
116
+ match refMap[t]?, solEnv.find? t with
117
+ | none, _ => ok := false; why := "target missing from reference"
118
+ | _, none => ok := false; why := "theorem not found in the submission"
119
+ | some r, some s =>
120
+ if !tampered.isEmpty then
121
+ ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}"
122
+ else if kindOf s != "theorem" && kindOf s != "def" then
123
+ ok := false; why := s!"declared as {kindOf s}, not proved"
124
+ else if r.levelParams != s.levelParams || r.type != s.type then
125
+ ok := false; why := "the statement differs from the one asked for"
126
+ else
127
+ let ax := axiomsOf solEnv t
128
+ let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a))
129
+ if !bad.isEmpty then
130
+ ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}"
131
+ IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}"
132
+ return 0
133
+ | _ =>
134
+ IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] <ReferenceModule> <SubmissionModule> <target>..."
135
+ return 2
tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/tests/grade.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Grade a Lean submission against a task. Standard library only.
3
+
4
+ python3 grade.py --spec spec.json --solution Solution.lean --out <dir>
5
+
6
+ `spec.json` holds the hidden reference file, the target theorem names and their weights (see
7
+ arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as
8
+ asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a
9
+ second kernel check by `leanchecker`. A submission that does not compile scores 0.
10
+
11
+ The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this
12
+ file, then /opt/arena/lean.
13
+ """
14
+ import argparse, json, os, shutil, subprocess, sys, tempfile, time
15
+
16
+ HERE = os.path.dirname(os.path.abspath(__file__))
17
+ TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600"))
18
+
19
+ def project():
20
+ for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"):
21
+ if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p)
22
+ raise SystemExit("Lean project not found; set ARENA_LEAN")
23
+
24
+ _lp = {}
25
+ def lean_path(proj):
26
+ if proj not in _lp:
27
+ cache = os.path.join(proj, ".lake", "lean_path.txt")
28
+ if os.path.exists(cache): _lp[proj] = open(cache).read().strip()
29
+ else:
30
+ _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip()
31
+ try: open(cache, "w").write(_lp[proj])
32
+ except OSError: pass
33
+ return _lp[proj]
34
+
35
+ class Slot:
36
+ """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir."""
37
+ def __enter__(self):
38
+ self.path = None
39
+ n = int(os.environ.get("ARENA_SLOTS", "0"))
40
+ if not n: return self
41
+ d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True)
42
+ while True:
43
+ for i in range(n):
44
+ p = os.path.join(d, "slot%d" % i)
45
+ try:
46
+ os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self
47
+ except FileExistsError:
48
+ try:
49
+ pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0)
50
+ except (OSError, ValueError):
51
+ shutil.rmtree(p, ignore_errors=True) # stale
52
+ time.sleep(1)
53
+ def __exit__(self, *a):
54
+ if self.path: shutil.rmtree(self.path, ignore_errors=True)
55
+
56
+ def run(cmd, proj, extra_path=None, timeout=TIMEOUT):
57
+ env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "")
58
+ with Slot():
59
+ try:
60
+ r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout)
61
+ return r.returncode, (r.stdout + r.stderr)
62
+ except subprocess.TimeoutExpired:
63
+ return 124, "timed out after %d s" % timeout
64
+
65
+ def compile_lean(proj, src, work):
66
+ """Compile work/<src>.lean to work/<src>.olean. Returns (ok, messages)."""
67
+ olean = os.path.join(work, src + ".olean")
68
+ if os.path.exists(olean): os.remove(olean)
69
+ code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work)
70
+ return code == 0 and os.path.exists(olean), out
71
+
72
+ def grade(spec, solution_text, keep=None):
73
+ proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-")
74
+ os.makedirs(work, exist_ok=True)
75
+ targets = spec["targets"]; total = float(sum(t["weight"] for t in targets))
76
+ res = {"reward": 0.0, "stage": "", "targets": [], "log": ""}
77
+ def fail(stage, log):
78
+ res["stage"] = stage; res["log"] = log[-4000:]
79
+ res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets]
80
+ return res
81
+ try:
82
+ open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"])
83
+ open(os.path.join(work, "Solution.lean"), "w").write(solution_text)
84
+ ok, out = compile_lean(proj, "Reference", work)
85
+ if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out)
86
+ ok, out = compile_lean(proj, "Solution", work)
87
+ if not ok: return fail("the submission does not compile", out)
88
+ code, out = run(["leanchecker", "Solution"], proj, work)
89
+ if code != 0: return fail("the submission fails the kernel re-check", out)
90
+ sub = "Solution"; flags = []
91
+ if spec.get("tests"):
92
+ open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"])
93
+ ok, out = compile_lean(proj, "Tests", work)
94
+ if not ok: return fail("the hidden tests do not pass", out)
95
+ code, out = run(["leanchecker", "Tests"], proj, work)
96
+ if code != 0: return fail("the tests fail the kernel re-check", out)
97
+ sub = "Tests"; flags = ["--native"]
98
+ if spec.get("free"): flags += ["--free", ",".join(spec["free"])]
99
+ verify = os.path.join(HERE, "Verify.lean")
100
+ if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean")
101
+ code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work)
102
+ got = {}
103
+ for line in out.splitlines():
104
+ if line.startswith("{"):
105
+ try: j = json.loads(line); got[j["target"]] = j
106
+ except ValueError: pass
107
+ if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out)
108
+ res["targets"] = [got[t["name"]] for t in targets]
109
+ res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4)
110
+ res["stage"] = "graded"
111
+ return res
112
+ finally:
113
+ if not keep: shutil.rmtree(work, ignore_errors=True)
114
+
115
+ if __name__ == "__main__":
116
+ ap = argparse.ArgumentParser()
117
+ ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None)
118
+ a = ap.parse_args()
119
+ spec = json.load(open(a.spec, encoding="utf-8"))
120
+ try: text = open(a.solution, encoding="utf-8").read()
121
+ except OSError: text = None
122
+ res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""}
123
+ print(json.dumps(res, indent=1, ensure_ascii=False))
124
+ if a.out:
125
+ os.makedirs(a.out, exist_ok=True)
126
+ open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"])
127
+ json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False)
tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/tests/spec.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "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",
3
+ "targets": [
4
+ {
5
+ "name": "det_of_product",
6
+ "weight": 1.0
7
+ }
8
+ ]
9
+ }
tasks/linear-algebra/linear-algebra-det_trace-d1-e0000/tests/test.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ mkdir -p /logs/verifier
3
+ python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt
tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/environment/Dockerfile ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ FROM lean-arena
2
+ WORKDIR /app
3
+ COPY workdir/ /app/
tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/environment/workdir/Solution.lean ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ import Mathlib
2
+
3
+ /-- The determinant of the product is the product of the determinants. -/
4
+ theorem det_of_product : Matrix.det (!![3, 1; -2, 2] * !![4, -1; -3, 2] : Matrix (Fin 2) (Fin 2) ℤ) = 40 := by
5
+ sorry
tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/instruction.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Determinant and trace of 2x2 matrices
2
+
3
+ Prove the following statement.
4
+
5
+ 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.
6
+
7
+ ## What to do
8
+
9
+ `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.
10
+
11
+ - Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions.
12
+ - 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.
13
+ - A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`.
14
+ - The reward is 1 if the theorem is proved and 0 otherwise.
tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/solution/Solution.lean ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ import Mathlib
2
+
3
+ /-- The determinant of the product is the product of the determinants. -/
4
+ theorem det_of_product : Matrix.det (!![3, 1; -2, 2] * !![4, -1; -3, 2] : Matrix (Fin 2) (Fin 2) ℤ) = 40 := by
5
+ rw [Matrix.det_mul, Matrix.det_fin_two_of, Matrix.det_fin_two_of]
6
+ norm_num
tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/solution/solve.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ set -e
3
+ cp /solution/Solution.lean /app/Solution.lean
tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/task.toml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [metadata]
4
+ author_name = "Renaissance Labs"
5
+ author_email = "unknown"
6
+ difficulty = "easy"
7
+ category = "linear-algebra"
8
+ tags = ["linear-algebra", "det_trace", "msc-15", "eval", "lean4"]
9
+ msc = "15"
10
+ family = "det_trace"
11
+ split = "eval"
12
+ seed = 10012
13
+
14
+ [verifier]
15
+ timeout_sec = 900.0
16
+
17
+ [agent]
18
+ timeout_sec = 1800.0
19
+
20
+ [environment]
21
+ build_timeout_sec = 1800.0
22
+ cpus = 2
23
+ memory_mb = 6144
24
+ storage_mb = 10240
25
+ allow_internet = false
tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/tests/Verify.lean ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /-
2
+ Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for.
3
+
4
+ lean --run Verify.lean [--free a,b] [--native] <ReferenceModule> <SubmissionModule> <target>...
5
+
6
+ `--free a,b` names definitions the task asks the solver to write: their type must match the
7
+ reference, their value is the solver's own. `--native` additionally accepts the axioms that
8
+ `native_decide` introduces; it is used only for hidden test theorems the grader itself proves.
9
+
10
+ Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only
11
+ `Lean`, never the submission, so nothing the submission declares (notation, macros, instances)
12
+ can change how the check itself is read. It reads the reference module's constants from its .olean, imports the
13
+ submission as an environment, and compares kernel terms:
14
+
15
+ 1. every non-target constant the reference module declares (the task's own definitions) must be
16
+ present in the submission with the same kind, type and value;
17
+ 2. every target must be present with exactly the reference type;
18
+ 3. the proof of every target may depend only on the three standard axioms.
19
+
20
+ It prints one JSON object per target and exits 0. The caller turns that into a reward.
21
+ -/
22
+ import Lean
23
+ open Lean
24
+
25
+ def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound]
26
+
27
+ /-- All axioms a constant depends on, found by walking every constant it mentions. -/
28
+ partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do
29
+ let mut seen : NameSet := {}
30
+ let mut todo : Array Name := #[root]
31
+ let mut out : Array Name := #[]
32
+ while h : todo.size > 0 do
33
+ let c := todo[todo.size - 1]
34
+ todo := todo.pop
35
+ if seen.contains c then continue
36
+ seen := seen.insert c
37
+ match env.find? c with
38
+ | none => out := out.push (`missing ++ c)
39
+ | some info =>
40
+ let mut es : Array Expr := #[info.type]
41
+ match info with
42
+ | .axiomInfo _ => out := out.push c
43
+ | .defnInfo v => es := es.push v.value
44
+ | .thmInfo v => es := es.push v.value
45
+ | .opaqueInfo v => es := es.push v.value
46
+ | .ctorInfo v => todo := todo.push v.induct
47
+ | .inductInfo v => for k in v.ctors do todo := todo.push k
48
+ | .recInfo v => for r in v.rules do es := es.push r.rhs
49
+ | .quotInfo _ => pure ()
50
+ for e in es do
51
+ for k in e.getUsedConstants do
52
+ if !seen.contains k then todo := todo.push k
53
+ return out
54
+
55
+ def kindOf : ConstantInfo → String
56
+ | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem"
57
+ | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive"
58
+ | .ctorInfo _ => "constructor" | .recInfo _ => "recursor"
59
+
60
+ def valueOf : ConstantInfo → Option Expr
61
+ | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value
62
+ | _ => none
63
+
64
+ def sameDecl (a b : ConstantInfo) : Bool :=
65
+ kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b
66
+
67
+ def jstr (s : String) : String := (Json.str s).compress
68
+
69
+ def isNativeAxiom (n : Name) : Bool :=
70
+ n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler ||
71
+ n.components.any (fun c => c == `native_decide)
72
+
73
+ def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c)
74
+
75
+ partial def parseFlags (args : List String) (free : List Name) (native : Bool) :
76
+ List Name × Bool × List String :=
77
+ match args with
78
+ | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native
79
+ | "--native" :: rest => parseFlags rest free true
80
+ | rest => (free, native, rest)
81
+
82
+ def main (args : List String) : IO UInt32 := do
83
+ let (free, native, args) := parseFlags args [] false
84
+ match args with
85
+ | refMod :: solMod :: targets =>
86
+ initSearchPath (← findSysroot)
87
+ let refName := refMod.toName
88
+ let solName := solMod.toName
89
+ let targetNames := targets.map String.toName
90
+ -- The reference is read straight from its .olean: that file holds exactly the constants the
91
+ -- reference module declares, which is all the comparison needs. Only the submission is imported
92
+ -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two.
93
+ let (refData, _) ← readModuleData (← findOLean refName)
94
+ let mut refMap : Std.HashMap Name ConstantInfo := {}
95
+ for i in [0:refData.constNames.size] do
96
+ refMap := refMap.insert refData.constNames[i]! refData.constants[i]!
97
+ let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0)
98
+ -- 1. the task's own definitions are unchanged
99
+ let mut tampered : Array Name := #[]
100
+ for c in refData.constNames do
101
+ if targetNames.contains c then continue
102
+ let some r := refMap[c]? | continue
103
+ if free.contains c then
104
+ match solEnv.find? c with
105
+ | some s =>
106
+ if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c
107
+ | none => tampered := tampered.push c
108
+ continue
109
+ if isUnder free c then continue
110
+ match solEnv.find? c with
111
+ | some s => if !sameDecl r s then tampered := tampered.push c
112
+ | none => tampered := tampered.push c
113
+ for t in targetNames do
114
+ let mut ok := true
115
+ let mut why := ""
116
+ match refMap[t]?, solEnv.find? t with
117
+ | none, _ => ok := false; why := "target missing from reference"
118
+ | _, none => ok := false; why := "theorem not found in the submission"
119
+ | some r, some s =>
120
+ if !tampered.isEmpty then
121
+ ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}"
122
+ else if kindOf s != "theorem" && kindOf s != "def" then
123
+ ok := false; why := s!"declared as {kindOf s}, not proved"
124
+ else if r.levelParams != s.levelParams || r.type != s.type then
125
+ ok := false; why := "the statement differs from the one asked for"
126
+ else
127
+ let ax := axiomsOf solEnv t
128
+ let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a))
129
+ if !bad.isEmpty then
130
+ ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}"
131
+ IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}"
132
+ return 0
133
+ | _ =>
134
+ IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] <ReferenceModule> <SubmissionModule> <target>..."
135
+ return 2
tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/tests/grade.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Grade a Lean submission against a task. Standard library only.
3
+
4
+ python3 grade.py --spec spec.json --solution Solution.lean --out <dir>
5
+
6
+ `spec.json` holds the hidden reference file, the target theorem names and their weights (see
7
+ arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as
8
+ asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a
9
+ second kernel check by `leanchecker`. A submission that does not compile scores 0.
10
+
11
+ The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this
12
+ file, then /opt/arena/lean.
13
+ """
14
+ import argparse, json, os, shutil, subprocess, sys, tempfile, time
15
+
16
+ HERE = os.path.dirname(os.path.abspath(__file__))
17
+ TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600"))
18
+
19
+ def project():
20
+ for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"):
21
+ if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p)
22
+ raise SystemExit("Lean project not found; set ARENA_LEAN")
23
+
24
+ _lp = {}
25
+ def lean_path(proj):
26
+ if proj not in _lp:
27
+ cache = os.path.join(proj, ".lake", "lean_path.txt")
28
+ if os.path.exists(cache): _lp[proj] = open(cache).read().strip()
29
+ else:
30
+ _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip()
31
+ try: open(cache, "w").write(_lp[proj])
32
+ except OSError: pass
33
+ return _lp[proj]
34
+
35
+ class Slot:
36
+ """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir."""
37
+ def __enter__(self):
38
+ self.path = None
39
+ n = int(os.environ.get("ARENA_SLOTS", "0"))
40
+ if not n: return self
41
+ d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True)
42
+ while True:
43
+ for i in range(n):
44
+ p = os.path.join(d, "slot%d" % i)
45
+ try:
46
+ os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self
47
+ except FileExistsError:
48
+ try:
49
+ pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0)
50
+ except (OSError, ValueError):
51
+ shutil.rmtree(p, ignore_errors=True) # stale
52
+ time.sleep(1)
53
+ def __exit__(self, *a):
54
+ if self.path: shutil.rmtree(self.path, ignore_errors=True)
55
+
56
+ def run(cmd, proj, extra_path=None, timeout=TIMEOUT):
57
+ env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "")
58
+ with Slot():
59
+ try:
60
+ r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout)
61
+ return r.returncode, (r.stdout + r.stderr)
62
+ except subprocess.TimeoutExpired:
63
+ return 124, "timed out after %d s" % timeout
64
+
65
+ def compile_lean(proj, src, work):
66
+ """Compile work/<src>.lean to work/<src>.olean. Returns (ok, messages)."""
67
+ olean = os.path.join(work, src + ".olean")
68
+ if os.path.exists(olean): os.remove(olean)
69
+ code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work)
70
+ return code == 0 and os.path.exists(olean), out
71
+
72
+ def grade(spec, solution_text, keep=None):
73
+ proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-")
74
+ os.makedirs(work, exist_ok=True)
75
+ targets = spec["targets"]; total = float(sum(t["weight"] for t in targets))
76
+ res = {"reward": 0.0, "stage": "", "targets": [], "log": ""}
77
+ def fail(stage, log):
78
+ res["stage"] = stage; res["log"] = log[-4000:]
79
+ res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets]
80
+ return res
81
+ try:
82
+ open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"])
83
+ open(os.path.join(work, "Solution.lean"), "w").write(solution_text)
84
+ ok, out = compile_lean(proj, "Reference", work)
85
+ if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out)
86
+ ok, out = compile_lean(proj, "Solution", work)
87
+ if not ok: return fail("the submission does not compile", out)
88
+ code, out = run(["leanchecker", "Solution"], proj, work)
89
+ if code != 0: return fail("the submission fails the kernel re-check", out)
90
+ sub = "Solution"; flags = []
91
+ if spec.get("tests"):
92
+ open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"])
93
+ ok, out = compile_lean(proj, "Tests", work)
94
+ if not ok: return fail("the hidden tests do not pass", out)
95
+ code, out = run(["leanchecker", "Tests"], proj, work)
96
+ if code != 0: return fail("the tests fail the kernel re-check", out)
97
+ sub = "Tests"; flags = ["--native"]
98
+ if spec.get("free"): flags += ["--free", ",".join(spec["free"])]
99
+ verify = os.path.join(HERE, "Verify.lean")
100
+ if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean")
101
+ code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work)
102
+ got = {}
103
+ for line in out.splitlines():
104
+ if line.startswith("{"):
105
+ try: j = json.loads(line); got[j["target"]] = j
106
+ except ValueError: pass
107
+ if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out)
108
+ res["targets"] = [got[t["name"]] for t in targets]
109
+ res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4)
110
+ res["stage"] = "graded"
111
+ return res
112
+ finally:
113
+ if not keep: shutil.rmtree(work, ignore_errors=True)
114
+
115
+ if __name__ == "__main__":
116
+ ap = argparse.ArgumentParser()
117
+ ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None)
118
+ a = ap.parse_args()
119
+ spec = json.load(open(a.spec, encoding="utf-8"))
120
+ try: text = open(a.solution, encoding="utf-8").read()
121
+ except OSError: text = None
122
+ res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""}
123
+ print(json.dumps(res, indent=1, ensure_ascii=False))
124
+ if a.out:
125
+ os.makedirs(a.out, exist_ok=True)
126
+ open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"])
127
+ json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False)
tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/tests/spec.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "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",
3
+ "targets": [
4
+ {
5
+ "name": "det_of_product",
6
+ "weight": 1.0
7
+ }
8
+ ]
9
+ }
tasks/linear-algebra/linear-algebra-det_trace-d1-e0012/tests/test.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ mkdir -p /logs/verifier
3
+ python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt
tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/environment/Dockerfile ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ FROM lean-arena
2
+ WORKDIR /app
3
+ COPY workdir/ /app/
tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/environment/workdir/Solution.lean ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ import Mathlib
2
+
3
+ /-- The determinant of the product is the product of the determinants. -/
4
+ theorem det_of_product : Matrix.det (!![-2, 3; 3, 0] * !![-2, 4; 3, 0] : Matrix (Fin 2) (Fin 2) ℤ) = 108 := by
5
+ sorry
tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/instruction.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Determinant and trace of 2x2 matrices
2
+
3
+ Prove the following statement.
4
+
5
+ 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.
6
+
7
+ ## What to do
8
+
9
+ `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.
10
+
11
+ - Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions.
12
+ - 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.
13
+ - A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`.
14
+ - The reward is 1 if the theorem is proved and 0 otherwise.
tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/solution/Solution.lean ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ import Mathlib
2
+
3
+ /-- The determinant of the product is the product of the determinants. -/
4
+ theorem det_of_product : Matrix.det (!![-2, 3; 3, 0] * !![-2, 4; 3, 0] : Matrix (Fin 2) (Fin 2) ℤ) = 108 := by
5
+ rw [Matrix.det_mul, Matrix.det_fin_two_of, Matrix.det_fin_two_of]
6
+ norm_num
tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/solution/solve.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ set -e
3
+ cp /solution/Solution.lean /app/Solution.lean
tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/task.toml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [metadata]
4
+ author_name = "Renaissance Labs"
5
+ author_email = "unknown"
6
+ difficulty = "easy"
7
+ category = "linear-algebra"
8
+ tags = ["linear-algebra", "det_trace", "msc-15", "train", "lean4"]
9
+ msc = "15"
10
+ family = "det_trace"
11
+ split = "train"
12
+ seed = 0
13
+
14
+ [verifier]
15
+ timeout_sec = 900.0
16
+
17
+ [agent]
18
+ timeout_sec = 1800.0
19
+
20
+ [environment]
21
+ build_timeout_sec = 1800.0
22
+ cpus = 2
23
+ memory_mb = 6144
24
+ storage_mb = 10240
25
+ allow_internet = false
tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/tests/Verify.lean ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /-
2
+ Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for.
3
+
4
+ lean --run Verify.lean [--free a,b] [--native] <ReferenceModule> <SubmissionModule> <target>...
5
+
6
+ `--free a,b` names definitions the task asks the solver to write: their type must match the
7
+ reference, their value is the solver's own. `--native` additionally accepts the axioms that
8
+ `native_decide` introduces; it is used only for hidden test theorems the grader itself proves.
9
+
10
+ Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only
11
+ `Lean`, never the submission, so nothing the submission declares (notation, macros, instances)
12
+ can change how the check itself is read. It reads the reference module's constants from its .olean, imports the
13
+ submission as an environment, and compares kernel terms:
14
+
15
+ 1. every non-target constant the reference module declares (the task's own definitions) must be
16
+ present in the submission with the same kind, type and value;
17
+ 2. every target must be present with exactly the reference type;
18
+ 3. the proof of every target may depend only on the three standard axioms.
19
+
20
+ It prints one JSON object per target and exits 0. The caller turns that into a reward.
21
+ -/
22
+ import Lean
23
+ open Lean
24
+
25
+ def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound]
26
+
27
+ /-- All axioms a constant depends on, found by walking every constant it mentions. -/
28
+ partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do
29
+ let mut seen : NameSet := {}
30
+ let mut todo : Array Name := #[root]
31
+ let mut out : Array Name := #[]
32
+ while h : todo.size > 0 do
33
+ let c := todo[todo.size - 1]
34
+ todo := todo.pop
35
+ if seen.contains c then continue
36
+ seen := seen.insert c
37
+ match env.find? c with
38
+ | none => out := out.push (`missing ++ c)
39
+ | some info =>
40
+ let mut es : Array Expr := #[info.type]
41
+ match info with
42
+ | .axiomInfo _ => out := out.push c
43
+ | .defnInfo v => es := es.push v.value
44
+ | .thmInfo v => es := es.push v.value
45
+ | .opaqueInfo v => es := es.push v.value
46
+ | .ctorInfo v => todo := todo.push v.induct
47
+ | .inductInfo v => for k in v.ctors do todo := todo.push k
48
+ | .recInfo v => for r in v.rules do es := es.push r.rhs
49
+ | .quotInfo _ => pure ()
50
+ for e in es do
51
+ for k in e.getUsedConstants do
52
+ if !seen.contains k then todo := todo.push k
53
+ return out
54
+
55
+ def kindOf : ConstantInfo → String
56
+ | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem"
57
+ | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive"
58
+ | .ctorInfo _ => "constructor" | .recInfo _ => "recursor"
59
+
60
+ def valueOf : ConstantInfo → Option Expr
61
+ | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value
62
+ | _ => none
63
+
64
+ def sameDecl (a b : ConstantInfo) : Bool :=
65
+ kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b
66
+
67
+ def jstr (s : String) : String := (Json.str s).compress
68
+
69
+ def isNativeAxiom (n : Name) : Bool :=
70
+ n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler ||
71
+ n.components.any (fun c => c == `native_decide)
72
+
73
+ def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c)
74
+
75
+ partial def parseFlags (args : List String) (free : List Name) (native : Bool) :
76
+ List Name × Bool × List String :=
77
+ match args with
78
+ | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native
79
+ | "--native" :: rest => parseFlags rest free true
80
+ | rest => (free, native, rest)
81
+
82
+ def main (args : List String) : IO UInt32 := do
83
+ let (free, native, args) := parseFlags args [] false
84
+ match args with
85
+ | refMod :: solMod :: targets =>
86
+ initSearchPath (← findSysroot)
87
+ let refName := refMod.toName
88
+ let solName := solMod.toName
89
+ let targetNames := targets.map String.toName
90
+ -- The reference is read straight from its .olean: that file holds exactly the constants the
91
+ -- reference module declares, which is all the comparison needs. Only the submission is imported
92
+ -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two.
93
+ let (refData, _) ← readModuleData (← findOLean refName)
94
+ let mut refMap : Std.HashMap Name ConstantInfo := {}
95
+ for i in [0:refData.constNames.size] do
96
+ refMap := refMap.insert refData.constNames[i]! refData.constants[i]!
97
+ let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0)
98
+ -- 1. the task's own definitions are unchanged
99
+ let mut tampered : Array Name := #[]
100
+ for c in refData.constNames do
101
+ if targetNames.contains c then continue
102
+ let some r := refMap[c]? | continue
103
+ if free.contains c then
104
+ match solEnv.find? c with
105
+ | some s =>
106
+ if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c
107
+ | none => tampered := tampered.push c
108
+ continue
109
+ if isUnder free c then continue
110
+ match solEnv.find? c with
111
+ | some s => if !sameDecl r s then tampered := tampered.push c
112
+ | none => tampered := tampered.push c
113
+ for t in targetNames do
114
+ let mut ok := true
115
+ let mut why := ""
116
+ match refMap[t]?, solEnv.find? t with
117
+ | none, _ => ok := false; why := "target missing from reference"
118
+ | _, none => ok := false; why := "theorem not found in the submission"
119
+ | some r, some s =>
120
+ if !tampered.isEmpty then
121
+ ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}"
122
+ else if kindOf s != "theorem" && kindOf s != "def" then
123
+ ok := false; why := s!"declared as {kindOf s}, not proved"
124
+ else if r.levelParams != s.levelParams || r.type != s.type then
125
+ ok := false; why := "the statement differs from the one asked for"
126
+ else
127
+ let ax := axiomsOf solEnv t
128
+ let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a))
129
+ if !bad.isEmpty then
130
+ ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}"
131
+ IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}"
132
+ return 0
133
+ | _ =>
134
+ IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] <ReferenceModule> <SubmissionModule> <target>..."
135
+ return 2
tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/tests/grade.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Grade a Lean submission against a task. Standard library only.
3
+
4
+ python3 grade.py --spec spec.json --solution Solution.lean --out <dir>
5
+
6
+ `spec.json` holds the hidden reference file, the target theorem names and their weights (see
7
+ arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as
8
+ asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a
9
+ second kernel check by `leanchecker`. A submission that does not compile scores 0.
10
+
11
+ The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this
12
+ file, then /opt/arena/lean.
13
+ """
14
+ import argparse, json, os, shutil, subprocess, sys, tempfile, time
15
+
16
+ HERE = os.path.dirname(os.path.abspath(__file__))
17
+ TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600"))
18
+
19
+ def project():
20
+ for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"):
21
+ if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p)
22
+ raise SystemExit("Lean project not found; set ARENA_LEAN")
23
+
24
+ _lp = {}
25
+ def lean_path(proj):
26
+ if proj not in _lp:
27
+ cache = os.path.join(proj, ".lake", "lean_path.txt")
28
+ if os.path.exists(cache): _lp[proj] = open(cache).read().strip()
29
+ else:
30
+ _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip()
31
+ try: open(cache, "w").write(_lp[proj])
32
+ except OSError: pass
33
+ return _lp[proj]
34
+
35
+ class Slot:
36
+ """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir."""
37
+ def __enter__(self):
38
+ self.path = None
39
+ n = int(os.environ.get("ARENA_SLOTS", "0"))
40
+ if not n: return self
41
+ d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True)
42
+ while True:
43
+ for i in range(n):
44
+ p = os.path.join(d, "slot%d" % i)
45
+ try:
46
+ os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self
47
+ except FileExistsError:
48
+ try:
49
+ pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0)
50
+ except (OSError, ValueError):
51
+ shutil.rmtree(p, ignore_errors=True) # stale
52
+ time.sleep(1)
53
+ def __exit__(self, *a):
54
+ if self.path: shutil.rmtree(self.path, ignore_errors=True)
55
+
56
+ def run(cmd, proj, extra_path=None, timeout=TIMEOUT):
57
+ env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "")
58
+ with Slot():
59
+ try:
60
+ r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout)
61
+ return r.returncode, (r.stdout + r.stderr)
62
+ except subprocess.TimeoutExpired:
63
+ return 124, "timed out after %d s" % timeout
64
+
65
+ def compile_lean(proj, src, work):
66
+ """Compile work/<src>.lean to work/<src>.olean. Returns (ok, messages)."""
67
+ olean = os.path.join(work, src + ".olean")
68
+ if os.path.exists(olean): os.remove(olean)
69
+ code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work)
70
+ return code == 0 and os.path.exists(olean), out
71
+
72
+ def grade(spec, solution_text, keep=None):
73
+ proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-")
74
+ os.makedirs(work, exist_ok=True)
75
+ targets = spec["targets"]; total = float(sum(t["weight"] for t in targets))
76
+ res = {"reward": 0.0, "stage": "", "targets": [], "log": ""}
77
+ def fail(stage, log):
78
+ res["stage"] = stage; res["log"] = log[-4000:]
79
+ res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets]
80
+ return res
81
+ try:
82
+ open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"])
83
+ open(os.path.join(work, "Solution.lean"), "w").write(solution_text)
84
+ ok, out = compile_lean(proj, "Reference", work)
85
+ if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out)
86
+ ok, out = compile_lean(proj, "Solution", work)
87
+ if not ok: return fail("the submission does not compile", out)
88
+ code, out = run(["leanchecker", "Solution"], proj, work)
89
+ if code != 0: return fail("the submission fails the kernel re-check", out)
90
+ sub = "Solution"; flags = []
91
+ if spec.get("tests"):
92
+ open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"])
93
+ ok, out = compile_lean(proj, "Tests", work)
94
+ if not ok: return fail("the hidden tests do not pass", out)
95
+ code, out = run(["leanchecker", "Tests"], proj, work)
96
+ if code != 0: return fail("the tests fail the kernel re-check", out)
97
+ sub = "Tests"; flags = ["--native"]
98
+ if spec.get("free"): flags += ["--free", ",".join(spec["free"])]
99
+ verify = os.path.join(HERE, "Verify.lean")
100
+ if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean")
101
+ code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work)
102
+ got = {}
103
+ for line in out.splitlines():
104
+ if line.startswith("{"):
105
+ try: j = json.loads(line); got[j["target"]] = j
106
+ except ValueError: pass
107
+ if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out)
108
+ res["targets"] = [got[t["name"]] for t in targets]
109
+ res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4)
110
+ res["stage"] = "graded"
111
+ return res
112
+ finally:
113
+ if not keep: shutil.rmtree(work, ignore_errors=True)
114
+
115
+ if __name__ == "__main__":
116
+ ap = argparse.ArgumentParser()
117
+ ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None)
118
+ a = ap.parse_args()
119
+ spec = json.load(open(a.spec, encoding="utf-8"))
120
+ try: text = open(a.solution, encoding="utf-8").read()
121
+ except OSError: text = None
122
+ res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""}
123
+ print(json.dumps(res, indent=1, ensure_ascii=False))
124
+ if a.out:
125
+ os.makedirs(a.out, exist_ok=True)
126
+ open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"])
127
+ json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False)
tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/tests/spec.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "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",
3
+ "targets": [
4
+ {
5
+ "name": "det_of_product",
6
+ "weight": 1.0
7
+ }
8
+ ]
9
+ }
tasks/linear-algebra/linear-algebra-det_trace-d1-t0000/tests/test.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ mkdir -p /logs/verifier
3
+ python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt
tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/environment/Dockerfile ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ FROM lean-arena
2
+ WORKDIR /app
3
+ COPY workdir/ /app/
tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/environment/workdir/Solution.lean ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ import Mathlib
2
+
3
+ /-- A matrix times its adjugate is its determinant times the identity. -/
4
+ theorem adjugate_product (x : ℤ) :
5
+ !![x + 0, 2; -3, x - 3] * !![x - 3, -2; 3, x + 0] = (x ^ 2 + -3 * x + 6) • (1 : Matrix (Fin 2) (Fin 2) ℤ) := by
6
+ sorry
tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/instruction.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Determinant and trace of 2x2 matrices
2
+
3
+ Prove the following statement.
4
+
5
+ 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}.\]
6
+
7
+ ## What to do
8
+
9
+ `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.
10
+
11
+ - Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions.
12
+ - 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.
13
+ - A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`.
14
+ - The reward is 1 if the theorem is proved and 0 otherwise.
tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/solution/Solution.lean ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import Mathlib
2
+
3
+ /-- A matrix times its adjugate is its determinant times the identity. -/
4
+ theorem adjugate_product (x : ℤ) :
5
+ !![x + 0, 2; -3, x - 3] * !![x - 3, -2; 3, x + 0] = (x ^ 2 + -3 * x + 6) • (1 : Matrix (Fin 2) (Fin 2) ℤ) := by
6
+ rw [Matrix.one_fin_two, Matrix.mul_fin_two]
7
+ ext i j
8
+ fin_cases i <;> fin_cases j <;> simp <;> ring
tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/solution/solve.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ set -e
3
+ cp /solution/Solution.lean /app/Solution.lean
tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/task.toml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [metadata]
4
+ author_name = "Renaissance Labs"
5
+ author_email = "unknown"
6
+ difficulty = "easy"
7
+ category = "linear-algebra"
8
+ tags = ["linear-algebra", "det_trace", "msc-15", "train", "lean4"]
9
+ msc = "15"
10
+ family = "det_trace"
11
+ split = "train"
12
+ seed = 12
13
+
14
+ [verifier]
15
+ timeout_sec = 900.0
16
+
17
+ [agent]
18
+ timeout_sec = 1800.0
19
+
20
+ [environment]
21
+ build_timeout_sec = 1800.0
22
+ cpus = 2
23
+ memory_mb = 6144
24
+ storage_mb = 10240
25
+ allow_internet = false
tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/tests/Verify.lean ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /-
2
+ Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for.
3
+
4
+ lean --run Verify.lean [--free a,b] [--native] <ReferenceModule> <SubmissionModule> <target>...
5
+
6
+ `--free a,b` names definitions the task asks the solver to write: their type must match the
7
+ reference, their value is the solver's own. `--native` additionally accepts the axioms that
8
+ `native_decide` introduces; it is used only for hidden test theorems the grader itself proves.
9
+
10
+ Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only
11
+ `Lean`, never the submission, so nothing the submission declares (notation, macros, instances)
12
+ can change how the check itself is read. It reads the reference module's constants from its .olean, imports the
13
+ submission as an environment, and compares kernel terms:
14
+
15
+ 1. every non-target constant the reference module declares (the task's own definitions) must be
16
+ present in the submission with the same kind, type and value;
17
+ 2. every target must be present with exactly the reference type;
18
+ 3. the proof of every target may depend only on the three standard axioms.
19
+
20
+ It prints one JSON object per target and exits 0. The caller turns that into a reward.
21
+ -/
22
+ import Lean
23
+ open Lean
24
+
25
+ def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound]
26
+
27
+ /-- All axioms a constant depends on, found by walking every constant it mentions. -/
28
+ partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do
29
+ let mut seen : NameSet := {}
30
+ let mut todo : Array Name := #[root]
31
+ let mut out : Array Name := #[]
32
+ while h : todo.size > 0 do
33
+ let c := todo[todo.size - 1]
34
+ todo := todo.pop
35
+ if seen.contains c then continue
36
+ seen := seen.insert c
37
+ match env.find? c with
38
+ | none => out := out.push (`missing ++ c)
39
+ | some info =>
40
+ let mut es : Array Expr := #[info.type]
41
+ match info with
42
+ | .axiomInfo _ => out := out.push c
43
+ | .defnInfo v => es := es.push v.value
44
+ | .thmInfo v => es := es.push v.value
45
+ | .opaqueInfo v => es := es.push v.value
46
+ | .ctorInfo v => todo := todo.push v.induct
47
+ | .inductInfo v => for k in v.ctors do todo := todo.push k
48
+ | .recInfo v => for r in v.rules do es := es.push r.rhs
49
+ | .quotInfo _ => pure ()
50
+ for e in es do
51
+ for k in e.getUsedConstants do
52
+ if !seen.contains k then todo := todo.push k
53
+ return out
54
+
55
+ def kindOf : ConstantInfo → String
56
+ | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem"
57
+ | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive"
58
+ | .ctorInfo _ => "constructor" | .recInfo _ => "recursor"
59
+
60
+ def valueOf : ConstantInfo → Option Expr
61
+ | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value
62
+ | _ => none
63
+
64
+ def sameDecl (a b : ConstantInfo) : Bool :=
65
+ kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b
66
+
67
+ def jstr (s : String) : String := (Json.str s).compress
68
+
69
+ def isNativeAxiom (n : Name) : Bool :=
70
+ n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler ||
71
+ n.components.any (fun c => c == `native_decide)
72
+
73
+ def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c)
74
+
75
+ partial def parseFlags (args : List String) (free : List Name) (native : Bool) :
76
+ List Name × Bool × List String :=
77
+ match args with
78
+ | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native
79
+ | "--native" :: rest => parseFlags rest free true
80
+ | rest => (free, native, rest)
81
+
82
+ def main (args : List String) : IO UInt32 := do
83
+ let (free, native, args) := parseFlags args [] false
84
+ match args with
85
+ | refMod :: solMod :: targets =>
86
+ initSearchPath (← findSysroot)
87
+ let refName := refMod.toName
88
+ let solName := solMod.toName
89
+ let targetNames := targets.map String.toName
90
+ -- The reference is read straight from its .olean: that file holds exactly the constants the
91
+ -- reference module declares, which is all the comparison needs. Only the submission is imported
92
+ -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two.
93
+ let (refData, _) ← readModuleData (← findOLean refName)
94
+ let mut refMap : Std.HashMap Name ConstantInfo := {}
95
+ for i in [0:refData.constNames.size] do
96
+ refMap := refMap.insert refData.constNames[i]! refData.constants[i]!
97
+ let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0)
98
+ -- 1. the task's own definitions are unchanged
99
+ let mut tampered : Array Name := #[]
100
+ for c in refData.constNames do
101
+ if targetNames.contains c then continue
102
+ let some r := refMap[c]? | continue
103
+ if free.contains c then
104
+ match solEnv.find? c with
105
+ | some s =>
106
+ if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c
107
+ | none => tampered := tampered.push c
108
+ continue
109
+ if isUnder free c then continue
110
+ match solEnv.find? c with
111
+ | some s => if !sameDecl r s then tampered := tampered.push c
112
+ | none => tampered := tampered.push c
113
+ for t in targetNames do
114
+ let mut ok := true
115
+ let mut why := ""
116
+ match refMap[t]?, solEnv.find? t with
117
+ | none, _ => ok := false; why := "target missing from reference"
118
+ | _, none => ok := false; why := "theorem not found in the submission"
119
+ | some r, some s =>
120
+ if !tampered.isEmpty then
121
+ ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}"
122
+ else if kindOf s != "theorem" && kindOf s != "def" then
123
+ ok := false; why := s!"declared as {kindOf s}, not proved"
124
+ else if r.levelParams != s.levelParams || r.type != s.type then
125
+ ok := false; why := "the statement differs from the one asked for"
126
+ else
127
+ let ax := axiomsOf solEnv t
128
+ let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a))
129
+ if !bad.isEmpty then
130
+ ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}"
131
+ IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}"
132
+ return 0
133
+ | _ =>
134
+ IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] <ReferenceModule> <SubmissionModule> <target>..."
135
+ return 2
tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/tests/grade.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Grade a Lean submission against a task. Standard library only.
3
+
4
+ python3 grade.py --spec spec.json --solution Solution.lean --out <dir>
5
+
6
+ `spec.json` holds the hidden reference file, the target theorem names and their weights (see
7
+ arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as
8
+ asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a
9
+ second kernel check by `leanchecker`. A submission that does not compile scores 0.
10
+
11
+ The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this
12
+ file, then /opt/arena/lean.
13
+ """
14
+ import argparse, json, os, shutil, subprocess, sys, tempfile, time
15
+
16
+ HERE = os.path.dirname(os.path.abspath(__file__))
17
+ TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600"))
18
+
19
+ def project():
20
+ for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"):
21
+ if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p)
22
+ raise SystemExit("Lean project not found; set ARENA_LEAN")
23
+
24
+ _lp = {}
25
+ def lean_path(proj):
26
+ if proj not in _lp:
27
+ cache = os.path.join(proj, ".lake", "lean_path.txt")
28
+ if os.path.exists(cache): _lp[proj] = open(cache).read().strip()
29
+ else:
30
+ _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip()
31
+ try: open(cache, "w").write(_lp[proj])
32
+ except OSError: pass
33
+ return _lp[proj]
34
+
35
+ class Slot:
36
+ """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir."""
37
+ def __enter__(self):
38
+ self.path = None
39
+ n = int(os.environ.get("ARENA_SLOTS", "0"))
40
+ if not n: return self
41
+ d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True)
42
+ while True:
43
+ for i in range(n):
44
+ p = os.path.join(d, "slot%d" % i)
45
+ try:
46
+ os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self
47
+ except FileExistsError:
48
+ try:
49
+ pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0)
50
+ except (OSError, ValueError):
51
+ shutil.rmtree(p, ignore_errors=True) # stale
52
+ time.sleep(1)
53
+ def __exit__(self, *a):
54
+ if self.path: shutil.rmtree(self.path, ignore_errors=True)
55
+
56
+ def run(cmd, proj, extra_path=None, timeout=TIMEOUT):
57
+ env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "")
58
+ with Slot():
59
+ try:
60
+ r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout)
61
+ return r.returncode, (r.stdout + r.stderr)
62
+ except subprocess.TimeoutExpired:
63
+ return 124, "timed out after %d s" % timeout
64
+
65
+ def compile_lean(proj, src, work):
66
+ """Compile work/<src>.lean to work/<src>.olean. Returns (ok, messages)."""
67
+ olean = os.path.join(work, src + ".olean")
68
+ if os.path.exists(olean): os.remove(olean)
69
+ code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work)
70
+ return code == 0 and os.path.exists(olean), out
71
+
72
+ def grade(spec, solution_text, keep=None):
73
+ proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-")
74
+ os.makedirs(work, exist_ok=True)
75
+ targets = spec["targets"]; total = float(sum(t["weight"] for t in targets))
76
+ res = {"reward": 0.0, "stage": "", "targets": [], "log": ""}
77
+ def fail(stage, log):
78
+ res["stage"] = stage; res["log"] = log[-4000:]
79
+ res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets]
80
+ return res
81
+ try:
82
+ open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"])
83
+ open(os.path.join(work, "Solution.lean"), "w").write(solution_text)
84
+ ok, out = compile_lean(proj, "Reference", work)
85
+ if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out)
86
+ ok, out = compile_lean(proj, "Solution", work)
87
+ if not ok: return fail("the submission does not compile", out)
88
+ code, out = run(["leanchecker", "Solution"], proj, work)
89
+ if code != 0: return fail("the submission fails the kernel re-check", out)
90
+ sub = "Solution"; flags = []
91
+ if spec.get("tests"):
92
+ open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"])
93
+ ok, out = compile_lean(proj, "Tests", work)
94
+ if not ok: return fail("the hidden tests do not pass", out)
95
+ code, out = run(["leanchecker", "Tests"], proj, work)
96
+ if code != 0: return fail("the tests fail the kernel re-check", out)
97
+ sub = "Tests"; flags = ["--native"]
98
+ if spec.get("free"): flags += ["--free", ",".join(spec["free"])]
99
+ verify = os.path.join(HERE, "Verify.lean")
100
+ if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean")
101
+ code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work)
102
+ got = {}
103
+ for line in out.splitlines():
104
+ if line.startswith("{"):
105
+ try: j = json.loads(line); got[j["target"]] = j
106
+ except ValueError: pass
107
+ if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out)
108
+ res["targets"] = [got[t["name"]] for t in targets]
109
+ res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4)
110
+ res["stage"] = "graded"
111
+ return res
112
+ finally:
113
+ if not keep: shutil.rmtree(work, ignore_errors=True)
114
+
115
+ if __name__ == "__main__":
116
+ ap = argparse.ArgumentParser()
117
+ ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None)
118
+ a = ap.parse_args()
119
+ spec = json.load(open(a.spec, encoding="utf-8"))
120
+ try: text = open(a.solution, encoding="utf-8").read()
121
+ except OSError: text = None
122
+ res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""}
123
+ print(json.dumps(res, indent=1, ensure_ascii=False))
124
+ if a.out:
125
+ os.makedirs(a.out, exist_ok=True)
126
+ open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"])
127
+ json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False)
tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/tests/spec.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "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",
3
+ "targets": [
4
+ {
5
+ "name": "adjugate_product",
6
+ "weight": 1.0
7
+ }
8
+ ]
9
+ }
tasks/linear-algebra/linear-algebra-det_trace-d1-t0012/tests/test.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ mkdir -p /logs/verifier
3
+ python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt
tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/environment/Dockerfile ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ FROM lean-arena
2
+ WORKDIR /app
3
+ COPY workdir/ /app/
tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/environment/workdir/Solution.lean ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ import Mathlib
2
+
3
+ /-- The determinant of the product is the product of the determinants. -/
4
+ theorem det_of_product : Matrix.det (!![-2, 0; 1, -3] * !![3, -2; 4, -1] : Matrix (Fin 2) (Fin 2) ℤ) = 30 := by
5
+ sorry
tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/instruction.md ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Determinant and trace of 2x2 matrices
2
+
3
+ Prove the following statement.
4
+
5
+ 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.
6
+
7
+ ## What to do
8
+
9
+ `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.
10
+
11
+ - Do not change the statement of any theorem or any definition the file gives you. You may add your own lemmas and definitions.
12
+ - 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.
13
+ - A theorem counts only if its proof is complete: no `sorry`, no new axioms, no `native_decide`.
14
+ - The reward is 1 if the theorem is proved and 0 otherwise.
tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/solution/Solution.lean ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ import Mathlib
2
+
3
+ /-- The determinant of the product is the product of the determinants. -/
4
+ theorem det_of_product : Matrix.det (!![-2, 0; 1, -3] * !![3, -2; 4, -1] : Matrix (Fin 2) (Fin 2) ℤ) = 30 := by
5
+ rw [Matrix.det_mul, Matrix.det_fin_two_of, Matrix.det_fin_two_of]
6
+ norm_num
tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/solution/solve.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ set -e
3
+ cp /solution/Solution.lean /app/Solution.lean
tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/task.toml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [metadata]
4
+ author_name = "Renaissance Labs"
5
+ author_email = "unknown"
6
+ difficulty = "easy"
7
+ category = "linear-algebra"
8
+ tags = ["linear-algebra", "det_trace", "msc-15", "train", "lean4"]
9
+ msc = "15"
10
+ family = "det_trace"
11
+ split = "train"
12
+ seed = 24
13
+
14
+ [verifier]
15
+ timeout_sec = 900.0
16
+
17
+ [agent]
18
+ timeout_sec = 1800.0
19
+
20
+ [environment]
21
+ build_timeout_sec = 1800.0
22
+ cpus = 2
23
+ memory_mb = 6144
24
+ storage_mb = 10240
25
+ allow_internet = false
tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/tests/Verify.lean ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /-
2
+ Verify.lean: decides whether a submitted Lean module proves the theorems a task asked for.
3
+
4
+ lean --run Verify.lean [--free a,b] [--native] <ReferenceModule> <SubmissionModule> <target>...
5
+
6
+ `--free a,b` names definitions the task asks the solver to write: their type must match the
7
+ reference, their value is the solver's own. `--native` additionally accepts the axioms that
8
+ `native_decide` introduces; it is used only for hidden test theorems the grader itself proves.
9
+
10
+ Both modules must already be compiled to .olean files on LEAN_PATH. This program imports only
11
+ `Lean`, never the submission, so nothing the submission declares (notation, macros, instances)
12
+ can change how the check itself is read. It reads the reference module's constants from its .olean, imports the
13
+ submission as an environment, and compares kernel terms:
14
+
15
+ 1. every non-target constant the reference module declares (the task's own definitions) must be
16
+ present in the submission with the same kind, type and value;
17
+ 2. every target must be present with exactly the reference type;
18
+ 3. the proof of every target may depend only on the three standard axioms.
19
+
20
+ It prints one JSON object per target and exits 0. The caller turns that into a reward.
21
+ -/
22
+ import Lean
23
+ open Lean
24
+
25
+ def allowedAxioms : List Name := [``propext, ``Classical.choice, ``Quot.sound]
26
+
27
+ /-- All axioms a constant depends on, found by walking every constant it mentions. -/
28
+ partial def axiomsOf (env : Environment) (root : Name) : Array Name := Id.run do
29
+ let mut seen : NameSet := {}
30
+ let mut todo : Array Name := #[root]
31
+ let mut out : Array Name := #[]
32
+ while h : todo.size > 0 do
33
+ let c := todo[todo.size - 1]
34
+ todo := todo.pop
35
+ if seen.contains c then continue
36
+ seen := seen.insert c
37
+ match env.find? c with
38
+ | none => out := out.push (`missing ++ c)
39
+ | some info =>
40
+ let mut es : Array Expr := #[info.type]
41
+ match info with
42
+ | .axiomInfo _ => out := out.push c
43
+ | .defnInfo v => es := es.push v.value
44
+ | .thmInfo v => es := es.push v.value
45
+ | .opaqueInfo v => es := es.push v.value
46
+ | .ctorInfo v => todo := todo.push v.induct
47
+ | .inductInfo v => for k in v.ctors do todo := todo.push k
48
+ | .recInfo v => for r in v.rules do es := es.push r.rhs
49
+ | .quotInfo _ => pure ()
50
+ for e in es do
51
+ for k in e.getUsedConstants do
52
+ if !seen.contains k then todo := todo.push k
53
+ return out
54
+
55
+ def kindOf : ConstantInfo → String
56
+ | .axiomInfo _ => "axiom" | .defnInfo _ => "def" | .thmInfo _ => "theorem"
57
+ | .opaqueInfo _ => "opaque" | .quotInfo _ => "quot" | .inductInfo _ => "inductive"
58
+ | .ctorInfo _ => "constructor" | .recInfo _ => "recursor"
59
+
60
+ def valueOf : ConstantInfo → Option Expr
61
+ | .defnInfo v => some v.value | .thmInfo v => some v.value | .opaqueInfo v => some v.value
62
+ | _ => none
63
+
64
+ def sameDecl (a b : ConstantInfo) : Bool :=
65
+ kindOf a == kindOf b && a.levelParams == b.levelParams && a.type == b.type && valueOf a == valueOf b
66
+
67
+ def jstr (s : String) : String := (Json.str s).compress
68
+
69
+ def isNativeAxiom (n : Name) : Bool :=
70
+ n == ``Lean.ofReduceBool || n == ``Lean.trustCompiler ||
71
+ n.components.any (fun c => c == `native_decide)
72
+
73
+ def isUnder (frees : List Name) (c : Name) : Bool := frees.any (fun f => f.isPrefixOf c)
74
+
75
+ partial def parseFlags (args : List String) (free : List Name) (native : Bool) :
76
+ List Name × Bool × List String :=
77
+ match args with
78
+ | "--free" :: v :: rest => parseFlags rest (free ++ (v.splitOn ",").map String.toName) native
79
+ | "--native" :: rest => parseFlags rest free true
80
+ | rest => (free, native, rest)
81
+
82
+ def main (args : List String) : IO UInt32 := do
83
+ let (free, native, args) := parseFlags args [] false
84
+ match args with
85
+ | refMod :: solMod :: targets =>
86
+ initSearchPath (← findSysroot)
87
+ let refName := refMod.toName
88
+ let solName := solMod.toName
89
+ let targetNames := targets.map String.toName
90
+ -- The reference is read straight from its .olean: that file holds exactly the constants the
91
+ -- reference module declares, which is all the comparison needs. Only the submission is imported
92
+ -- as a full environment (Mathlib included), so memory stays at one copy of Mathlib, not two.
93
+ let (refData, _) ← readModuleData (← findOLean refName)
94
+ let mut refMap : Std.HashMap Name ConstantInfo := {}
95
+ for i in [0:refData.constNames.size] do
96
+ refMap := refMap.insert refData.constNames[i]! refData.constants[i]!
97
+ let solEnv ← importModules #[{ module := solName }] {} (trustLevel := 0)
98
+ -- 1. the task's own definitions are unchanged
99
+ let mut tampered : Array Name := #[]
100
+ for c in refData.constNames do
101
+ if targetNames.contains c then continue
102
+ let some r := refMap[c]? | continue
103
+ if free.contains c then
104
+ match solEnv.find? c with
105
+ | some s =>
106
+ if r.levelParams != s.levelParams || r.type != s.type then tampered := tampered.push c
107
+ | none => tampered := tampered.push c
108
+ continue
109
+ if isUnder free c then continue
110
+ match solEnv.find? c with
111
+ | some s => if !sameDecl r s then tampered := tampered.push c
112
+ | none => tampered := tampered.push c
113
+ for t in targetNames do
114
+ let mut ok := true
115
+ let mut why := ""
116
+ match refMap[t]?, solEnv.find? t with
117
+ | none, _ => ok := false; why := "target missing from reference"
118
+ | _, none => ok := false; why := "theorem not found in the submission"
119
+ | some r, some s =>
120
+ if !tampered.isEmpty then
121
+ ok := false; why := s!"the task's definitions were changed or are missing: {tampered.toList}"
122
+ else if kindOf s != "theorem" && kindOf s != "def" then
123
+ ok := false; why := s!"declared as {kindOf s}, not proved"
124
+ else if r.levelParams != s.levelParams || r.type != s.type then
125
+ ok := false; why := "the statement differs from the one asked for"
126
+ else
127
+ let ax := axiomsOf solEnv t
128
+ let bad := ax.filter (fun a => !allowedAxioms.contains a && !(native && isNativeAxiom a))
129
+ if !bad.isEmpty then
130
+ ok := false; why := s!"depends on axioms that are not allowed: {bad.toList}"
131
+ IO.println s!"\{\"target\": {jstr t.toString}, \"ok\": {ok}, \"why\": {jstr why}}"
132
+ return 0
133
+ | _ =>
134
+ IO.eprintln "usage: lean --run Verify.lean [--free a,b] [--native] <ReferenceModule> <SubmissionModule> <target>..."
135
+ return 2
tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/tests/grade.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Grade a Lean submission against a task. Standard library only.
3
+
4
+ python3 grade.py --spec spec.json --solution Solution.lean --out <dir>
5
+
6
+ `spec.json` holds the hidden reference file, the target theorem names and their weights (see
7
+ arena/core.py). The reward is the weighted share of targets that are proved: stated exactly as
8
+ asked, with no `sorry`, depending only on propext, Classical.choice and Quot.sound, and passing a
9
+ second kernel check by `leanchecker`. A submission that does not compile scores 0.
10
+
11
+ The Lean project (toolchain + Mathlib) is found through $ARENA_LEAN, default: ../lean next to this
12
+ file, then /opt/arena/lean.
13
+ """
14
+ import argparse, json, os, shutil, subprocess, sys, tempfile, time
15
+
16
+ HERE = os.path.dirname(os.path.abspath(__file__))
17
+ TIMEOUT = int(os.environ.get("ARENA_TIMEOUT", "600"))
18
+
19
+ def project():
20
+ for p in (os.environ.get("ARENA_LEAN"), os.path.join(HERE, "..", "lean"), "/opt/arena/lean"):
21
+ if p and os.path.exists(os.path.join(p, "lean-toolchain")): return os.path.abspath(p)
22
+ raise SystemExit("Lean project not found; set ARENA_LEAN")
23
+
24
+ _lp = {}
25
+ def lean_path(proj):
26
+ if proj not in _lp:
27
+ cache = os.path.join(proj, ".lake", "lean_path.txt")
28
+ if os.path.exists(cache): _lp[proj] = open(cache).read().strip()
29
+ else:
30
+ _lp[proj] = subprocess.run(["lake", "env", "printenv", "LEAN_PATH"], cwd=proj, capture_output=True, text=True, check=True).stdout.strip()
31
+ try: open(cache, "w").write(_lp[proj])
32
+ except OSError: pass
33
+ return _lp[proj]
34
+
35
+ class Slot:
36
+ """Optional machine-wide cap on concurrent Lean processes: ARENA_SLOTS=n, ARENA_LOCKDIR=dir."""
37
+ def __enter__(self):
38
+ self.path = None
39
+ n = int(os.environ.get("ARENA_SLOTS", "0"))
40
+ if not n: return self
41
+ d = os.environ.get("ARENA_LOCKDIR", os.path.join(tempfile.gettempdir(), "arena-locks")); os.makedirs(d, exist_ok=True)
42
+ while True:
43
+ for i in range(n):
44
+ p = os.path.join(d, "slot%d" % i)
45
+ try:
46
+ os.mkdir(p); open(os.path.join(p, "pid"), "w").write(str(os.getpid())); self.path = p; return self
47
+ except FileExistsError:
48
+ try:
49
+ pid = int(open(os.path.join(p, "pid")).read()); os.kill(pid, 0)
50
+ except (OSError, ValueError):
51
+ shutil.rmtree(p, ignore_errors=True) # stale
52
+ time.sleep(1)
53
+ def __exit__(self, *a):
54
+ if self.path: shutil.rmtree(self.path, ignore_errors=True)
55
+
56
+ def run(cmd, proj, extra_path=None, timeout=TIMEOUT):
57
+ env = dict(os.environ); env["LEAN_PATH"] = lean_path(proj) + ((":" + extra_path) if extra_path else "")
58
+ with Slot():
59
+ try:
60
+ r = subprocess.run(cmd, cwd=proj, env=env, capture_output=True, text=True, timeout=timeout)
61
+ return r.returncode, (r.stdout + r.stderr)
62
+ except subprocess.TimeoutExpired:
63
+ return 124, "timed out after %d s" % timeout
64
+
65
+ def compile_lean(proj, src, work):
66
+ """Compile work/<src>.lean to work/<src>.olean. Returns (ok, messages)."""
67
+ olean = os.path.join(work, src + ".olean")
68
+ if os.path.exists(olean): os.remove(olean)
69
+ code, out = run(["lean", "--root=" + work, "-o", olean, os.path.join(work, src + ".lean")], proj, work)
70
+ return code == 0 and os.path.exists(olean), out
71
+
72
+ def grade(spec, solution_text, keep=None):
73
+ proj = project(); work = keep or tempfile.mkdtemp(prefix="arena-")
74
+ os.makedirs(work, exist_ok=True)
75
+ targets = spec["targets"]; total = float(sum(t["weight"] for t in targets))
76
+ res = {"reward": 0.0, "stage": "", "targets": [], "log": ""}
77
+ def fail(stage, log):
78
+ res["stage"] = stage; res["log"] = log[-4000:]
79
+ res["targets"] = [{"target": t["name"], "ok": False, "why": stage} for t in targets]
80
+ return res
81
+ try:
82
+ open(os.path.join(work, "Reference.lean"), "w").write(spec["reference"])
83
+ open(os.path.join(work, "Solution.lean"), "w").write(solution_text)
84
+ ok, out = compile_lean(proj, "Reference", work)
85
+ if not ok: return fail("the reference file did not compile (a fault in the task, not in the submission)", out)
86
+ ok, out = compile_lean(proj, "Solution", work)
87
+ if not ok: return fail("the submission does not compile", out)
88
+ code, out = run(["leanchecker", "Solution"], proj, work)
89
+ if code != 0: return fail("the submission fails the kernel re-check", out)
90
+ sub = "Solution"; flags = []
91
+ if spec.get("tests"):
92
+ open(os.path.join(work, "Tests.lean"), "w").write(spec["tests"])
93
+ ok, out = compile_lean(proj, "Tests", work)
94
+ if not ok: return fail("the hidden tests do not pass", out)
95
+ code, out = run(["leanchecker", "Tests"], proj, work)
96
+ if code != 0: return fail("the tests fail the kernel re-check", out)
97
+ sub = "Tests"; flags = ["--native"]
98
+ if spec.get("free"): flags += ["--free", ",".join(spec["free"])]
99
+ verify = os.path.join(HERE, "Verify.lean")
100
+ if not os.path.exists(verify): verify = os.path.join(proj, "verifier", "Verify.lean")
101
+ code, out = run(["lean", "--run", verify] + flags + ["Reference", sub] + [t["name"] for t in targets], proj, work)
102
+ got = {}
103
+ for line in out.splitlines():
104
+ if line.startswith("{"):
105
+ try: j = json.loads(line); got[j["target"]] = j
106
+ except ValueError: pass
107
+ if code != 0 or len(got) != len(targets): return fail("the verifier did not finish", out)
108
+ res["targets"] = [got[t["name"]] for t in targets]
109
+ res["reward"] = round(sum(t["weight"] for t in targets if got[t["name"]]["ok"]) / total, 4)
110
+ res["stage"] = "graded"
111
+ return res
112
+ finally:
113
+ if not keep: shutil.rmtree(work, ignore_errors=True)
114
+
115
+ if __name__ == "__main__":
116
+ ap = argparse.ArgumentParser()
117
+ ap.add_argument("--spec", required=True); ap.add_argument("--solution", required=True); ap.add_argument("--out", default=None)
118
+ a = ap.parse_args()
119
+ spec = json.load(open(a.spec, encoding="utf-8"))
120
+ try: text = open(a.solution, encoding="utf-8").read()
121
+ except OSError: text = None
122
+ res = grade(spec, text) if text is not None else {"reward": 0.0, "stage": "no Solution.lean found", "targets": [], "log": ""}
123
+ print(json.dumps(res, indent=1, ensure_ascii=False))
124
+ if a.out:
125
+ os.makedirs(a.out, exist_ok=True)
126
+ open(os.path.join(a.out, "reward.txt"), "w").write("%g\n" % res["reward"])
127
+ json.dump(res, open(os.path.join(a.out, "result.json"), "w"), indent=1, ensure_ascii=False)
tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/tests/spec.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "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",
3
+ "targets": [
4
+ {
5
+ "name": "det_of_product",
6
+ "weight": 1.0
7
+ }
8
+ ]
9
+ }
tasks/linear-algebra/linear-algebra-det_trace-d1-t0024/tests/test.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/bash
2
+ mkdir -p /logs/verifier
3
+ python3 /tests/grade.py --spec /tests/spec.json --solution /app/Solution.lean --out /logs/verifier || echo 0 > /logs/verifier/reward.txt