fact
stringlengths
18
2.71k
type
stringclasses
5 values
library
stringclasses
4 values
imports
listlengths
0
7
filename
stringclasses
18 values
symbolic_name
stringlengths
3
28
docstring
stringclasses
19 values
SupportedOS where | linux | macos | windows deriving Inhabited, BEq
inductive
root
[ "import Lake" ]
lakefile.lean
SupportedOS
null
getOS ! : SupportedOS := if Platform.isWindows then .windows else if Platform.isOSX then .macos else .linux
def
root
[ "import Lake" ]
lakefile.lean
getOS
null
SupportedArch where | x86_64 | arm64 deriving Inhabited, BEq
inductive
root
[ "import Lake" ]
lakefile.lean
SupportedArch
null
nproc : IO Nat := do let cmd := if getOS! == .windows then "cmd" else "nproc" let args := if getOS! == .windows then #["/c echo %NUMBER_OF_PROCESSORS%"] else #[] let out ← IO.Process.output {cmd := cmd, args := args, stdin := .null} return out.stdout.trim.toNat!
def
root
[ "import Lake" ]
lakefile.lean
nproc
null
getArch ? : IO (Option SupportedArch) := do let cmd := if getOS! == .windows then "cmd" else "uname" let args := if getOS! == .windows then #["/c echo %PROCESSOR_ARCHITECTURE%\n"] else #["-m"] let out ← IO.Process.output {cmd := cmd, args := args, stdin := .null} let arch := out.stdout.trim if arch ∈ ["arm64", "aarch64", "ARM64"] then return some .arm64 else if arch ∈ ["x86_64", "AMD64"] then return some .x86_64 else return none
def
root
[ "import Lake" ]
lakefile.lean
getArch
null
getArch ! : IO SupportedArch := do if let some arch ← getArch? then return arch else error "Unknown architecture"
def
root
[ "import Lake" ]
lakefile.lean
getArch
null
isArm ! : IO Bool := do return (← getArch!) == .arm64
def
root
[ "import Lake" ]
lakefile.lean
isArm
null
hasCUDA : IO Bool := do if getOS! == .windows then let ok ← testProc { cmd := "nvidia-smi" args := #[] } return ok else let out ← IO.Process.output {cmd := "which", args := #["nvcc"], stdin := .null} return out.exitCode == 0
def
root
[ "import Lake" ]
lakefile.lean
hasCUDA
null
useCUDA : IO Bool := do return (get_config? noCUDA |>.isNone) ∧ (← hasCUDA)
def
root
[ "import Lake" ]
lakefile.lean
useCUDA
null
buildArchiveName : String := let arch := if run_io isArm! then "arm64" else "x86_64" let os := if getOS! == .macos then "macOS" else "linux" if run_io useCUDA then s!"{arch}-cuda-{os}.tar.gz" else s!"{arch}-{os}.tar.gz"
def
root
[ "import Lake" ]
lakefile.lean
buildArchiveName
null
SupportedPlatform where os : SupportedOS arch : SupportedArch
structure
root
[ "import Lake" ]
lakefile.lean
SupportedPlatform
null
getPlatform ! : IO SupportedPlatform := do if Platform.numBits != 64 then error "Only 64-bit platforms are supported" return ⟨getOS!, ← getArch!⟩
def
root
[ "import Lake" ]
lakefile.lean
getPlatform
null
copySingleFile (src dst : FilePath) : LogIO Unit := do let cmd := if getOS! == .windows then "cmd" else "cp" let args := if getOS! == .windows then #[s!"/c copy {src.toString.replace "/" "\\"} {dst.toString.replace "/" "\\"}"] else #[src.toString, dst.toString] proc { cmd := cmd args := args }
def
root
[ "import Lake" ]
lakefile.lean
copySingleFile
null
copyFolder (src dst : FilePath) : LogIO Unit := do let cmd := if getOS! == .windows then "robocopy" else "cp" let args := if getOS! == .windows then #[src.toString, dst.toString, "/E"] else #["-r", src.toString, dst.toString] let _out ← rawProc { cmd := cmd args := args }
def
root
[ "import Lake" ]
lakefile.lean
copyFolder
null
removeFolder (dir : FilePath) : LogIO Unit := do let cmd := if getOS! == .windows then "cmd" else "rm" let args := if getOS! == .windows then #[s!"/c rmdir /s /q {dir.toString.replace "/" "\\"}"] else #["-rf", dir.toString] proc { cmd := cmd args := args }
def
root
[ "import Lake" ]
lakefile.lean
removeFolder
null
removeFile (src: FilePath) : LogIO Unit := do proc { cmd := if getOS! == .windows then "cmd" else "rm" args := if getOS! == .windows then #[s!"/c del {src.toString.replace "/" "\\"}"] else #[src.toString] } package LeanCopilot where preferReleaseBuild := get_config? noCloudRelease |>.isNone buildArchive? := buildArchiveName precompileModules := true buildType := BuildType.release moreLinkArgs := #[s!"-L{__dir__}/.lake/build/lib", "-l" ++ if getOS! == .windows then "libctranslate2" else "ctranslate2"] weakLeanArgs := #[s!"--load-dynlib={__dir__}/.lake/build/lib/" ++ nameToSharedLib (if getOS! == .windows then "libctranslate2" else "ctranslate2")] @[default_target] lean_lib LeanCopilot { } lean_lib ModelCheckpointManager { } lean_exe download { root := `ModelCheckpointManager.Main } lean_lib LeanCopilotTests { globs := #[.submodules "LeanCopilotTests".toName] }
def
root
[ "import Lake" ]
lakefile.lean
removeFile
null
nameToVersionedSharedLib (name : String) (v : String) : String := if Platform.isWindows then s!"lib{name}.{v}.dll" else if Platform.isOSX then s!"lib{name}.{v}.dylib" else s!"lib{name}.so.{v}"
def
root
[ "import Lake" ]
lakefile.lean
nameToVersionedSharedLib
null
afterReleaseSync {α : Type} (pkg : Package) (build : SpawnM (Job α)) : FetchM (Job α) := do if pkg.preferReleaseBuild ∧ pkg.name ≠ (← getRootPackage).name then (← pkg.optGitHubRelease.fetch).bindM fun _ => build else build
def
root
[ "import Lake" ]
lakefile.lean
afterReleaseSync
null
afterReleaseAsync {α : Type} (pkg : Package) (build : JobM α) : FetchM (Job α) := do if pkg.preferReleaseBuild ∧ pkg.name ≠ (← getRootPackage).name then (← pkg.optGitHubRelease.fetch).mapM fun _ => build else Job.async build
def
root
[ "import Lake" ]
lakefile.lean
afterReleaseAsync
null
ensureDirExists (dir : FilePath) : IO Unit := do if !(← dir.pathExists) then IO.FS.createDirAll dir
def
root
[ "import Lake" ]
lakefile.lean
ensureDirExists
null
gitClone (url : String) (cwd : Option FilePath) : LogIO Unit := do proc (quiet := true) { cmd := "git" args := if getOS! == .windows then #["clone", url] else #["clone", "--recursive", url] cwd := cwd }
def
root
[ "import Lake" ]
lakefile.lean
gitClone
null
runCmake (root : FilePath) (flags : Array String) : LogIO Unit := do assert! (← root.pathExists) ∧ (← (root / "CMakeLists.txt").pathExists) let buildDir := root / "build" if ← buildDir.pathExists then IO.FS.removeDirAll buildDir IO.FS.createDirAll buildDir let ok ← testProc { cmd := "cmake" args := flags ++ #[".."] cwd := buildDir } if ¬ ok then if flags.contains "-DWITH_CUDNN=ON" then -- Some users may have CUDA but not cuDNN. let ok' ← testProc { cmd := "cmake" args := (flags.erase "-DWITH_CUDNN=ON" |>.push "-DWITH_CUDNN=OFF") ++ #[".."] cwd := buildDir } if ok' then return () error "Failed to run cmake" target libopenblas pkg : FilePath := do afterReleaseAsync pkg do let rootDir := pkg.buildDir / "OpenBLAS" ensureDirExists rootDir let dst := pkg.sharedLibDir / (nameToSharedLib (if getOS! == .windows then "libopenblas" else "openblas")) createParentDirs dst let url := "https://github.com/OpenMathLib/OpenBLAS" let depTrace := Hash.ofString url setTrace depTrace buildFileUnlessUpToDate' dst do if getOS! == .windows then -- For Windows, the binary for OpenBLAS is provided. let _out ← rawProc { cmd := "curl" args := #["-L", "-o", "OpenBLAS.zip", "https://sourceforge.net/projects/openblas/files/v0.3.29/OpenBLAS-0.3.29_x64.zip/download"] cwd := pkg.buildDir } proc { cmd := "tar" args := #["-xvf", "OpenBLAS.zip"] cwd := pkg.buildDir } copySingleFile (pkg.buildDir / "bin" / "libopenblas.dll") (pkg.buildDir / "lib" / "libopenblas.dll") else logInfo s!"Cloning OpenBLAS from {url}" gitClone url pkg.buildDir let numThreads := max 4 $ min 32 (← nproc) let flags := #["NO_LAPACK=1", "NO_FORTRAN=1", s!"-j{numThreads}"] logInfo s!"Building OpenBLAS with `make{flags.foldl (· ++ " " ++ ·) ""}`" proc (quiet := true) { cmd := "make" args := flags cwd := rootDir } copySingleFile (rootDir / nameToSharedLib "openblas") dst -- TODO: Don't hardcode the version "0". let dst' := pkg.sharedLibDir / (nameToVersionedSharedLib "openblas" "0") copySingleFile dst dst' let _ := (← getTrace) return dst
def
root
[ "import Lake" ]
lakefile.lean
runCmake
null
getCt2CmakeFlags : IO (Array String) := do let mut flags := #["-DOPENMP_RUNTIME=NONE", "-DWITH_MKL=OFF"] match getOS! with | .macos => flags := flags ++ #["-DWITH_ACCELERATE=ON", "-DWITH_OPENBLAS=OFF"] | .linux => flags := flags ++ #["-DWITH_ACCELERATE=OFF", "-DWITH_OPENBLAS=ON", "-DOPENBLAS_INCLUDE_DIR=../../OpenBLAS", "-DOPENBLAS_LIBRARY=../../OpenBLAS/libopenblas.so"] | .windows => flags := flags -- [TODO] Temporary fix: Do not use CUDA even if it is available. -- if ← useCUDA then -- flags := flags ++ #["-DWITH_CUDA=ON", "-DWITH_CUDNN=ON"] -- else -- flags := flags ++ #["-DWITH_CUDA=OFF", "-DWITH_CUDNN=OFF"] return flags /- Download and build CTranslate2. Copy its C++ header files to `build/include` and shared libraries to `build/lib` -/ target libctranslate2 pkg : FilePath := do if getOS! == .linux ∨ getOS! == .windows then let openblas ← libopenblas.fetch let _ ← openblas.await afterReleaseAsync pkg do let dst := pkg.sharedLibDir / (nameToSharedLib (if getOS! == .windows then "libctranslate2" else "ctranslate2")) createParentDirs dst let ct2URL := "https://github.com/OpenNMT/CTranslate2" let depTrace := Hash.ofString ct2URL setTrace depTrace buildFileUnlessUpToDate' dst do logInfo s!"Cloning CTranslate2 from {ct2URL}" if !(← (pkg.buildDir / "CTranslate2").pathExists) then let _ ← gitClone ct2URL pkg.buildDir let ct2Dir := pkg.buildDir / "CTranslate2" if getOS! == .windows then ensureDirExists $ ct2Dir / "build" let _out ← rawProc { cmd := "curl" args := #["-L", "-o", "libctranslate2.dll", "https://drive.google.com/uc?export=download&id=1W6ZsbBG8gK9FRoMedNCKkg8qqS-bDa9U"] cwd := ct2Dir / "build" } else let flags ← getCt2CmakeFlags logInfo s!"Configuring CTranslate2 with `cmake{flags.foldl (· ++ " " ++ ·) ""} ..`" runCmake ct2Dir flags let numThreads := max 4 $ min 32 (← nproc) logInfo s!"Building CTranslate2 with `make -j{numThreads}`" proc { cmd := "make" args := #[s!"-j{numThreads}"] cwd := ct2Dir / "build" } ensureDirExists $ pkg.buildDir / "include" copySingleFile (pkg.buildDir / "CTranslate2" / "build" / nameToSharedLib (if getOS! == .windows then "libctranslate2" else "ctranslate2")) dst -- [TODO]: Don't hardcode the version "4". let dst' := pkg.sharedLibDir / (nameToVersionedSharedLib "ctranslate2" "4") copySingleFile dst dst' copyFolder (ct2Dir / "include" / "ctranslate2") (pkg.buildDir / "include" / "ctranslate2") copyFolder (ct2Dir / "include" / "nlohmann") (pkg.buildDir / "include" / "nlohmann") copyFolder (ct2Dir / "include" / "half_float") (pkg.buildDir / "include" / "half_float") removeFolder ct2Dir if getOS! == .windows then removeFolder (pkg.buildDir / "OPENBLAS") removeFile (pkg.buildDir / "OPENBLAS.zip") let _ := (← getTrace) return dst
def
root
[ "import Lake" ]
lakefile.lean
getCt2CmakeFlags
null
buildCpp (pkg : Package) (path : FilePath) (dep : Job FilePath) : SpawnM (Job FilePath) := do let optLevel := if pkg.buildType == .release then "-O3" else "-O0" let flags := #["-fPIC", "-std=c++17", optLevel] let mut args := flags ++ #[ "-I", (← getLeanIncludeDir).toString, "-I", (pkg.buildDir / "include").toString, ] if getOS! == .windows then -- link the headers args := args ++ #[ "-I", (pkg.buildDir / "clang64/include/c++/v1").toString, "-I", (pkg.buildDir / "clang64/include").toString, "-I", (pkg.buildDir / "clang64/lib/clang/20/include").toString, ] let oFile := pkg.buildDir / (path.withExtension "o") let srcJob ← inputTextFile <| pkg.dir / path let leanPath ← Lake.getLeanSysroot buildFileAfterDep oFile (.collectList [srcJob, dep]) (extraDepTrace := computeHash flags) fun deps => compileO oFile deps[0]! args (if getOS! == .windows then s!"{leanPath}/bin/clang.exe" else "c++") target ct2.o pkg : FilePath := do let ct2 ← libctranslate2.fetch if getOS! == .windows then -- download headers from https://repo.msys2.org/mingw/clang64/ proc { cmd := "curl" args := #["-L", "-o", "headers.pkg.tar.zst", "https://repo.msys2.org/mingw/clang64/mingw-w64-clang-x86_64-headers-git-12.0.0.r81.g90abf784a-1-any.pkg.tar.zst"] cwd := pkg.buildDir } proc { cmd := "curl" args := #["-L", "-o", "clang.pkg.tar.zst", "https://repo.msys2.org/mingw/clang64/mingw-w64-clang-x86_64-clang-20.1.3-1-any.pkg.tar.zst"] cwd := pkg.buildDir } proc { cmd := "curl" args := #["-L", "-o", "libcxx.pkg.tar.zst", "https://repo.msys2.org/mingw/clang64/mingw-w64-clang-x86_64-libc%2B%2B-20.1.3-1-any.pkg.tar.zst"] cwd := pkg.buildDir } proc { cmd := "curl" args := #["-L", "-o", "pthread.pkg.tar.zst", "https://repo.msys2.org/mingw/clang64/mingw-w64-clang-x86_64-winpthreads-git-12.0.0.r724.g7e3f2dd90-1-any.pkg.tar.zst"] cwd := pkg.buildDir } proc { cmd := "tar" args := #["-xvf", "clang.pkg.tar.zst"] cwd := pkg.buildDir } proc { cmd := "tar" args := #["-xvf", "headers.pkg.tar.zst"] cwd := pkg.buildDir } proc { cmd := "tar" args := #["-xvf", "libcxx.pkg.tar.zst"] cwd := pkg.buildDir } proc { cmd := "tar" args := #["-xvf", "pthread.pkg.tar.zst"] cwd := pkg.buildDir } let build := buildCpp pkg "cpp/ct2.cpp" ct2 afterReleaseSync pkg build extern_lib libleanffi pkg := do let name := nameToStaticLib "leanffi" let ct2O ← ct2.o.fetch buildStaticLib (pkg.sharedLibDir / name) #[ct2O] require batteries from git "https://github.com/leanprover-community/batteries.git" @ "main" require aesop from git "https://github.com/leanprover-community/aesop" @ "master" meta if get_config? env = some "dev" then -- dev is so not everyone has to build it require «doc-gen4» from git "https://github.com/leanprover/doc-gen4" @ "main"
def
root
[ "import Lake" ]
lakefile.lean
buildCpp
null
suggestion (tac : String) (msgs : MessageLog := {}) : TacticM Suggestion := do -- TODO `addExactSuggestion` has an option to construct `postInfo?` -- Factor that out so we can use it here instead of copying and pasting? let goals ← getGoals let postInfo? ← if goals.isEmpty then pure none else let mut str := "\nRemaining subgoals:" for g in goals do let goalType ← instantiateMVars (← g.getType) let e ← g.withContext do (PrettyPrinter.ppExpr goalType) str := str ++ Format.pretty ("\n⊢ " ++ e) pure (some str) let msg? ← msgs.toList.findM? fun m => do pure <| m.severity == MessageSeverity.information && (← m.data.toString).startsWith "Try this: " let suggestion ← match msg? with | some m => pure <| SuggestionText.string (((← m.data.toString).drop 10).takeWhile (· != '\n')) | none => pure <| SuggestionText.string tac return { suggestion, postInfo? } /-- Run a tactic, returning any new messages rather than adding them to the message log. -/
def
LeanCopilot
[ "import Lean", "import LeanCopilot.Options", "import Lean.Meta.Tactic.TryThis", "import Batteries.Data.MLList.Basic", "import Batteries.Control.Nondet.Basic" ]
LeanCopilot/Frontend.lean
suggestion
/-- Construct a suggestion for a tactic. * Check the passed `MessageLog` for an info message beginning with "Try this: ". * If found, use that as the suggestion. * Otherwise use the provided syntax. * Also, look for remaining goals and pretty print them after the suggestion. -/
withMessageLog (t : TacticM Unit) : TacticM MessageLog := do let initMsgs ← modifyGetThe Core.State fun st => (st.messages, { st with messages := {} }) t modifyGetThe Core.State fun st => (st.messages, { st with messages := initMsgs }) /-- Run a tactic, but revert any changes to info trees. We use this to inhibit the creation of widgets by subsidiary tactics. -/
def
LeanCopilot
[ "import Lean", "import LeanCopilot.Options", "import Lean.Meta.Tactic.TryThis", "import Batteries.Data.MLList.Basic", "import Batteries.Control.Nondet.Basic" ]
LeanCopilot/Frontend.lean
withMessageLog
/-- Run a tactic, returning any new messages rather than adding them to the message log. -/
withoutInfoTrees (t : TacticM Unit) : TacticM Unit := do let trees := (← getInfoState).trees t modifyInfoState fun s => { s with trees } open Lean.Meta.Tactic.TryThis in
def
LeanCopilot
[ "import Lean", "import LeanCopilot.Options", "import Lean.Meta.Tactic.TryThis", "import Batteries.Data.MLList.Basic", "import Batteries.Control.Nondet.Basic" ]
LeanCopilot/Frontend.lean
withoutInfoTrees
/-- Run a tactic, but revert any changes to info trees. We use this to inhibit the creation of widgets by subsidiary tactics. -/
hint (stx : Syntax) (tacStrs : Array String) (check : Bool) : TacticM Unit := do if check then let tacStxs ← tacStrs.filterMapM fun tstr : String => do match runParserCategory (← getEnv) `tactic tstr with | Except.error _ => return none | Except.ok stx => return some (tstr, stx) let tacs := Nondet.ofList tacStxs.toList let results := tacs.filterMapM fun t : (String × Syntax) => do if let some msgs ← observing? (withMessageLog (withoutInfoTrees (evalTactic t.2))) then return some (← getGoals, ← suggestion t.1 msgs) else return none let results ← (results.toMLList.takeUpToFirst fun r => r.1.1.isEmpty).asArray let results := results.qsort (·.1.1.length < ·.1.1.length) addSuggestions stx (results.map (·.1.2)) match results.find? (·.1.1.isEmpty) with | some r => setMCtx r.2.term.meta.meta.mctx | none => admitGoal (← getMainGoal) else let tacsNoCheck : Array Suggestion := tacStrs.map fun tac => { suggestion := SuggestionText.string tac } addSuggestions stx tacsNoCheck
def
LeanCopilot
[ "import Lean", "import LeanCopilot.Options", "import Lean.Meta.Tactic.TryThis", "import Batteries.Data.MLList.Basic", "import Batteries.Control.Nondet.Basic" ]
LeanCopilot/Frontend.lean
hint
/-- Run a tactic, but revert any changes to info trees. We use this to inhibit the creation of widgets by subsidiary tactics. -/
tacGen : Aesop.TacGen := fun (mvarId : MVarId) => do let state ← ppTacticState [mvarId] let nm ← SuggestTactics.getGeneratorName let model ← getGenerator nm let suggestions ← generate model state "" -- A temporary workaround to prevent the tactic from using the current theorem. -- TODO: Use a more principled way, e.g., see `Lean4Repl.lean` in `LeanDojo`. if let some declName := (← liftM (m := MetaM) <| Term.TermElabM.run getDeclName?).1 then let theoremName := match declName.toString with | "_example" => "" | n => n.splitOn "." |>.getLast! let theoremNameMatcher := String.Matcher.ofString theoremName let filteredSuggestions := suggestions.filterMap fun ((t, s) : String × Float) => let isAesop := t == "aesop" let isSelfReference := ¬ (theoremName == "") ∧ (theoremNameMatcher.find? t |>.isSome) if isSelfReference ∨ isAesop then none else some (t, s) return filteredSuggestions else let filteredSuggestions := suggestions.filterMap fun ((t, s) : String × Float) => let isAesop := t == "aesop" if isAesop then none else some (t, s) return filteredSuggestions macro "#configure_llm_aesop" : command => `(@[aesop 100%] def tacGen := LeanCopilot.tacGen) macro "search_proof" : tactic => `(tactic| aesop? (add 100% tacGen))
def
LeanCopilot
[ "import LeanCopilot.Tactics", "import LeanCopilot.Options", "import Batteries.Data.String.Basic", "import Aesop" ]
LeanCopilot/LlmAesop.lean
tacGen
null
isVerbose : m Bool := do match LeanCopilot.verbose.get? (← getOptions) with | some true => return true | _ => return false namespace SuggestTactics register_option LeanCopilot.suggest_tactics.check : Bool := { defValue := true descr := "Whether to run the generated tactics." }
def
LeanCopilot
[ "import Lean", "import LeanCopilot.Models" ]
LeanCopilot/Options.lean
isVerbose
null
checkTactics : CoreM Bool := do match LeanCopilot.suggest_tactics.check.get? (← getOptions) with | some false => return false | _ => return true register_option LeanCopilot.suggest_tactics.model : String := { defValue := Builtin.generator.name }
def
LeanCopilot
[ "import Lean", "import LeanCopilot.Models" ]
LeanCopilot/Options.lean
checkTactics
null
getGeneratorName : m String := do match LeanCopilot.suggest_tactics.model.get? (← getOptions) with | some n => return n | _ => return Builtin.generator.name
def
LeanCopilot
[ "import Lean", "import LeanCopilot.Models" ]
LeanCopilot/Options.lean
getGeneratorName
null
getNumPremises : m Nat := do match LeanCopilot.select_premises.k.get? (← getOptions) with | some k => return k | _ => return 16
def
LeanCopilot
[ "import Lean", "import LeanCopilot.Models" ]
LeanCopilot/Options.lean
getNumPremises
null
ppTacticState : List MVarId → MetaM String | [] => return "no goals" | [g] => return (← Meta.ppGoal g).pretty | goals => return (← goals.foldlM (init := "") (fun a b => do return s!"{a}\n\n{(← Meta.ppGoal b).pretty}")).trim /-- Pretty-print the current tactic state. -/
def
LeanCopilot
[ "import Lean", "import LeanCopilot.Options", "import LeanCopilot.Frontend", "import Aesop.Util.Basic", "import Batteries.Data.String.Basic", "import Batteries.Data.String.Matcher" ]
LeanCopilot/Tactics.lean
ppTacticState
/-- Pretty-print a list of goals. -/
getPpTacticState : TacticM String := do let goals ← getUnsolvedGoals ppTacticState goals open SuggestTactics in /-- Generate a list of tactic suggestions. -/
def
LeanCopilot
[ "import Lean", "import LeanCopilot.Options", "import LeanCopilot.Frontend", "import Aesop.Util.Basic", "import Batteries.Data.String.Basic", "import Batteries.Data.String.Matcher" ]
LeanCopilot/Tactics.lean
getPpTacticState
/-- Pretty-print the current tactic state. -/
suggestTactics (targetPrefix : String) : TacticM (Array (String × Float)) := do let state ← getPpTacticState let nm ← getGeneratorName let model ← getGenerator nm let suggestions ← generate model state targetPrefix -- A temporary workaround to prevent the tactic from using the current theorem. -- TODO: Use a more principled way, e.g., see `Lean4Repl.lean` in `LeanDojo`. if let some declName ← getDeclName? then let theoremName := match declName.toString with | "_example" => "" | n => n.splitOn "." |>.getLast! let theoremNameMatcher := String.Matcher.ofString theoremName if ← isVerbose then logInfo s!"State:\n{state}" logInfo s!"Theorem name:\n{theoremName}" let filteredSuggestions := suggestions.filterMap fun ((t, s) : String × Float) => let isAesop := t == "aesop" let isSelfReference := ¬ (theoremName == "") ∧ (theoremNameMatcher.find? t |>.isSome) if isSelfReference ∨ isAesop then none else some (t, s) return filteredSuggestions else let filteredSuggestions := suggestions.filterMap fun ((t, s) : String × Float) => let isAesop := t == "aesop" if isAesop then none else some (t, s) return filteredSuggestions /-- Information of a premise. -/
def
LeanCopilot
[ "import Lean", "import LeanCopilot.Options", "import LeanCopilot.Frontend", "import Aesop.Util.Basic", "import Batteries.Data.String.Basic", "import Batteries.Data.String.Matcher" ]
LeanCopilot/Tactics.lean
suggestTactics
/-- Generate a list of tactic suggestions. -/
PremiseInfo where name : String path : String code : String score : Float /-- Annotate a premise with its type, doc string, import module path, and definition code. -/
structure
LeanCopilot
[ "import Lean", "import LeanCopilot.Options", "import LeanCopilot.Frontend", "import Aesop.Util.Basic", "import Batteries.Data.String.Basic", "import Batteries.Data.String.Matcher" ]
LeanCopilot/Tactics.lean
PremiseInfo
/-- Information of a premise. -/
annotatePremise (pi : PremiseInfo) : MetaM String := do let declName := pi.name.toName try let info ← getConstInfo declName let premise_type ← Meta.ppExpr info.type let some doc_str ← findDocString? (← getEnv) declName | return s!"{pi.name} : {premise_type}\n" return s!"{pi.name} : {premise_type}\n```doc\n{doc_str}\n```\n" catch _ => return s!"{pi.name} needs to be imported from `{pi.path}`.\n```code\n{pi.code}\n```\n" /-- Retrieve a list of premises given a query. -/
def
LeanCopilot
[ "import Lean", "import LeanCopilot.Options", "import LeanCopilot.Frontend", "import Aesop.Util.Basic", "import Batteries.Data.String.Basic", "import Batteries.Data.String.Matcher" ]
LeanCopilot/Tactics.lean
annotatePremise
/-- Annotate a premise with its type, doc string, import module path, and definition code. -/
retrieve (input : String) : TacticM (Array PremiseInfo) := do if ¬ (← premiseEmbeddingsInitialized) ∧ ¬ (← initPremiseEmbeddings .auto) then throwError "Cannot initialize premise embeddings" if ¬ (← premiseDictionaryInitialized) ∧ ¬ (← initPremiseDictionary) then throwError "Cannot initialize premise dictionary" let k ← SelectPremises.getNumPremises let query ← encode Builtin.encoder input let rawPremiseInfo := FFI.retrieve query k.toUInt64 let premiseInfo : Array PremiseInfo := rawPremiseInfo.map fun (name, path, code, score) => { name := name, path := path, code := code, score := score } return premiseInfo /-- Retrieve a list of premises using the current pretty-printed tactic state as the query. -/
def
LeanCopilot
[ "import Lean", "import LeanCopilot.Options", "import LeanCopilot.Frontend", "import Aesop.Util.Basic", "import Batteries.Data.String.Basic", "import Batteries.Data.String.Matcher" ]
LeanCopilot/Tactics.lean
retrieve
/-- Retrieve a list of premises given a query. -/
selectPremises : TacticM (Array PremiseInfo) := do retrieve (← getPpTacticState) syntax "pp_state" : tactic syntax "suggest_tactics" : tactic syntax "suggest_tactics" str : tactic syntax "select_premises" : tactic macro_rules | `(tactic | suggest_tactics%$tac) => `(tactic | suggest_tactics%$tac "") elab_rules : tactic | `(tactic | pp_state) => do let state ← getPpTacticState logInfo state | `(tactic | suggest_tactics%$tac $pfx:str) => do let (tacticsWithScores, elapsed) ← Aesop.time $ suggestTactics pfx.getString if ← isVerbose then logInfo s!"{elapsed.printAsMillis} for generating {tacticsWithScores.size} tactics" let tactics := tacticsWithScores.map (·.1) if ← isVerbose then logInfo s!"Tactics: {tactics}" let range : Lean.Syntax.Range := { start := tac.getRange?.get!.start, stop := pfx.raw.getRange?.get!.stop } let ref := Syntax.ofRange range hint ref tactics (← SuggestTactics.checkTactics) | `(tactic | select_premises) => do let premisesWithInfoAndScores ← selectPremises let rankedPremisesWithInfoAndScores := premisesWithInfoAndScores.qsort (·.score > ·.score) let richPremises ← Meta.liftMetaM $ (rankedPremisesWithInfoAndScores.mapM annotatePremise) let richPremisesExpand := richPremises.foldl (init := "") (· ++ · ++ "\n") logInfo richPremisesExpand
def
LeanCopilot
[ "import Lean", "import LeanCopilot.Options", "import LeanCopilot.Frontend", "import Aesop.Util.Basic", "import Batteries.Data.String.Basic", "import Batteries.Data.String.Matcher" ]
LeanCopilot/Tactics.lean
selectPremises
/-- Retrieve a list of premises using the current pretty-printed tactic state as the query. -/
reprover : NativeGenerator := { url := Url.parse! "https://huggingface.co/kaiyuy/ct2-leandojo-lean4-tacgen-byt5-small" tokenizer := ByT5.tokenizer params := { numReturnSequences := 1 } } #eval generate reprover "n : ℕ\n⊢ gcd n n = n"
def
LeanCopilotTests
[ "import LeanCopilot" ]
LeanCopilotTests/ModelAPIs.lean
reprover
/-- ReProver's tactic generator in CT2 format. -/
reprover' : NativeGenerator := {reprover with device := .cpu computeType := .float32 params := {numReturnSequences := 4} } #eval generate reprover' "n : ℕ\n⊢ gcd n n = n" /-- The original ByT5 checkpoint in CT2 format. -/
def
LeanCopilotTests
[ "import LeanCopilot" ]
LeanCopilotTests/ModelAPIs.lean
reprover'
/-- ReProver's tactic generator in CT2 format. -/
byt5 : NativeGenerator := { url := Url.parse! "https://huggingface.co/kaiyuy/ct2-byt5-small" tokenizer := ByT5.tokenizer params := { numReturnSequences := 1 } } #eval generate byt5 "Hello, world!" /-- ReProver's retriever encoder in CT2 format. -/
def
LeanCopilotTests
[ "import LeanCopilot" ]
LeanCopilotTests/ModelAPIs.lean
byt5
/-- The original ByT5 checkpoint in CT2 format. -/
reproverEncoder : NativeEncoder := { url := Url.parse! "https://huggingface.co/kaiyuy/ct2-leandojo-lean4-retriever-byt5-small" tokenizer := ByT5.tokenizer } #eval encode reproverEncoder "n : ℕ\n⊢ gcd n n = n" /-- Arbitrary generator you can define. -/
def
LeanCopilotTests
[ "import LeanCopilot" ]
LeanCopilotTests/ModelAPIs.lean
reproverEncoder
/-- ReProver's retriever encoder in CT2 format. -/
dummyGenerator : GenericGenerator where generate _ _ := return #[⟨"Hello, world!", 0.5⟩, ("Hi!", 0.3)] #eval generate dummyGenerator "n : ℕ\n⊢ gcd n n = n" /-- Arbitrary encoder you can define. -/
def
LeanCopilotTests
[ "import LeanCopilot" ]
LeanCopilotTests/ModelAPIs.lean
dummyGenerator
/-- Arbitrary generator you can define. -/
dummyEncoder : GenericEncoder where encode _ := return FloatArray.mk #[1, 2, 3] #eval encode dummyEncoder "Hi!" /- External Models 1. Make sure the model is up and running, e.g., by going to ./python and running `uvicorn server:app --port 23337`. 2. Uncomment the code below. -/ /- /-- https://huggingface.co/wellecks/llmstep-mathlib4-pythia2.8b -/
def
LeanCopilotTests
[ "import LeanCopilot" ]
LeanCopilotTests/ModelAPIs.lean
dummyEncoder
/-- Arbitrary encoder you can define. -/
pythia : ExternalGenerator := { name := "wellecks/llmstep-mathlib4-pythia2.8b" host := "localhost" port := 23337 } #eval generate pythia "n : ℕ\n⊢ gcd n n = n" /-- ReProver's retriever encoder as an external model. -/
def
LeanCopilotTests
[ "import LeanCopilot" ]
LeanCopilotTests/ModelAPIs.lean
pythia
/-- https://huggingface.co/wellecks/llmstep-mathlib4-pythia2.8b -/
reproverExternalEncoder : ExternalEncoder := { name := "kaiyuy/leandojo-lean4-retriever-byt5-small" host := "localhost" port := 23337 } -- Go to ./python and run `uvicorn server:app --port 23337` #eval encode reproverExternalEncoder "n : ℕ\n⊢ gcd n n = n" /-- General-purpose LLM apis: openai, claude, etc. -/
def
LeanCopilotTests
[ "import LeanCopilot" ]
LeanCopilotTests/ModelAPIs.lean
reproverExternalEncoder
/-- ReProver's retriever encoder as an external model. -/
gpt4 : ExternalGenerator := { name := "gpt4" host := "localhost" port := 23337 } #eval generate gpt4 "n : ℕ\n⊢ gcd n n = n" /-- Math LLMs: InternLM, Deepseekmath, etc. -/
def
LeanCopilotTests
[ "import LeanCopilot" ]
LeanCopilotTests/ModelAPIs.lean
gpt4
/-- General-purpose LLM apis: openai, claude, etc. -/
internLM : ExternalGenerator := { name := "InternLM" host := "localhost" port := 23337 } #eval generate internLM "n : ℕ\n⊢ gcd n n = n" -/ /-
def
LeanCopilotTests
[ "import LeanCopilot" ]
LeanCopilotTests/ModelAPIs.lean
internLM
/-- Math LLMs: InternLM, Deepseekmath, etc. -/
kimina : ExternalGenerator := { name := "kimina" host := "localhost" port := 23337 } #eval generate kimina "n : ℕ\n⊢ gcd n n = n" -/
def
LeanCopilotTests
[ "import LeanCopilot" ]
LeanCopilotTests/ModelAPIs.lean
kimina
/-- Math LLMs: InternLM, Deepseekmath, etc. -/
params := {Builtin.generator.params with numReturnSequences := 4 minLength := 100 lengthPenalty := 1.0 temperature := 0.5 }
def
LeanCopilotTests
[ "import LeanCopilot" ]
LeanCopilotTests/TacticSuggestion.lean
params
null
updatedModel := {Builtin.generator with params := params} #eval getModelRegistry #eval registerGenerator "updatedModel" (.native updatedModel) #eval getModelRegistry set_option LeanCopilot.suggest_tactics.model "updatedModel" in
def
LeanCopilotTests
[ "import LeanCopilot" ]
LeanCopilotTests/TacticSuggestion.lean
updatedModel
null
myModel : ExternalGenerator := { name := "wellecks/llmstep-mathlib4-pythia2.8b" host := "localhost" port := 23337 } #eval registerGenerator "wellecks/llmstep-mathlib4-pythia2.8b" (.external myModel) set_option LeanCopilot.suggest_tactics.check false in set_option LeanCopilot.suggest_tactics.model "wellecks/llmstep-mathlib4-pythia2.8b" in
def
LeanCopilotTests
[ "import LeanCopilot" ]
LeanCopilotTests/TacticSuggestion.lean
myModel
null
SupportedOS where | linux | macos | windows deriving Inhabited, BEq
inductive
ModelCheckpointManager
[ "import ModelCheckpointManager.Url" ]
ModelCheckpointManager/Download.lean
SupportedOS
null
getOS ! : SupportedOS := if System.Platform.isWindows then .windows else if System.Platform.isOSX then .macos else .linux
def
ModelCheckpointManager
[ "import ModelCheckpointManager.Url" ]
ModelCheckpointManager/Download.lean
getOS
null
ensureDirExists (dir : FilePath) : IO Unit := do if ¬ (← dir.pathExists) then IO.FS.createDirAll dir
def
ModelCheckpointManager
[ "import ModelCheckpointManager.Url" ]
ModelCheckpointManager/Download.lean
ensureDirExists
null
getHomeDir : IO FilePath := do let home := if getOS! == .windows then "USERPROFILE" else "HOME" let some dir ← IO.getEnv home | throw $ IO.userError s!"Cannot find the ${home} environment variable." return dir
def
ModelCheckpointManager
[ "import ModelCheckpointManager.Url" ]
ModelCheckpointManager/Download.lean
getHomeDir
null
getDefaultCacheDir : IO FilePath := do return (← getHomeDir) / ".cache/lean_copilot/models"
def
ModelCheckpointManager
[ "import ModelCheckpointManager.Url" ]
ModelCheckpointManager/Download.lean
getDefaultCacheDir
null
getCacheDir : IO FilePath := do let defaultCacheDir ← getDefaultCacheDir let dir := match ← IO.getEnv "LEAN_COPILOT_CACHE_DIR" with | some dir => (dir : FilePath) | none => defaultCacheDir ensureDirExists dir return dir.normalize
def
ModelCheckpointManager
[ "import ModelCheckpointManager.Url" ]
ModelCheckpointManager/Download.lean
getCacheDir
null
getModelDir (url : Url) : IO FilePath := do return (← getCacheDir) / url.hostname / url.path |>.normalize
def
ModelCheckpointManager
[ "import ModelCheckpointManager.Url" ]
ModelCheckpointManager/Download.lean
getModelDir
null
isUpToDate (url : Url) : IO Bool := do let dir := ← getModelDir url if ¬ (← dir.pathExists) then return false let _ ← IO.Process.run { cmd := "git" args := #["fetch", "--quiet", "--all"] cwd := dir } let branch := (← IO.Process.run { cmd := "git" args := #["symbolic-ref", "refs/remotes/origin/HEAD","--short"] cwd := dir }).trim let hasRemoteChange := (← IO.Process.run { cmd := "git" args := #["diff", (branch.splitOn "/")[1]!, branch, "--shortstat"] cwd := dir }).trim != "" return ¬hasRemoteChange
def
ModelCheckpointManager
[ "import ModelCheckpointManager.Url" ]
ModelCheckpointManager/Download.lean
isUpToDate
null
initGitLFS : IO Unit := do let proc ← IO.Process.output { cmd := "git" args := #["lfs", "install"] } if proc.exitCode != 0 then throw $ IO.userError "Failed to initialize Git LFS. Please install it."
def
ModelCheckpointManager
[ "import ModelCheckpointManager.Url" ]
ModelCheckpointManager/Download.lean
initGitLFS
null
downloadUnlessUpToDate (url : Url) : IO Unit := do let dir := ← getModelDir url if ← isUpToDate url then println! s!"The model is available at {dir}" return println! s!"Downloading the model into {dir}" if ← dir.pathExists then IO.FS.removeDirAll dir let some parentDir := dir.parent | unreachable! IO.FS.createDirAll parentDir initGitLFS let proc ← IO.Process.output { cmd := "git" args := #["clone", toString url] cwd := parentDir } if proc.exitCode != 0 then throw $ IO.userError s!"Failed to download the model. You can download it manually from {url} and store it in `{dir}/`. See https://huggingface.co/docs/hub/models-downloading for details."
def
ModelCheckpointManager
[ "import ModelCheckpointManager.Url" ]
ModelCheckpointManager/Download.lean
downloadUnlessUpToDate
null
builtinModelUrls : List String := [ "https://huggingface.co/kaiyuy/ct2-leandojo-lean4-tacgen-byt5-small", "https://huggingface.co/kaiyuy/ct2-leandojo-lean4-retriever-byt5-small", "https://huggingface.co/kaiyuy/premise-embeddings-leandojo-lean4-retriever-byt5-small", "https://huggingface.co/kaiyuy/ct2-byt5-small" ]
def
ModelCheckpointManager
[ "import ModelCheckpointManager.Url", "import ModelCheckpointManager.Download" ]
ModelCheckpointManager/Main.lean
builtinModelUrls
null
main (args : List String) : IO Unit := do let mut tasks := #[] let urls := Url.parse! <$> (if args.isEmpty then builtinModelUrls else args) for url in urls do tasks := tasks.push $ ← IO.asTask $ downloadUnlessUpToDate url for t in tasks do match ← IO.wait t with | Except.error e => throw e | Except.ok _ => pure () println! "Done!"
def
ModelCheckpointManager
[ "import ModelCheckpointManager.Url", "import ModelCheckpointManager.Download" ]
ModelCheckpointManager/Main.lean
main
null
Url where protocol : String hostname : String path : FilePath deriving Inhabited, Repr namespace Url
structure
ModelCheckpointManager
[]
ModelCheckpointManager/Url.lean
Url
null
isValid (url : Url) : Bool := ¬ url.protocol.isEmpty ∧ ¬ url.hostname.isEmpty ∧ ¬ url.path.toString.isEmpty ∧ url.path.isRelative ∧ url.path.fileName.isSome
def
ModelCheckpointManager
[]
ModelCheckpointManager/Url.lean
isValid
null
toString (url : Url) : String := assert! isValid url s!"{url.protocol}://{url.hostname}/{url.path}"
def
ModelCheckpointManager
[]
ModelCheckpointManager/Url.lean
toString
null
parse (s : String) : Option Url := let parts := s.splitOn "://" if h : parts.length != 2 then none else have : parts.length > 1 := by by_cases h' : parts.length = 2 · rw [h'] apply Nat.lt_succ_of_le simp · simp_all have : parts.length > 0 := by apply Nat.lt_of_succ_lt assumption let protocol := parts[0] match parts[1].splitOn "/" with | hostname :: path => let path := FilePath.mk $ "/".intercalate path let url : Url := ⟨protocol, hostname, path⟩ if url.isValid then some url else none | _ => none
def
ModelCheckpointManager
[]
ModelCheckpointManager/Url.lean
parse
null
parse ! (s : String) : Url := match parse s with | some url => url | none => panic! "Invalid url: {s}"
def
ModelCheckpointManager
[]
ModelCheckpointManager/Url.lean
parse
null
name ! (url : Url) : String := url.path.fileName.get!
def
ModelCheckpointManager
[]
ModelCheckpointManager/Url.lean
name
null
url₁ := parse! "https://huggingface.co/kaiyuy/ct2-leandojo-lean4-tacgen-byt5-small"
def
ModelCheckpointManager
[]
ModelCheckpointManager/Url.lean
url₁
null
url₂ := parse! "https://huggingface.co/bert-base-uncased" #eval url₁ #eval url₂ #eval url₁.name! #eval url₂.name!
def
ModelCheckpointManager
[]
ModelCheckpointManager/Url.lean
url₂
null
generator : NativeGenerator := { url := Url.parse! "https://huggingface.co/kaiyuy/ct2-leandojo-lean4-tacgen-byt5-small" tokenizer := ByT5.tokenizer params := { numReturnSequences := 32 } }
def
LeanCopilot
[ "import ModelCheckpointManager", "import LeanCopilot.Models.ByT5" ]
LeanCopilot/Models/Builtin.lean
generator
null
encoder : NativeEncoder := { url := Url.parse! "https://huggingface.co/kaiyuy/ct2-leandojo-lean4-retriever-byt5-small" tokenizer := ByT5.tokenizer }
def
LeanCopilot
[ "import ModelCheckpointManager", "import LeanCopilot.Models.ByT5" ]
LeanCopilot/Models/Builtin.lean
encoder
null
premisesUrl := Url.parse! "https://huggingface.co/kaiyuy/premise-embeddings-leandojo-lean4-retriever-byt5-small"
def
LeanCopilot
[ "import ModelCheckpointManager", "import LeanCopilot.Models.ByT5" ]
LeanCopilot/Models/Builtin.lean
premisesUrl
null
vocab : Array String := #[ "\u0000", "\u0001", "\u0002", "\u0003", "\u0004", "\u0005", "\u0006", "\u0007", "\\b", "\t", "\n", "\u000b", "\\f", "\r", "\u000e", "\u000f", "\u0010", "\u0011", "\u0012", "\u0013", "\u0014", "\u0015", "\u0016", "\u0017", "\u0018", "\u0019", "\u001a", "\u001b", "\u001c", "\u001d", "\u001e", "\u001f", " ", "!", "\"", "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ":", ";", "<", "=", ">", "?", "@", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "[", "\\", "]", "^", "_", "`", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "{", "|", "}", "~", "\u007f", "\u0080", "\u0081", "\u0082", "\u0083", "\u0084", "\u0085", "\u0086", "\u0087", "\u0088", "\u0089", "\u008a", "\u008b", "\u008c", "\u008d", "\u008e", "\u008f", "\u0090", "\u0091", "\u0092", "\u0093", "\u0094", "\u0095", "\u0096", "\u0097", "\u0098", "\u0099", "\u009a", "\u009b", "\u009c", "\u009d", "\u009e", "\u009f", "\u00a0", "\u00a1", "\u00a2", "\u00a3", "\u00a4", "\u00a5", "\u00a6", "\u00a7", "\u00a8", "\u00a9", "\u00aa", "\u00ab", "\u00ac", "\u00ad", "\u00ae", "\u00af", "\u00b0", "\u00b1", "\u00b2", "\u00b3", "\u00b4", "\u00b5", "\u00b6", "\u00b7", "\u00b8", "\u00b9", "\u00ba", "\u00bb", "\u00bc", "\u00bd", "\u00be", "\u00bf", "\u00c0", "\u00c1", "\u00c2", "\u00c3", "\u00c4", "\u00c5", "\u00c6", "\u00c7", "\u00c8", "\u00c9", "\u00ca", "\u00cb", "\u00cc", "\u00cd", "\u00ce", "\u00cf", "\u00d0", "\u00d1", "\u00d2", "\u00d3", "\u00d4", "\u00d5", "\u00d6", "\u00d7", "\u00d8", "\u00d9", "\u00da", "\u00db", "\u00dc", "\u00dd", "\u00de", "\u00df", "\u00e0", "\u00e1", "\u00e2", "\u00e3", "\u00e4", "\u00e5", "\u00e6", "\u00e7", "\u00e8", "\u00e9", "\u00ea", "\u00eb", "\u00ec", "\u00ed", "\u00ee", "\u00ef", "\u00f0", "\u00f1", "\u00f2", "\u00f3", "\u00f4", "\u00f5", "\u00f6", "\u00f7", "\u00f8", "\u00f9", "\u00fa", "\u00fb", "\u00fc", "\u00fd", "\u00fe", "\u00ff" ]
def
LeanCopilot
[ "import LeanCopilot.Models.Native" ]
LeanCopilot/Models/ByT5.lean
vocab
null
byteToToken (b : UInt8) : String := vocab[b.toNat]!
def
LeanCopilot
[ "import LeanCopilot.Models.Native" ]
LeanCopilot/Models/ByT5.lean
byteToToken
null
tokenToByte ! (t : String) : UInt8 := vocab.findIdx? (· = t) |>.get! |>.toUInt8
def
LeanCopilot
[ "import LeanCopilot.Models.Native" ]
LeanCopilot/Models/ByT5.lean
tokenToByte
null
tokenize (text : String) : Array String := (byteToToken <$> text.toUTF8.toList).toArray
def
LeanCopilot
[ "import LeanCopilot.Models.Native" ]
LeanCopilot/Models/ByT5.lean
tokenize
null
detokenize (tokens : Array String) : String := match (String.fromUTF8? ⟨tokens.map tokenToByte!⟩) with | some s => s | none => ""
def
LeanCopilot
[ "import LeanCopilot.Models.Native" ]
LeanCopilot/Models/ByT5.lean
detokenize
null
eosToken := "</s>"
def
LeanCopilot
[ "import LeanCopilot.Models.Native" ]
LeanCopilot/Models/ByT5.lean
eosToken
null
tokenizer : Tokenizer := { tokenize := tokenize, detokenize := detokenize, eosToken := eosToken }
def
LeanCopilot
[ "import LeanCopilot.Models.Native" ]
LeanCopilot/Models/ByT5.lean
tokenizer
null
ExternalModel where name : String host : String := "localhost" port : UInt16 := 23337 deriving Inhabited, Repr
structure
LeanCopilot
[ "import Lean", "import LeanCopilot.Models.Interface" ]
LeanCopilot/Models/External.lean
ExternalModel
null
ExternalGenerator extends ExternalModel deriving Repr
structure
LeanCopilot
[ "import Lean", "import LeanCopilot.Models.Interface" ]
LeanCopilot/Models/External.lean
ExternalGenerator
null
GeneratorRequest where name : String input : String «prefix» : String deriving ToJson
structure
LeanCopilot
[ "import Lean", "import LeanCopilot.Models.Interface" ]
LeanCopilot/Models/External.lean
GeneratorRequest
null
Generation where output: String score: Float deriving FromJson
structure
LeanCopilot
[ "import Lean", "import LeanCopilot.Models.Interface" ]
LeanCopilot/Models/External.lean
Generation
null
GeneratorResponse where outputs : Array Generation deriving FromJson
structure
LeanCopilot
[ "import Lean", "import LeanCopilot.Models.Interface" ]
LeanCopilot/Models/External.lean
GeneratorResponse
null
EnencoderRequest where name : String input : String deriving ToJson
structure
LeanCopilot
[ "import Lean", "import LeanCopilot.Models.Interface" ]
LeanCopilot/Models/External.lean
EnencoderRequest
null
EncoderResponse where outputs : Array Float deriving FromJson
structure
LeanCopilot
[ "import Lean", "import LeanCopilot.Models.Interface" ]
LeanCopilot/Models/External.lean
EncoderResponse
null
send {α β : Type} [ToJson α] [FromJson β] (req : α) (url : String) : IO β := do let reqStr := (toJson req).pretty 99999999999999999 let out ← IO.Process.output { cmd := "curl" args := #["-X", "POST", url, "-H", "accept: application/json", "-H", "Content-Type: application/json", "-d", reqStr] } if out.exitCode != 0 then throw $ IO.userError s!"Request failed. Please check if the server is up at `{url}`." let some json := Json.parse out.stdout |>.toOption | throw $ IO.userError "Failed to parse response" let some res := (fromJson? json : Except String β) |>.toOption | throw $ IO.userError "Failed to parse response" return res
def
LeanCopilot
[ "import Lean", "import LeanCopilot.Models.Interface" ]
LeanCopilot/Models/External.lean
send
null
ExternalGenerator.generate (model : ExternalGenerator) (input : String) (targetPrefix : String) : IO $ Array (String × Float) := do let url := s!"http://{model.host}:{model.port}/generate" let req : GeneratorRequest := { name := model.name, input := input, «prefix» := targetPrefix } let res : GeneratorResponse ← send req url return res.outputs.map fun g => (g.output, g.score)
def
LeanCopilot
[ "import Lean", "import LeanCopilot.Models.Interface" ]
LeanCopilot/Models/External.lean
ExternalGenerator.generate
null
ExternalEncoder extends ExternalModel deriving Repr
structure
LeanCopilot
[ "import Lean", "import LeanCopilot.Models.Interface" ]
LeanCopilot/Models/External.lean
ExternalEncoder
null
ExternalEncoder.encode (model : ExternalEncoder) (input : String) : IO FloatArray := do let url := s!"http://{model.host}:{model.port}/encode" let req : EnencoderRequest := { name := model.name, input := input, } let res : EncoderResponse ← send req url return FloatArray.mk res.outputs
def
LeanCopilot
[ "import Lean", "import LeanCopilot.Models.Interface" ]
LeanCopilot/Models/External.lean
ExternalEncoder.encode
null
isGeneratorInitialized : (name : @& String) → Bool @[extern "is_encoder_initialized"]
opaque
LeanCopilot
[ "import Lean", "import LeanCopilot.Models.Interface", "import LeanCopilot.Models.Native", "import LeanCopilot.Models.Builtin" ]
LeanCopilot/Models/FFI.lean
isGeneratorInitialized
null
isEncoderInitialized : (name : @& String) → Bool @[extern "init_generator"]
opaque
LeanCopilot
[ "import Lean", "import LeanCopilot.Models.Interface", "import LeanCopilot.Models.Native", "import LeanCopilot.Models.Builtin" ]
LeanCopilot/Models/FFI.lean
isEncoderInitialized
null
initGenerator (name : @& String) (modelPath : @& String) (computeType : @& String) (device : @& String) (deviceIndex : @& Array UInt64) : Bool @[extern "init_encoder"]
opaque
LeanCopilot
[ "import Lean", "import LeanCopilot.Models.Interface", "import LeanCopilot.Models.Native", "import LeanCopilot.Models.Builtin" ]
LeanCopilot/Models/FFI.lean
initGenerator
null
initEncoder (name : @& String) (modelPath : @& String) (computeType : @& String) (device : @& String) (deviceIndex : @& Array UInt64) : Bool @[extern "generate"]
opaque
LeanCopilot
[ "import Lean", "import LeanCopilot.Models.Interface", "import LeanCopilot.Models.Native", "import LeanCopilot.Models.Builtin" ]
LeanCopilot/Models/FFI.lean
initEncoder
null
generate (name : @& String) (inputTokens : @& Array String) (targetPrefixTokens : @& Array String) (numReturnSequences : UInt64) (beamSize : UInt64) (minLength : UInt64) (maxLength : UInt64) (lengthPenalty : Float) (patience : Float) (temperature : Float) : Array (Array String × Float) @[extern "encode"]
opaque
LeanCopilot
[ "import Lean", "import LeanCopilot.Models.Interface", "import LeanCopilot.Models.Native", "import LeanCopilot.Models.Builtin" ]
LeanCopilot/Models/FFI.lean
generate
null