lcode-cli 0.56.0__py3-none-any.whl → 0.58.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
lcode/__init__.py CHANGED
@@ -3,7 +3,7 @@
3
3
  From a program: `from lcode import Session` (see lcode.api).
4
4
  """
5
5
 
6
- __version__ = "0.56.0"
6
+ __version__ = "0.58.0"
7
7
 
8
8
  API = ("Session", "Result", "Options", "SetupError")
9
9
 
lcode/bench.py CHANGED
@@ -19,6 +19,7 @@ import subprocess
19
19
  import sys
20
20
  import tempfile
21
21
  import time
22
+ from collections import Counter
22
23
  from collections.abc import Callable, Iterator
23
24
  from contextlib import contextmanager
24
25
  from dataclasses import asdict, dataclass, field
@@ -38,6 +39,8 @@ from lcode.ollama import Ollama, OllamaError
38
39
  SCHEMA_VERSION = 1
39
40
  DEFAULT_CONTEXT = 32768 # the same everywhere, so results compare across machines
40
41
  DEFAULT_TIMEOUT = 300 # seconds per task
42
+ LONGER_TIMEOUT = 600 # for the longer tasks, which take a strong model up to five minutes
43
+ DEFAULT_ATTEMPTS = 3 # each task's attempts: one run is within the noise between runs
41
44
  CHECK_TIMEOUT = 60
42
45
  PROBE_WORDS = 3000 # about 4,000 tokens
43
46
  PROBE_TEXT = (
@@ -63,6 +66,7 @@ class Task:
63
66
  prompt: str
64
67
  files: dict[str, str]
65
68
  check: Callable[[Path, str], Check] # (task folder, the model's final answer) -> result
69
+ timeout: float = DEFAULT_TIMEOUT # seconds before it stops, unless --timeout says otherwise
66
70
 
67
71
 
68
72
  # ----------------------------------------------------------------------------- helpers for checks
@@ -745,32 +749,41 @@ TASKS = [
745
749
 
746
750
 
747
751
  def extra_tasks() -> list[Task]:
748
- """Tasks that only run when asked for with --tasks (they're slower, or test optional features)."""
749
- from lcode import bench_backend, bench_runtime
752
+ """Tasks that only run when asked for with --tasks (for optional features such as --code-search)."""
753
+ from lcode import bench_backend
754
+
755
+ return [Task("find-concept", "Find code by what it does (40 files)", *parts(bench_backend))]
756
+
757
+
758
+ def work_tasks() -> list[Task]:
759
+ """Tasks closer to real work, after the quick ones: longer, and where good models still slip."""
760
+ from lcode import bench_budgets, bench_dedupe, bench_flaky, bench_logsum, bench_quotes, bench_runtime
750
761
 
751
762
  return [
752
- Task(
753
- "find-concept",
754
- "Find code by what it does (40 files)",
755
- bench_backend.PROMPT,
756
- bench_backend.FILES,
757
- bench_backend.check,
758
- ),
759
- Task(
760
- "runtime-bug",
761
- "Fix a bug that shows only when it runs",
762
- bench_runtime.PROMPT,
763
- bench_runtime.FILES,
764
- bench_runtime.check,
765
- ),
763
+ Task("cli-tool", "Build a tool from a spec", *parts(bench_logsum), LONGER_TIMEOUT),
764
+ Task("flaky-test", "Find why a test is flaky", *parts(bench_flaky), LONGER_TIMEOUT),
765
+ Task("repo-bug", "Fix a bug in a 47-file repo", *parts(bench_quotes), LONGER_TIMEOUT),
766
+ Task("wide-feature", "Add a feature across modules", *parts(bench_budgets), LONGER_TIMEOUT),
767
+ Task("fast-dedupe", "Make a slow job fast, same output", *parts(bench_dedupe), LONGER_TIMEOUT),
768
+ Task("runtime-bug", "Fix a bug that shows only when it runs", *parts(bench_runtime), LONGER_TIMEOUT),
766
769
  ]
767
770
 
768
771
 
772
+ def parts(module) -> tuple:
773
+ """A task module's prompt, files and check."""
774
+ return module.PROMPT, module.FILES, module.check
775
+
776
+
777
+ def default_tasks() -> list[Task]:
778
+ """What `lcode bench` runs: the quick tasks, then the longer ones."""
779
+ return [*TASKS, *work_tasks()]
780
+
781
+
769
782
  def select_tasks(ids: str | None) -> list[Task]:
770
783
  if not ids:
771
- return list(TASKS)
784
+ return default_tasks()
772
785
  wanted = [i.strip() for i in ids.split(",") if i.strip()]
773
- known = {task.id: task for task in [*TASKS, *extra_tasks()]}
786
+ known = {task.id: task for task in [*default_tasks(), *extra_tasks()]}
774
787
  unknown = [i for i in wanted if i not in known]
775
788
  if unknown:
776
789
  raise ValueError(f"unknown task(s) {', '.join(unknown)}; choose from {', '.join(known)}")
@@ -792,6 +805,46 @@ class TaskResult:
792
805
  errors_by_tool: dict[str, int] = field(default_factory=dict) # which tools failed, "malformed" for unreadable calls
793
806
  first_passed: bool | None = None # with --retry: whether the first try passed (None: no retry was needed)
794
807
  escalations: int = 0 # times the stronger model was asked (--escalate)
808
+ attempt: int = 1 # which of the task's attempts this was (--attempts)
809
+
810
+
811
+ @dataclass
812
+ class PassRates:
813
+ """How often the tasks passed, as `lcode bench --harbor` counts it (lcode.harbor_bench.summarize)."""
814
+
815
+ tries: int # k: each task's tries, its attempts (times the rounds of a --session)
816
+ pass_at_1: float | None # the share of tries that passed, averaged over the tasks
817
+ pass_all: float | None # pass^k: the share of tasks that passed every try (of those with all k)
818
+ attempts: list[tuple[int, int]] # (passed, tasks run) in each attempt, in order
819
+
820
+ @property
821
+ def runs(self) -> list[float]:
822
+ """The pass rate of each attempt that ran every task."""
823
+ full = max((ran for _, ran in self.attempts), default=0)
824
+ return [passed / ran for passed, ran in self.attempts if ran == full and ran]
825
+
826
+ @property
827
+ def spread(self) -> float | None:
828
+ runs = self.runs
829
+ return max(runs) - min(runs) if len(runs) > 1 else None
830
+
831
+
832
+ def pass_rates(results: list[TaskResult], attempts: int) -> PassRates:
833
+ tries: dict[str, list[bool]] = {}
834
+ for result in results:
835
+ tries.setdefault(result.id, []).append(result.passed)
836
+ per_attempt = Counter((result.id, result.attempt) for result in results)
837
+ k = max(1, attempts) * max(per_attempt.values(), default=1)
838
+ full = [passed for passed in tries.values() if len(passed) >= k]
839
+ by_attempt: dict[int, list[bool]] = {}
840
+ for result in results:
841
+ by_attempt.setdefault(result.attempt, []).append(result.passed)
842
+ return PassRates(
843
+ tries=k,
844
+ pass_at_1=statistics.fmean(statistics.fmean(passed) for passed in tries.values()) if tries else None,
845
+ pass_all=statistics.fmean(all(passed[:k]) for passed in full) if full else None,
846
+ attempts=[(sum(passed), len(passed)) for _, passed in sorted(by_attempt.items())],
847
+ )
795
848
 
796
849
 
797
850
  @dataclass
@@ -812,6 +865,10 @@ class ModelRun:
812
865
  session: bool = False # all tasks in one conversation (--session)
813
866
  pruned: int = 0 # times old tool output was removed to make room
814
867
  compacted: int = 0 # times the conversation was summarized
868
+ attempts: int = 1 # each task's attempts, each in a new folder and conversation (--attempts)
869
+
870
+ def rates(self) -> PassRates:
871
+ return pass_rates(self.tasks, self.attempts)
815
872
 
816
873
  @property
817
874
  def passed(self) -> int:
@@ -832,12 +889,19 @@ class ModelRun:
832
889
 
833
890
  def to_json(self) -> dict:
834
891
  data = asdict(self)
892
+ rates = self.rates()
835
893
  data.update(
836
894
  passed=self.passed,
837
895
  total=len(self.tasks),
838
896
  seconds=round(self.seconds, 1),
839
897
  generation_tps=self.generation_tps,
840
898
  tool_errors=self.tool_errors,
899
+ summary={
900
+ "pass_at_1": rates.pass_at_1,
901
+ f"pass^{rates.tries}": rates.pass_all,
902
+ "runs": rates.runs,
903
+ "spread": rates.spread,
904
+ },
841
905
  )
842
906
  return data
843
907
 
@@ -1029,17 +1093,24 @@ def run_model(
1029
1093
  settings: Settings,
1030
1094
  tasks: list[Task],
1031
1095
  console: Console,
1032
- timeout: float = DEFAULT_TIMEOUT,
1096
+ timeout: float | None = None,
1033
1097
  keep: bool = False,
1034
1098
  verbose: bool = False,
1035
1099
  session: bool = False,
1036
1100
  retry: bool = False,
1101
+ attempts: int = 1,
1037
1102
  ) -> ModelRun:
1038
- run = ModelRun(name, settings.model, settings.context, settings.num_batch, settings.think, session=session)
1103
+ """Run the tasks `attempts` times: every task once, then every task again, each time in a new folder and
1104
+ conversation (with `session`, each attempt is one conversation for all the tasks)."""
1105
+ attempts = max(1, attempts)
1106
+ run = ModelRun(
1107
+ name, settings.model, settings.context, settings.num_batch, settings.think, session=session, attempts=attempts
1108
+ )
1039
1109
  shared: Agent | None = None # with --session, one conversation for all tasks
1040
1110
  console.print(
1041
1111
  f"\n[bold]{escape(settings.model)}[/] · {format_tokens(settings.context)} context · "
1042
1112
  f"reasoning {'on' if settings.think else 'off'} · {len(tasks)} task{'' if len(tasks) == 1 else 's'}"
1113
+ + (f" · {attempts} attempts each" if attempts > 1 else "")
1043
1114
  )
1044
1115
  options = {"num_ctx": settings.context, **({"num_batch": settings.num_batch} if settings.num_batch else {})}
1045
1116
  started = time.monotonic()
@@ -1065,30 +1136,41 @@ def run_model(
1065
1136
  console.print(f" [dim]Loaded in {run.load_seconds:.0f}s{where}{reads}[/]")
1066
1137
  elif reads: # the server loads the model itself
1067
1138
  console.print(f" [dim]{reads.removeprefix(' · ').capitalize()}[/]")
1068
- for task in tasks:
1069
- log = console if verbose else Console(file=io.StringIO(), width=120, force_terminal=False)
1070
- if session and shared is None:
1071
- shared = Agent(ollama, settings, Path(tempfile.gettempdir()), console=log)
1072
- if shared is not None:
1073
- shared.console = log
1074
- try:
1075
- if verbose:
1076
- console.rule(f"{task.id}: {task.title}")
1077
- result = run_task(ollama, settings, task, timeout, log, keep, run.usage, shared, retry)
1078
- else:
1079
- with console.status(Elapsed(f" {task.id:<13} {task.title}")):
1080
- result = run_task(ollama, settings, task, timeout, log, keep, run.usage, shared, retry)
1081
- except KeyboardInterrupt:
1082
- console.print(" [yellow]Stopped.[/]")
1083
- run.interrupted = True
1139
+ pruned = compacted = 0 # in the conversations of the earlier attempts (--session)
1140
+ for attempt in range(1, attempts + 1):
1141
+ if attempts > 1:
1142
+ console.print(f" [dim]Attempt {attempt} of {attempts}[/]")
1143
+ if shared is not None: # with --session, each attempt is a conversation of its own
1144
+ pruned, compacted = pruned + shared.pruned, compacted + shared.compacted
1145
+ shared = None
1146
+ for task in tasks:
1147
+ limit = timeout or task.timeout # --timeout, or the task's own
1148
+ log = console if verbose else Console(file=io.StringIO(), width=120, force_terminal=False)
1149
+ if session and shared is None:
1150
+ shared = Agent(ollama, settings, Path(tempfile.gettempdir()), console=log)
1151
+ if shared is not None:
1152
+ shared.console = log
1153
+ try:
1154
+ if verbose:
1155
+ console.rule(f"{task.id}: {task.title}")
1156
+ result = run_task(ollama, settings, task, limit, log, keep, run.usage, shared, retry)
1157
+ else:
1158
+ with console.status(Elapsed(f" {task.id:<13} {task.title}")):
1159
+ result = run_task(ollama, settings, task, limit, log, keep, run.usage, shared, retry)
1160
+ except KeyboardInterrupt:
1161
+ console.print(" [yellow]Stopped.[/]")
1162
+ run.interrupted = True
1163
+ break
1164
+ result.attempt = attempt
1165
+ run.tasks.append(result)
1166
+ mark = "[green]✓[/]" if result.passed else "[red]✗[/]"
1167
+ console.print(
1168
+ f" {mark} {task.id:<13} {task.title:<32} {result.seconds:>5.0f}s [dim]{escape(result.detail)}[/]"
1169
+ )
1170
+ if shared is not None:
1171
+ run.pruned, run.compacted = pruned + shared.pruned, compacted + shared.compacted
1172
+ if run.interrupted:
1084
1173
  break
1085
- run.tasks.append(result)
1086
- mark = "[green]✓[/]" if result.passed else "[red]✗[/]"
1087
- console.print(
1088
- f" {mark} {task.id:<13} {task.title:<32} {result.seconds:>5.0f}s [dim]{escape(result.detail)}[/]"
1089
- )
1090
- if shared is not None:
1091
- run.pruned, run.compacted = shared.pruned, shared.compacted
1092
1174
  if run.memory_gb is None:
1093
1175
  run.memory_gb, run.gpu_percent = memory_use(ollama, settings.model)
1094
1176
  # lcode lowers the batch size or context if the GPU runs out of memory; report what was used.
@@ -1103,21 +1185,39 @@ def duration(seconds: float) -> str:
1103
1185
  return f"{int(seconds // 60)}m {seconds % 60:02.0f}s" if seconds >= 60 else f"{seconds:.0f}s"
1104
1186
 
1105
1187
 
1188
+ def percent(share: float | None) -> str:
1189
+ return "–" if share is None else f"{share * 100:.0f}%"
1190
+
1191
+
1106
1192
  def summary_rows(runs: list[ModelRun], tasks: list[Task]) -> list[tuple[str, list[str]]]:
1107
1193
  rows = []
1108
- for task in {t.id: t for t in tasks}.values(): # with --rounds a task runs several times: one row, a mark each
1194
+ for task in {t.id: t for t in tasks}.values(): # a task that ran several times: one row, a mark each
1109
1195
  cells = []
1110
1196
  for run in runs:
1111
1197
  results = [t for t in run.tasks if t.id == task.id]
1112
1198
  marks = "".join("✓" if r.passed else "✗" for r in results)
1113
- cells.append(f"{marks} {duration(sum(r.seconds for r in results))}" if results else "")
1199
+ each = sum(r.seconds for r in results) / len(results) if results else 0.0 # one try's time, on average
1200
+ cells.append(f"{marks} {duration(each)}" if results else "")
1114
1201
  rows.append((f"{task.id}: {task.title}", cells))
1115
1202
 
1116
1203
  def cell(run: ModelRun, value: str) -> str:
1117
1204
  return "—" if run.error else value
1118
1205
 
1206
+ rows.append(
1207
+ ("Passed", [cell(r, f"{r.passed}/{len(r.tasks)}" + (" (stopped)" if r.interrupted else "")) for r in runs])
1208
+ )
1209
+ rates = [(run, run.rates()) for run in runs]
1210
+ tries = max((rate.tries for _, rate in rates), default=1)
1211
+ if tries > 1:
1212
+ rows += [
1213
+ ("pass@1", [cell(run, percent(rate.pass_at_1)) for run, rate in rates]),
1214
+ (f"pass^{tries}", [cell(run, percent(rate.pass_all)) for run, rate in rates]),
1215
+ ]
1216
+ if any(len(rate.attempts) > 1 for _, rate in rates):
1217
+ rows.append(
1218
+ ("Each attempt", [cell(run, ", ".join(f"{p}/{n}" for p, n in rate.attempts)) for run, rate in rates])
1219
+ )
1119
1220
  rows += [
1120
- ("Passed", [cell(r, f"{r.passed}/{len(r.tasks)}" + (" (stopped)" if r.interrupted else "")) for r in runs]),
1121
1221
  ("Time", [cell(r, duration(r.seconds)) for r in runs]),
1122
1222
  ("Generation", [cell(r, f"{r.generation_tps:.1f} tok/s" if r.generation_tps else "?") for r in runs]),
1123
1223
  ("Prompt reading", [cell(r, f"{r.prompt_tps:,.0f} tok/s" if r.prompt_tps else "?") for r in runs]),
@@ -1162,7 +1262,7 @@ def report(runs: list[ModelRun], hardware: Hardware, ollama_version: str, server
1162
1262
  "server": server or f"Ollama {ollama_version}",
1163
1263
  "date": dt.datetime.now().astimezone().isoformat(timespec="seconds"),
1164
1264
  "hardware": {**asdict(hardware), "description": hardware.describe()},
1165
- "tasks": [{"id": t.id, "title": t.title} for t in TASKS],
1265
+ "tasks": [{"id": t.id, "title": t.title} for t in default_tasks()],
1166
1266
  "runs": [run.to_json() for run in runs],
1167
1267
  }
1168
1268
 
@@ -1192,7 +1292,11 @@ def print_tasks(console: Console) -> None:
1192
1292
  table = Table(title="lcode bench tasks", title_justify="left", header_style="bold")
1193
1293
  table.add_column("Task", style="cyan")
1194
1294
  table.add_column("What it tests")
1195
- for task in TASKS:
1196
- table.add_row(task.id, task.title)
1295
+ table.add_column("Runs", style="dim")
1296
+ for tasks, when in [(TASKS, "always"), (work_tasks(), "not with --quick"), (extra_tasks(), "only with --tasks")]:
1297
+ for task in tasks:
1298
+ table.add_row(task.id, task.title, when)
1197
1299
  console.print(table)
1198
- console.print("[dim]Run a subset with --tasks, e.g. lcode bench --tasks fix-bug,rename[/]")
1300
+ console.print(
1301
+ "[dim]--quick runs the quick ones once; --tasks picks some, e.g. lcode bench --tasks fix-bug,rename[/]"
1302
+ )