langfun 0.0.2.dev20240429__py3-none-any.whl → 0.0.2.dev20240503__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.
- langfun/core/eval/__init__.py +14 -1
- langfun/core/eval/base.py +499 -110
- langfun/core/eval/base_test.py +185 -53
- langfun/core/eval/matching.py +22 -21
- langfun/core/eval/matching_test.py +23 -2
- langfun/core/eval/patching.py +130 -0
- langfun/core/eval/patching_test.py +170 -0
- langfun/core/eval/scoring.py +4 -4
- langfun/core/eval/scoring_test.py +19 -2
- langfun/core/language_model.py +6 -0
- langfun/core/llms/openai.py +1 -1
- langfun/core/llms/openai_test.py +2 -1
- langfun/core/structured/scoring.py +4 -1
- langfun/core/structured/scoring_test.py +6 -0
- {langfun-0.0.2.dev20240429.dist-info → langfun-0.0.2.dev20240503.dist-info}/METADATA +1 -2
- {langfun-0.0.2.dev20240429.dist-info → langfun-0.0.2.dev20240503.dist-info}/RECORD +19 -17
- {langfun-0.0.2.dev20240429.dist-info → langfun-0.0.2.dev20240503.dist-info}/LICENSE +0 -0
- {langfun-0.0.2.dev20240429.dist-info → langfun-0.0.2.dev20240503.dist-info}/WHEEL +0 -0
- {langfun-0.0.2.dev20240429.dist-info → langfun-0.0.2.dev20240503.dist-info}/top_level.txt +0 -0
langfun/core/eval/base.py
CHANGED
@@ -18,16 +18,16 @@ import collections
|
|
18
18
|
import dataclasses
|
19
19
|
import functools
|
20
20
|
import hashlib
|
21
|
+
import html
|
21
22
|
import inspect
|
22
23
|
import io
|
23
24
|
import os
|
24
25
|
import re
|
25
26
|
import threading
|
26
27
|
import time
|
28
|
+
import types
|
27
29
|
from typing import Annotated, Any, Callable, Iterator, Literal, Optional, Sequence, Type, Union
|
28
30
|
|
29
|
-
from absl import app
|
30
|
-
from absl import flags
|
31
31
|
import langfun.core as lf
|
32
32
|
import langfun.core.coding as lf_coding
|
33
33
|
from langfun.core.llms.cache import in_memory
|
@@ -40,7 +40,8 @@ class Evaluable(lf.Component):
|
|
40
40
|
|
41
41
|
EXPERIMENT_JSON = 'experiment.json'
|
42
42
|
RESULT_JSON = 'result.json'
|
43
|
-
|
43
|
+
OOP_FAILURES_JSON = 'oop_failures.json'
|
44
|
+
NON_OOP_FAILURES_JSON = 'non_oop_failures.json'
|
44
45
|
INDEX_HTML = 'index.html'
|
45
46
|
SUMMARY_HTML = 'summary.html'
|
46
47
|
|
@@ -358,7 +359,7 @@ class Evaluable(lf.Component):
|
|
358
359
|
color='yellow')
|
359
360
|
|
360
361
|
for node in self.nonleaf_nodes:
|
361
|
-
node._result = {c.id: c.result for c in node.
|
362
|
+
node._result = {c.id: c.result for c in node.leaf_nodes} # pylint: disable=protected-access
|
362
363
|
if should_save:
|
363
364
|
node.save(result=False, report=False)
|
364
365
|
|
@@ -540,15 +541,15 @@ class Evaluable(lf.Component):
|
|
540
541
|
f'<div style="color: {text_color}; white-space: pre-wrap;'
|
541
542
|
'padding: 10px; border: 1px solid; margin-top: 10px">'
|
542
543
|
)
|
543
|
-
s.write(m.get('formatted_text', m.text))
|
544
|
+
s.write(html.escape(m.get('formatted_text', m.text)))
|
544
545
|
if m.result is not None:
|
545
546
|
s.write(
|
546
547
|
'<div style="color: magenta; white-space: pre-wrap;'
|
547
548
|
'padding: 10px; border: 1px solid; margin: 10px">'
|
548
549
|
)
|
549
|
-
s.write(pg.format(m.result))
|
550
|
+
s.write(html.escape(pg.format(m.result)))
|
550
551
|
s.write('</div>')
|
551
|
-
if 'usage' in m.metadata:
|
552
|
+
if 'usage' in m.metadata and m.usage is not None:
|
552
553
|
s.write(
|
553
554
|
'<div style="background-color: #EEEEEE; color: black; '
|
554
555
|
'white-space: pre-wrap; padding: 10px; border: 0px solid; '
|
@@ -598,7 +599,6 @@ class _LeafNode:
|
|
598
599
|
@pg.use_init_args(['children'])
|
599
600
|
class Suite(Evaluable):
|
600
601
|
"""Evaluation suite."""
|
601
|
-
|
602
602
|
children: Annotated[list[Evaluable], 'Child evaluation sets or suites.']
|
603
603
|
|
604
604
|
# Use empty ID as suite is just a container of child evaluations.
|
@@ -753,10 +753,12 @@ class Evaluation(Evaluable):
|
|
753
753
|
|
754
754
|
# Constants.
|
755
755
|
CACHE_JSON = 'cache.json'
|
756
|
-
|
756
|
+
OOP_FAILURES_HTML = 'oop_failures.html'
|
757
|
+
NON_OOP_FAILURES_HTML = 'non_oop_failures.html'
|
757
758
|
|
758
759
|
@functools.cached_property
|
759
760
|
def hash(self) -> str:
|
761
|
+
"""Returns the semantic-based hash of the evaluation."""
|
760
762
|
if self.is_deterministic:
|
761
763
|
identity = pg.format(self._identifiers(), compact=True)
|
762
764
|
else:
|
@@ -805,6 +807,10 @@ class Evaluation(Evaluable):
|
|
805
807
|
"""Returns the complete rate."""
|
806
808
|
return self.num_completed / self.num_examples
|
807
809
|
|
810
|
+
#
|
811
|
+
# Properties on failures.
|
812
|
+
#
|
813
|
+
|
808
814
|
@property
|
809
815
|
def failures(self) -> list[tuple[Any, Exception]]:
|
810
816
|
"""Returns the failed examples and their errors."""
|
@@ -815,6 +821,15 @@ class Evaluation(Evaluable):
|
|
815
821
|
"""Returns the number of failed examples."""
|
816
822
|
return len(self.failures)
|
817
823
|
|
824
|
+
@functools.cached_property
|
825
|
+
def failure_breakdown(self) -> dict[str, int]:
|
826
|
+
"""Returns the breakdown of failures."""
|
827
|
+
breakdown = collections.defaultdict(int)
|
828
|
+
for _, error in self.failures:
|
829
|
+
breakdown[_error_key(error)] += 1
|
830
|
+
sorted_items = sorted(breakdown.items(), key=lambda x: x[1], reverse=True)
|
831
|
+
return pg.Dict({x[0]: x[1] for x in sorted_items})
|
832
|
+
|
818
833
|
@property
|
819
834
|
def failure_rate(self) -> float:
|
820
835
|
"""Returns the failure rate in range [0, 1]."""
|
@@ -822,6 +837,46 @@ class Evaluation(Evaluable):
|
|
822
837
|
return 0.0
|
823
838
|
return self.num_failures / self.num_completed
|
824
839
|
|
840
|
+
@functools.cached_property
|
841
|
+
def oop_failures(self) -> list[tuple[Any, lf_structured.MappingError]]:
|
842
|
+
"""Returns the OOP failures."""
|
843
|
+
return [item for item in self.failures
|
844
|
+
if isinstance(item[1], lf_structured.MappingError)]
|
845
|
+
|
846
|
+
@property
|
847
|
+
def num_oop_failures(self) -> int:
|
848
|
+
"""Returns the number of OOP failures."""
|
849
|
+
return len(self.oop_failures)
|
850
|
+
|
851
|
+
@property
|
852
|
+
def oop_failure_rate(self) -> float:
|
853
|
+
"""Returns the OOP failure rate in range [0, 1]."""
|
854
|
+
if self.num_completed == 0:
|
855
|
+
return 0.0
|
856
|
+
return self.num_oop_failures / self.num_completed
|
857
|
+
|
858
|
+
@functools.cached_property
|
859
|
+
def non_oop_failures(self) -> list[tuple[Any, Exception]]:
|
860
|
+
"""Returns the OOP failures."""
|
861
|
+
return [item for item in self.failures
|
862
|
+
if not isinstance(item[1], lf_structured.MappingError)]
|
863
|
+
|
864
|
+
@property
|
865
|
+
def num_non_oop_failures(self) -> int:
|
866
|
+
"""Returns the number of non-OOP failures."""
|
867
|
+
return len(self.non_oop_failures)
|
868
|
+
|
869
|
+
@property
|
870
|
+
def non_oop_failure_rate(self) -> float:
|
871
|
+
"""Returns the non-OOP failure rate in range [0, 1]."""
|
872
|
+
if self.num_completed == 0:
|
873
|
+
return 0.0
|
874
|
+
return self.num_non_oop_failures / self.num_completed
|
875
|
+
|
876
|
+
#
|
877
|
+
# Properties on usage.
|
878
|
+
#
|
879
|
+
|
825
880
|
@property
|
826
881
|
def has_usage(self) -> bool:
|
827
882
|
"""Returns True if token usage is enabled."""
|
@@ -976,13 +1031,22 @@ class Evaluation(Evaluable):
|
|
976
1031
|
self._total_prompt_tokens = 0
|
977
1032
|
self._total_completion_tokens = 0
|
978
1033
|
self._num_usages = 0
|
1034
|
+
self.__dict__.pop('oop_failures', None)
|
1035
|
+
self.__dict__.pop('non_oop_failures', None)
|
979
1036
|
|
980
1037
|
@property
|
981
|
-
def
|
982
|
-
"""Returns the link to the failures page."""
|
1038
|
+
def oop_failures_link(self) -> str | None:
|
1039
|
+
"""Returns the link to the OOP failures page."""
|
983
1040
|
if self.dir is None:
|
984
1041
|
return None
|
985
|
-
return self.link(os.path.join(self.dir, Evaluation.
|
1042
|
+
return self.link(os.path.join(self.dir, Evaluation.OOP_FAILURES_HTML))
|
1043
|
+
|
1044
|
+
@property
|
1045
|
+
def non_oop_failures_link(self) -> str | None:
|
1046
|
+
"""Returns the link to then non-OOP failures page."""
|
1047
|
+
if self.dir is None:
|
1048
|
+
return None
|
1049
|
+
return self.link(os.path.join(self.dir, Evaluation.NON_OOP_FAILURES_HTML))
|
986
1050
|
|
987
1051
|
def _dryrun(
|
988
1052
|
self,
|
@@ -992,11 +1056,11 @@ class Evaluation(Evaluable):
|
|
992
1056
|
verbose: bool,
|
993
1057
|
**kwargs,
|
994
1058
|
) -> None:
|
995
|
-
# Set the example for dryrun.
|
996
|
-
example = example or self.examples[0]
|
997
|
-
|
998
1059
|
# We make a copy to avoid pollute the state of current object.
|
999
1060
|
copy: Evaluation = self.clone()
|
1061
|
+
|
1062
|
+
# Set the example for dryrun.
|
1063
|
+
example = example or copy.examples[0]
|
1000
1064
|
copy.__dict__['examples'] = [example]
|
1001
1065
|
|
1002
1066
|
# We set the symbolic parent of the cloned to access contextual information
|
@@ -1011,23 +1075,34 @@ class Evaluation(Evaluable):
|
|
1011
1075
|
color='green',
|
1012
1076
|
)
|
1013
1077
|
|
1014
|
-
|
1015
|
-
output_message = copy.process(example, **(self.additional_args or {}))
|
1016
|
-
if self.schema is None:
|
1017
|
-
output = output_message.text
|
1018
|
-
else:
|
1019
|
-
output = output_message.result
|
1078
|
+
error, output_message = None, None
|
1020
1079
|
|
1021
|
-
|
1080
|
+
try:
|
1081
|
+
with lf.use_settings(debug=debug):
|
1082
|
+
output_message = copy.process(example, **(self.additional_args or {}))
|
1083
|
+
if self.schema is None:
|
1084
|
+
output = output_message.text
|
1085
|
+
else:
|
1086
|
+
output = output_message.result
|
1087
|
+
|
1088
|
+
if verbose:
|
1089
|
+
lf.console.write('')
|
1090
|
+
lf.console.write(
|
1091
|
+
str(output),
|
1092
|
+
title='OUTPUT',
|
1093
|
+
color='blue',
|
1094
|
+
)
|
1095
|
+
except lf_structured.MappingError as e:
|
1022
1096
|
lf.console.write('')
|
1023
1097
|
lf.console.write(
|
1024
|
-
str(
|
1025
|
-
title='
|
1026
|
-
color='
|
1098
|
+
str(e),
|
1099
|
+
title='ERROR',
|
1100
|
+
color='red',
|
1027
1101
|
)
|
1102
|
+
error = e
|
1028
1103
|
|
1029
|
-
copy.audit(example, output_message,
|
1030
|
-
result = copy.
|
1104
|
+
copy.audit(example, output_message, error, dryrun=True)
|
1105
|
+
result = copy.finalize()
|
1031
1106
|
|
1032
1107
|
if verbose:
|
1033
1108
|
lf.console.write('')
|
@@ -1051,6 +1126,9 @@ class Evaluation(Evaluable):
|
|
1051
1126
|
**kwargs,
|
1052
1127
|
) -> None:
|
1053
1128
|
# Setup examples.
|
1129
|
+
# Reset examples so it could be read from the input functor.
|
1130
|
+
self.__dict__.pop('examples', None)
|
1131
|
+
|
1054
1132
|
if end is None:
|
1055
1133
|
end = len(self.examples)
|
1056
1134
|
examples = self.examples[start:end]
|
@@ -1087,7 +1165,7 @@ class Evaluation(Evaluable):
|
|
1087
1165
|
self.cache.save()
|
1088
1166
|
|
1089
1167
|
# Summarize result.
|
1090
|
-
self._result = self.
|
1168
|
+
self._result = self.finalize()
|
1091
1169
|
if verbose:
|
1092
1170
|
lf.console.write(
|
1093
1171
|
str(self.result),
|
@@ -1143,13 +1221,13 @@ class Evaluation(Evaluable):
|
|
1143
1221
|
def _status(self, progress: lf.concurrent.Progress) -> dict[str, Any]:
|
1144
1222
|
return {
|
1145
1223
|
'Model': self.lm.model_id,
|
1146
|
-
'Succeeded':
|
1147
|
-
progress.success_rate
|
1224
|
+
'Succeeded': '%s (%d/%d)' % (
|
1225
|
+
self._format_rate(progress.success_rate),
|
1148
1226
|
progress.succeeded,
|
1149
1227
|
progress.completed,
|
1150
1228
|
),
|
1151
|
-
'Failed':
|
1152
|
-
progress.failure_rate
|
1229
|
+
'Failed': '%s (%d/%d)' % (
|
1230
|
+
self._format_rate(progress.failure_rate),
|
1153
1231
|
progress.failed,
|
1154
1232
|
progress.completed,
|
1155
1233
|
),
|
@@ -1159,21 +1237,20 @@ class Evaluation(Evaluable):
|
|
1159
1237
|
assert self.result is not None
|
1160
1238
|
m = self.result.metrics
|
1161
1239
|
return (
|
1162
|
-
|
1163
|
-
f' Failures=%.{self.report_precision}f%% (%d/%d)'
|
1240
|
+
'COMPLETED(%s): Successes=%s(%d/%d) Failures=%s (%d/%d)'
|
1164
1241
|
% (
|
1165
1242
|
run_status,
|
1166
|
-
(1 - m.failure_rate)
|
1243
|
+
self._format_rate(1 - m.failure_rate),
|
1167
1244
|
m.total - m.failures,
|
1168
1245
|
m.total,
|
1169
|
-
m.failure_rate
|
1246
|
+
self._format_rate(m.failure_rate),
|
1170
1247
|
m.failures,
|
1171
1248
|
m.total,
|
1172
1249
|
)
|
1173
1250
|
)
|
1174
1251
|
|
1175
|
-
def
|
1176
|
-
"""
|
1252
|
+
def finalize(self) -> pg.Dict:
|
1253
|
+
"""Finalizes the evaluation result."""
|
1177
1254
|
if self.cache:
|
1178
1255
|
cache_stats = dict(
|
1179
1256
|
use_cache=True,
|
@@ -1210,12 +1287,18 @@ class Evaluation(Evaluable):
|
|
1210
1287
|
total=self.num_completed,
|
1211
1288
|
failures=self.num_failures,
|
1212
1289
|
failure_rate=self.failure_rate,
|
1290
|
+
oop_failures=self.num_oop_failures,
|
1291
|
+
oop_failure_rate=self.oop_failure_rate,
|
1292
|
+
non_oop_failures=self.num_non_oop_failures,
|
1293
|
+
non_oop_failure_rate=self.non_oop_failure_rate,
|
1294
|
+
failure_breakdown=self.failure_breakdown,
|
1213
1295
|
),
|
1214
1296
|
usage=usage,
|
1215
1297
|
)
|
1216
1298
|
return result
|
1217
1299
|
|
1218
|
-
def
|
1300
|
+
def summary_card(self) -> str:
|
1301
|
+
"""Returns summary card in HTML."""
|
1219
1302
|
s = io.StringIO()
|
1220
1303
|
definition = _html_repr(self, compact=False, escape=True)
|
1221
1304
|
s.write('<div><table><tr><td>')
|
@@ -1230,18 +1313,19 @@ class Evaluation(Evaluable):
|
|
1230
1313
|
s.write(
|
1231
1314
|
f'<a target="_blank" title="{definition}" '
|
1232
1315
|
f'href="{self.index_link}">{self.hash}</a>'
|
1316
|
+
f' [<a href="{self.link(self.dir)}">dir</a>]'
|
1233
1317
|
'</td></tr><tr><td>'
|
1234
1318
|
)
|
1235
|
-
self.
|
1319
|
+
self._render_summary_metrics(s)
|
1236
1320
|
|
1237
1321
|
# Summarize average usage.
|
1238
1322
|
if self.result.usage is not None:
|
1239
|
-
self.
|
1323
|
+
self._render_summary_usage(s)
|
1240
1324
|
|
1241
1325
|
s.write('</td></tr></table></div>')
|
1242
1326
|
return s.getvalue()
|
1243
1327
|
|
1244
|
-
def
|
1328
|
+
def _render_summary_usage(self, s: io.StringIO) -> None:
|
1245
1329
|
"""Renders usage in HTML."""
|
1246
1330
|
usage = self.result.usage
|
1247
1331
|
total = usage.total_prompt_tokens + usage.total_completion_tokens
|
@@ -1255,19 +1339,65 @@ class Evaluation(Evaluable):
|
|
1255
1339
|
f'" style="color:gray">({total} tokens)</a>'
|
1256
1340
|
)
|
1257
1341
|
|
1258
|
-
def
|
1342
|
+
def _render_summary_metrics(self, s: io.StringIO) -> None:
|
1259
1343
|
"""Renders metrics in HTML."""
|
1260
1344
|
assert self.result is not None
|
1261
1345
|
m = self.result.metrics
|
1346
|
+
|
1347
|
+
# OOP failures.
|
1348
|
+
oop_failure_title = f'OOP failures ({m.oop_failures}/{m.total})'
|
1349
|
+
if m.oop_failures:
|
1350
|
+
oop_failure_title += '
'
|
1351
|
+
for name, count in m.failure_breakdown.items():
|
1352
|
+
if name.startswith('MappingError'):
|
1353
|
+
oop_failure_title += '
%s: %s (%d/%d)' % (
|
1354
|
+
name.removeprefix('MappingError.'),
|
1355
|
+
self._format_rate(count / m.total),
|
1356
|
+
count,
|
1357
|
+
m.total,
|
1358
|
+
)
|
1359
|
+
|
1360
|
+
extra_style = ''
|
1361
|
+
if m.oop_failure_rate > 0.1 and m.oop_failures > 3:
|
1362
|
+
extra_style = ';font-weight:bold'
|
1262
1363
|
s.write(
|
1263
|
-
'<a title="
|
1364
|
+
'<a title="%s" href="%s" style="color:magenta%s">%s</a>'
|
1264
1365
|
% (
|
1265
|
-
|
1266
|
-
|
1267
|
-
|
1268
|
-
|
1366
|
+
oop_failure_title,
|
1367
|
+
self.oop_failures_link,
|
1368
|
+
extra_style,
|
1369
|
+
self._format_rate(m.oop_failure_rate),
|
1269
1370
|
)
|
1270
1371
|
)
|
1372
|
+
s.write(' | ')
|
1373
|
+
|
1374
|
+
# Non-OOP failures.
|
1375
|
+
non_oop_failure_title = f'Non-OOP failures ({m.non_oop_failures}/{m.total})'
|
1376
|
+
if m.non_oop_failures:
|
1377
|
+
non_oop_failure_title += '
'
|
1378
|
+
for name, count in m.failure_breakdown.items():
|
1379
|
+
if not name.startswith('MappingError'):
|
1380
|
+
non_oop_failure_title += '
%s: %s (%d/%d)' % (
|
1381
|
+
name,
|
1382
|
+
self._format_rate(count / m.total),
|
1383
|
+
count,
|
1384
|
+
m.total,
|
1385
|
+
)
|
1386
|
+
|
1387
|
+
extra_style = ';font-weight:bold' if m.non_oop_failures > 0 else ''
|
1388
|
+
s.write(
|
1389
|
+
'<a title="%s" href="%s" style="color:red%s">%s</a>'
|
1390
|
+
% (
|
1391
|
+
non_oop_failure_title,
|
1392
|
+
self.non_oop_failures_link,
|
1393
|
+
extra_style,
|
1394
|
+
self._format_rate(m.non_oop_failure_rate),
|
1395
|
+
)
|
1396
|
+
)
|
1397
|
+
|
1398
|
+
def _format_rate(self, rate: float) -> str:
|
1399
|
+
"""Formats a rate."""
|
1400
|
+
return f'%.{self.report_precision}f%% ' % (rate * 100)
|
1271
1401
|
|
1272
1402
|
def audit(
|
1273
1403
|
self,
|
@@ -1287,7 +1417,13 @@ class Evaluation(Evaluable):
|
|
1287
1417
|
dryrun: Whether or not audition takes place during dryrun.
|
1288
1418
|
"""
|
1289
1419
|
if error is not None:
|
1290
|
-
self._failures.append((example,
|
1420
|
+
self._failures.append((example, error))
|
1421
|
+
|
1422
|
+
# Invalid cache of num_oop_failures.
|
1423
|
+
self.__dict__.pop('oop_failures', None)
|
1424
|
+
self.__dict__.pop('non_oop_failures', None)
|
1425
|
+
self.__dict__.pop('failure_breakdown', None)
|
1426
|
+
|
1291
1427
|
if isinstance(error, lf_structured.MappingError):
|
1292
1428
|
message = error.lm_response
|
1293
1429
|
else:
|
@@ -1301,8 +1437,9 @@ class Evaluation(Evaluable):
|
|
1301
1437
|
self._num_completed += 1
|
1302
1438
|
|
1303
1439
|
def audit_usage(self, message: lf.Message, dryrun: bool = False) -> None:
|
1440
|
+
del dryrun
|
1304
1441
|
for m in message.trace():
|
1305
|
-
if 'usage'
|
1442
|
+
if m.metadata.get('usage', None) is not None:
|
1306
1443
|
self._total_prompt_tokens += m.usage.prompt_tokens
|
1307
1444
|
self._total_completion_tokens += m.usage.completion_tokens
|
1308
1445
|
self._num_usages += 1
|
@@ -1333,16 +1470,26 @@ class Evaluation(Evaluable):
|
|
1333
1470
|
# Save failures.
|
1334
1471
|
pg.save(
|
1335
1472
|
[
|
1336
|
-
pg.Dict(
|
1337
|
-
|
1338
|
-
|
1339
|
-
|
1473
|
+
pg.Dict(input=input, error=_format_error(error))
|
1474
|
+
for input, error in self.oop_failures
|
1475
|
+
],
|
1476
|
+
os.path.join(self.dir, Evaluation.OOP_FAILURES_JSON),
|
1477
|
+
)
|
1478
|
+
pg.save(
|
1479
|
+
self._html([self._render_result, self._render_oop_failures]),
|
1480
|
+
os.path.join(self.dir, Evaluation.OOP_FAILURES_HTML),
|
1481
|
+
file_format='txt',
|
1482
|
+
)
|
1483
|
+
pg.save(
|
1484
|
+
[
|
1485
|
+
pg.Dict(input=input, error=_format_error(error))
|
1486
|
+
for input, error in self.non_oop_failures
|
1340
1487
|
],
|
1341
|
-
os.path.join(self.dir, Evaluation.
|
1488
|
+
os.path.join(self.dir, Evaluation.NON_OOP_FAILURES_JSON),
|
1342
1489
|
)
|
1343
1490
|
pg.save(
|
1344
|
-
self._html([self._render_result, self.
|
1345
|
-
os.path.join(self.dir, Evaluation.
|
1491
|
+
self._html([self._render_result, self._render_non_oop_failures]),
|
1492
|
+
os.path.join(self.dir, Evaluation.NON_OOP_FAILURES_HTML),
|
1346
1493
|
file_format='txt',
|
1347
1494
|
)
|
1348
1495
|
|
@@ -1357,7 +1504,8 @@ class Evaluation(Evaluable):
|
|
1357
1504
|
)
|
1358
1505
|
if self.result.usage is not None:
|
1359
1506
|
s.write('<td>Usage</td>')
|
1360
|
-
s.write('<td>Failures</td>')
|
1507
|
+
s.write('<td>OOP Failures</td>')
|
1508
|
+
s.write('<td>Non-OOP Failures</td>')
|
1361
1509
|
|
1362
1510
|
def _render_result_row(self, s: io.StringIO) -> None:
|
1363
1511
|
s.write(
|
@@ -1385,16 +1533,29 @@ class Evaluation(Evaluable):
|
|
1385
1533
|
# Usage.
|
1386
1534
|
if self.result.usage is not None:
|
1387
1535
|
s.write('<td>')
|
1388
|
-
self.
|
1536
|
+
self._render_summary_usage(s)
|
1389
1537
|
s.write('</td>')
|
1390
1538
|
|
1391
|
-
#
|
1539
|
+
# OOP failures.
|
1540
|
+
s.write(
|
1541
|
+
'<td><span style="color:magenta">%s</span>%s</td>'
|
1542
|
+
% (
|
1543
|
+
self._format_rate(self.oop_failure_rate),
|
1544
|
+
'<a href="%s">(%d/%d)</a>'
|
1545
|
+
% (self.oop_failures_link,
|
1546
|
+
self.num_oop_failures,
|
1547
|
+
self.num_completed),
|
1548
|
+
)
|
1549
|
+
)
|
1550
|
+
# Non-OOP failures.
|
1392
1551
|
s.write(
|
1393
|
-
'<td><span style="color:
|
1552
|
+
'<td><span style="color:red">%s</span>%s</td>'
|
1394
1553
|
% (
|
1395
|
-
|
1554
|
+
self._format_rate(self.non_oop_failure_rate),
|
1396
1555
|
'<a href="%s">(%d/%d)</a>'
|
1397
|
-
% (self.
|
1556
|
+
% (self.non_oop_failures_link,
|
1557
|
+
self.num_non_oop_failures,
|
1558
|
+
self.num_completed),
|
1398
1559
|
)
|
1399
1560
|
)
|
1400
1561
|
|
@@ -1408,24 +1569,77 @@ class Evaluation(Evaluable):
|
|
1408
1569
|
else:
|
1409
1570
|
return 'cyan'
|
1410
1571
|
|
1411
|
-
def
|
1572
|
+
def _render_oop_failures(self, s: io.StringIO) -> None:
|
1573
|
+
self._render_failures(s, '^MappingError.*', error_color='magenta')
|
1574
|
+
|
1575
|
+
def _render_non_oop_failures(self, s: io.StringIO) -> None:
|
1576
|
+
self._render_failures(s, '^(?!MappingError).*', error_color='red')
|
1577
|
+
|
1578
|
+
def _render_failures(
|
1579
|
+
self, s: io.StringIO, error_regex: str, error_color: str) -> None:
|
1412
1580
|
"""Formats the failed cases into html."""
|
1581
|
+
# Failure summary.
|
1413
1582
|
s.write(
|
1414
|
-
'<h2>
|
1583
|
+
'<h2> Error Summary </h2>'
|
1415
1584
|
'<div style="white-space:pre">\n'
|
1416
1585
|
'<table style="border:1px solid">'
|
1417
|
-
'<tr class="header"><td>
|
1586
|
+
'<tr class="header"><td>Error type</td><td>Stats</td></tr>'
|
1418
1587
|
)
|
1588
|
+
error_regex = re.compile(error_regex)
|
1589
|
+
if self.result.metrics.failure_breakdown:
|
1590
|
+
for name, count in self.result.metrics.failure_breakdown.items():
|
1591
|
+
if not error_regex.match(name):
|
1592
|
+
continue
|
1593
|
+
|
1594
|
+
link = f'<a href="#{name}">{name}</a>'
|
1595
|
+
error_rate = self._format_rate(count / self.result.metrics.total)
|
1596
|
+
stats = (f'<span style="color:{error_color}">{error_rate} '
|
1597
|
+
f'({count}/{self.result.metrics.total})</span>')
|
1598
|
+
s.write(f'<tr><td>{link}</td><td>{stats})</td></tr>')
|
1599
|
+
s.write(
|
1600
|
+
'</table></div>'
|
1601
|
+
'<h2> Failed Cases </h2>'
|
1602
|
+
'<div style="white-space:pre">'
|
1603
|
+
)
|
1604
|
+
# Failure details by error type.
|
1605
|
+
failures_by_error = collections.defaultdict(list)
|
1606
|
+
for example, error in self.failures:
|
1607
|
+
error_name = _error_key(error)
|
1608
|
+
if error_regex.match(error_name):
|
1609
|
+
failures_by_error[error_name].append((example, error))
|
1610
|
+
|
1611
|
+
for error_key, failures in failures_by_error.items():
|
1612
|
+
s.write(
|
1613
|
+
f'<h3 id="{error_key}"><a href="#{error_key}">{error_key}</a> '
|
1614
|
+
f'(count={len(failures)})</h3>'
|
1615
|
+
'<table style="border:1px solid">'
|
1616
|
+
'<tr class="header"><td>No.</td><td>Input</td>'
|
1617
|
+
'<td>LM invocation</td><td>Error</td></tr>'
|
1618
|
+
)
|
1619
|
+
for i, (example, error) in enumerate(failures):
|
1620
|
+
lm_response = None
|
1621
|
+
if isinstance(error, lf.structured.MappingError):
|
1622
|
+
lm_response = error.lm_response
|
1623
|
+
error = error.cause
|
1624
|
+
|
1625
|
+
bgcolor = 'white' if i % 2 == 0 else '#DDDDDD'
|
1626
|
+
s.write(f'<tr style="background-color: {bgcolor}"><td>{i + 1}</td>')
|
1627
|
+
s.write('<td style="color:green;white-space:pre-wrap">')
|
1628
|
+
s.write(pg.format(example, verbose=False))
|
1629
|
+
s.write('</td><td>')
|
1630
|
+
if lm_response is not None:
|
1631
|
+
self._render_message(lm_response, s)
|
1632
|
+
s.write(f'</td><td style="color:{error_color};white-space:pre">')
|
1633
|
+
s.write(_format_error(error))
|
1634
|
+
s.write('</td></tr>')
|
1635
|
+
s.write('</table>')
|
1636
|
+
s.write('</div>')
|
1419
1637
|
|
1420
|
-
|
1421
|
-
|
1422
|
-
|
1423
|
-
|
1424
|
-
|
1425
|
-
error_str = lf.text_formatting.decolored(str(error))
|
1426
|
-
s.write(f'<td style="color:red;white-space:pre">{error_str}</td>')
|
1427
|
-
s.write('</tr>')
|
1428
|
-
s.write('</table></div>')
|
1638
|
+
@classmethod
|
1639
|
+
def visualize(cls, evaluations: list['Evaluation']) -> str | None:
|
1640
|
+
"""Visualize the a list of evaluations of this task in HTML."""
|
1641
|
+
del evaluations
|
1642
|
+
return None
|
1429
1643
|
|
1430
1644
|
|
1431
1645
|
@pg.functor()
|
@@ -1578,7 +1792,7 @@ class Summary(pg.Object):
|
|
1578
1792
|
if e is None:
|
1579
1793
|
s.write('<span style="color: gray">N/A<span>')
|
1580
1794
|
else:
|
1581
|
-
s.write(e.
|
1795
|
+
s.write(e.summary_card())
|
1582
1796
|
s.write('</td>')
|
1583
1797
|
s.write('</tr>')
|
1584
1798
|
s.write('</table>')
|
@@ -1653,13 +1867,22 @@ class Summary(pg.Object):
|
|
1653
1867
|
s.write('<html><body>')
|
1654
1868
|
for task in sorted(self.tasks(), key=lambda cls: cls.__name__):
|
1655
1869
|
table_id = task.__name__.lower()
|
1870
|
+
evaluations = self.select(task=task).evaluations
|
1871
|
+
table = Summary.Table.from_evaluations(evaluations, pivot_field)
|
1656
1872
|
s.write('<div>')
|
1657
|
-
s.write(
|
1658
|
-
|
1659
|
-
|
1660
|
-
table = Summary.Table.from_evaluations(
|
1661
|
-
self.select(task=task).evaluations, pivot_field
|
1873
|
+
s.write(
|
1874
|
+
f'<a id="{table_id}" href="#{table_id}">'
|
1875
|
+
f'<h2>{task.__name__}</h2></a>'
|
1662
1876
|
)
|
1877
|
+
|
1878
|
+
# Allow users to plugin visualization code (e.g. matplot) in the summary
|
1879
|
+
# page.
|
1880
|
+
visual_part = task.visualize(evaluations)
|
1881
|
+
if visual_part:
|
1882
|
+
s.write(visual_part)
|
1883
|
+
|
1884
|
+
s.write(f'<h4 style="color:gray">{len(evaluations)} experiments</h4>')
|
1885
|
+
s.write('<hr/>')
|
1663
1886
|
s.write(table.html())
|
1664
1887
|
s.write('</div>')
|
1665
1888
|
s.write('</body></html>')
|
@@ -1685,6 +1908,7 @@ class Summary(pg.Object):
|
|
1685
1908
|
experiment=entry,
|
1686
1909
|
dir=entry.dir,
|
1687
1910
|
metrics=entry.result.metrics if entry.result else None,
|
1911
|
+
usage=entry.result.usage if entry.result else None,
|
1688
1912
|
)
|
1689
1913
|
)
|
1690
1914
|
task_results[task.__name__] = results
|
@@ -1833,6 +2057,21 @@ class Summary(pg.Object):
|
|
1833
2057
|
return result.join()
|
1834
2058
|
|
1835
2059
|
|
2060
|
+
def _format_error(error: Exception):
|
2061
|
+
"""Formats an error into a string."""
|
2062
|
+
return (f'({error.__class__.__name__}) '
|
2063
|
+
+ lf.text_formatting.decolored(str(error)))
|
2064
|
+
|
2065
|
+
|
2066
|
+
def _error_key(error: Exception) -> str:
|
2067
|
+
"""Returns the key for an error."""
|
2068
|
+
error_names = []
|
2069
|
+
while error is not None:
|
2070
|
+
error_names.append(error.__class__.__name__)
|
2071
|
+
error = getattr(error, 'cause', None)
|
2072
|
+
return '.'.join(error_names)
|
2073
|
+
|
2074
|
+
|
1836
2075
|
def _html_repr(value: Any, compact: bool = True, escape: bool = False) -> str:
|
1837
2076
|
"""Formats prompt in HTML."""
|
1838
2077
|
if type(value) is lf.Template: # pylint: disable=unidiomatic-typecheck
|
@@ -1909,41 +2148,191 @@ def monitor_async(
|
|
1909
2148
|
)
|
1910
2149
|
|
1911
2150
|
|
1912
|
-
|
1913
|
-
|
2151
|
+
#
|
2152
|
+
# Named evaluations and experiments support.
|
2153
|
+
#
|
2154
|
+
|
2155
|
+
|
2156
|
+
class _NamedEvaluationRegistry:
|
2157
|
+
"""Named evaluation registry."""
|
1914
2158
|
|
1915
|
-
|
1916
|
-
|
1917
|
-
"""
|
1918
|
-
flags.DEFINE_string(
|
1919
|
-
'root_dir', None, 'Root directory for running the evaluation.'
|
1920
|
-
)
|
2159
|
+
def __init__(self):
|
2160
|
+
self._registry = {}
|
1921
2161
|
|
1922
|
-
|
1923
|
-
|
1924
|
-
|
2162
|
+
def names(self) -> list[str]:
|
2163
|
+
"""Returns all registered names."""
|
2164
|
+
return sorted(self._registry.keys())
|
1925
2165
|
|
1926
|
-
|
1927
|
-
|
1928
|
-
|
2166
|
+
def get(self, name: str) -> Type[Evaluable]:
|
2167
|
+
"""Gets an evaluation by name."""
|
2168
|
+
if name not in self._registry:
|
2169
|
+
raise ValueError(
|
2170
|
+
f'Evaluation {name!r} not found. '
|
2171
|
+
'Did you forget to import the module that registers it?'
|
2172
|
+
)
|
2173
|
+
return self._registry[name]
|
1929
2174
|
|
1930
|
-
|
1931
|
-
|
1932
|
-
|
1933
|
-
|
1934
|
-
)
|
2175
|
+
def register(
|
2176
|
+
self,
|
2177
|
+
name: str,
|
2178
|
+
experiment_cls: Type[Evaluable],
|
2179
|
+
):
|
2180
|
+
"""Register an experiment class."""
|
2181
|
+
self._registry[name] = experiment_cls
|
2182
|
+
|
2183
|
+
|
2184
|
+
_eval_registry = _NamedEvaluationRegistry()
|
2185
|
+
|
2186
|
+
|
2187
|
+
def registered_names() -> list[str]:
|
2188
|
+
"""Returns all registered names."""
|
2189
|
+
return _eval_registry.names()
|
1935
2190
|
|
1936
|
-
FLAGS = flags.FLAGS # pylint: disable=invalid-name
|
1937
2191
|
|
1938
|
-
|
1939
|
-
|
1940
|
-
|
2192
|
+
def get_evaluation(evaluation: str | Evaluable) -> Evaluable:
|
2193
|
+
"""Gets an evaluation experiment by name."""
|
2194
|
+
if isinstance(evaluation, str):
|
2195
|
+
return _eval_registry.get(evaluation)()
|
2196
|
+
return evaluation
|
1941
2197
|
|
1942
|
-
|
1943
|
-
|
1944
|
-
|
1945
|
-
|
2198
|
+
|
2199
|
+
def register(name: str):
|
2200
|
+
"""Decorator to create a named evaluation class."""
|
2201
|
+
|
2202
|
+
def _register(func_or_cls: Type[Evaluation] | types.FunctionType):
|
2203
|
+
if inspect.isfunction(func_or_cls):
|
2204
|
+
e = func_or_cls()
|
2205
|
+
if not isinstance(e, Evaluable):
|
2206
|
+
raise TypeError(
|
2207
|
+
f'The return value of `{func_or_cls}` should be an instance of '
|
2208
|
+
'`lf.eval.Evaluable` subclass.'
|
2209
|
+
)
|
2210
|
+
|
2211
|
+
class GeneratedSuite(Suite):
|
2212
|
+
# NOTE(daiyip): Delay serialization key registration for generated
|
2213
|
+
# class.
|
2214
|
+
auto_register = False
|
2215
|
+
children = e.children if isinstance(e, Suite) else [e]
|
2216
|
+
|
2217
|
+
cls = GeneratedSuite
|
2218
|
+
cls.__name__ = func_or_cls.__name__
|
2219
|
+
cls.__doc__ = func_or_cls.__doc__
|
2220
|
+
cls.__qualname__ = func_or_cls.__qualname__
|
2221
|
+
cls.__module__ = getattr(func_or_cls, '__module__', 'wrapper')
|
2222
|
+
cls.register_for_deserialization(cls.__type_name__)
|
2223
|
+
|
2224
|
+
elif issubclass(func_or_cls, Evaluable):
|
2225
|
+
cls = func_or_cls
|
1946
2226
|
else:
|
1947
|
-
|
2227
|
+
raise ValueError(f'Unsupported type: {type(func_or_cls)}')
|
2228
|
+
|
2229
|
+
_eval_registry.register(name, cls)
|
2230
|
+
return cls
|
2231
|
+
|
2232
|
+
return _register
|
2233
|
+
|
2234
|
+
|
2235
|
+
def get(
|
2236
|
+
root_dir: str,
|
2237
|
+
evaluations: list[str | Evaluable],
|
2238
|
+
filter: Union[ # pylint: disable=redefined-builtin
|
2239
|
+
str, # Regex to filter evaluation based on ID.
|
2240
|
+
Callable[[Evaluable], bool], # Custom filter function.
|
2241
|
+
None # No filtering (Default).
|
2242
|
+
] = None, # pylint: disable=bad-whitespace
|
2243
|
+
patches: list[Union[
|
2244
|
+
str, # String-based PyGlove patcher.
|
2245
|
+
pg.patching.Patcher, # PyGlove patcher object.
|
2246
|
+
Callable[[pg.KeyPath, Any, Any], Any], # PyGlove rebind function.
|
2247
|
+
]] | None = None, # pylint: disable=bad-whitespace
|
2248
|
+
) -> Suite:
|
2249
|
+
"""Gets a suite from a list of patched evaluations.
|
2250
|
+
|
2251
|
+
Args:
|
2252
|
+
root_dir: The root directory of the experiment.
|
2253
|
+
evaluations: A list of evaluations to be included in the suite.
|
2254
|
+
filter: A regular expression (str) for selecting sub-experiments of matched
|
2255
|
+
IDs, or a filter function to filter the evaluations.
|
2256
|
+
patches: A list of patches to be applied to the suite. Each element can be
|
2257
|
+
a string (for string-based patcher), a `pg.patching.Patcher` object, or
|
2258
|
+
a rebind function (e.g. `pg.rebind`). See `lf.eval.patch_*` for more
|
2259
|
+
details.
|
2260
|
+
|
2261
|
+
Returns:
|
2262
|
+
A suite of selected `lf.eval.Evaluation` objects.
|
2263
|
+
"""
|
2264
|
+
evaluations = [get_evaluation(e) for e in evaluations]
|
2265
|
+
suite = Suite(evaluations, root_dir=root_dir)
|
2266
|
+
if patches:
|
2267
|
+
suite = pg.patch(suite, patches)
|
2268
|
+
|
2269
|
+
if isinstance(filter, str):
|
2270
|
+
regex = re.compile(filter)
|
2271
|
+
filter = lambda x: bool(regex.match(x.id))
|
2272
|
+
|
2273
|
+
if filter:
|
2274
|
+
suite = Suite(
|
2275
|
+
[leaf for leaf in suite.leaf_nodes if filter(leaf)], root_dir=root_dir)
|
2276
|
+
return suite
|
2277
|
+
|
2278
|
+
|
2279
|
+
def run(
|
2280
|
+
root_dir: str,
|
2281
|
+
evaluations: list[str | Evaluable],
|
2282
|
+
filter: Union[ # pylint: disable=redefined-builtin
|
2283
|
+
str, # Regex to filter evaluation based on ID.
|
2284
|
+
Callable[[Evaluable], bool], # Custom filter function.
|
2285
|
+
None # No filtering (Default).
|
2286
|
+
] = None, # pylint: disable=bad-whitespace
|
2287
|
+
patches: list[Union[
|
2288
|
+
str, # String-based PyGlove patcher.
|
2289
|
+
pg.patching.Patcher, # PyGlove patcher object.
|
2290
|
+
Callable[[pg.KeyPath, Any, Any], Any], # PyGlove rebind function.
|
2291
|
+
]] | None = None, # pylint: disable=bad-whitespace
|
2292
|
+
mode: Literal['run', 'rerun', 'dryrun', 'noop'] = 'run',
|
2293
|
+
debug: bool = False,
|
2294
|
+
print_definition: bool = False,
|
2295
|
+
**kwargs,
|
2296
|
+
) -> Suite:
|
2297
|
+
"""Run selected evaluations with patching.
|
2298
|
+
|
2299
|
+
Args:
|
2300
|
+
root_dir: The root directory of the experiment.
|
2301
|
+
evaluations: A list of evaluations to be included in the suite.
|
2302
|
+
filter: A regular expression (str) for selecting sub-experiments of matched
|
2303
|
+
IDs, or a filter function to filter the evaluations.
|
2304
|
+
patches: A list of patches to be applied to the suite. Each element can be
|
2305
|
+
a string (for string-based patcher), a `pg.patching.Patcher` object, or
|
2306
|
+
a rebind function (e.g. `pg.rebind`). See `lf.eval.patch_*` for more
|
2307
|
+
details.
|
2308
|
+
mode: The mode to run the suite. "run" to run the suite, with reusing
|
2309
|
+
existing results if available; "rerun" to rerun all evaluations even if
|
2310
|
+
there are existing results; "dryrun" to dryrun the suite; and "noop"
|
2311
|
+
to do nothing.
|
2312
|
+
debug: Whether to run in debug mode.
|
2313
|
+
print_definition: Whether to print the experiment definition.
|
2314
|
+
**kwargs: Additional arguments to be passed to dryrun/run the suite.
|
2315
|
+
|
2316
|
+
Returns:
|
2317
|
+
A suite of selected `lf.eval.Evaluation` objects.
|
2318
|
+
"""
|
2319
|
+
suite = get(root_dir, evaluations, patches=patches, filter=filter)
|
2320
|
+
if print_definition:
|
2321
|
+
lf.console.write(
|
2322
|
+
pg.format(
|
2323
|
+
suite,
|
2324
|
+
compact=False,
|
2325
|
+
verbose=False,
|
2326
|
+
hide_default_values=True,
|
2327
|
+
python_format=True,
|
2328
|
+
),
|
2329
|
+
title='[EXPERIMENT DEFINITION]',
|
2330
|
+
color='blue',
|
2331
|
+
)
|
1948
2332
|
|
1949
|
-
|
2333
|
+
if mode == 'run':
|
2334
|
+
rerun = mode == 'rerun'
|
2335
|
+
suite.run(debug=debug, rerun=rerun, **kwargs)
|
2336
|
+
elif mode == 'dryrun':
|
2337
|
+
suite.dryrun(debug=debug, **kwargs)
|
2338
|
+
return suite
|