-
Notifications
You must be signed in to change notification settings - Fork 360
/
Copy pathtest_evaluation.py
1972 lines (1807 loc) · 71.4 KB
/
test_evaluation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import re
import threading
import time
from unittest import mock
from google import auth
from google.auth import credentials as auth_credentials
from google.cloud import aiplatform
import vertexai
from google.cloud.aiplatform import initializer
from google.cloud.aiplatform.metadata import metadata
from google.cloud.aiplatform_v1.services import (
evaluation_service as gapic_evaluation_services,
)
from google.cloud.aiplatform_v1.types import (
evaluation_service as gapic_evaluation_service_types,
)
from google.cloud.aiplatform_v1beta1.services import (
evaluation_service as gapic_evaluation_services_preview,
)
from google.cloud.aiplatform_v1beta1.types import (
evaluation_service as gapic_evaluation_service_types_preview,
)
from vertexai import evaluation
from vertexai import generative_models
from vertexai.evaluation import _base as eval_base
from vertexai.evaluation import _evaluation
from vertexai.evaluation import eval_task
from vertexai.evaluation import utils
from vertexai.evaluation.metrics import _rouge
from vertexai.evaluation.metrics import metric_prompt_template
from vertexai.evaluation.metrics import (
metric_prompt_template_examples,
)
from vertexai.evaluation.metrics import pairwise_metric
from vertexai.evaluation.metrics import pointwise_metric
from vertexai.preview import evaluation as evaluation_preview
from vertexai.preview import reasoning_engines
import numpy as np
import pandas as pd
import pytest
EvalTask = eval_task.EvalTask
EvalTaskPreview = evaluation_preview.eval_task.EvalTask
Pointwise = metric_prompt_template_examples.MetricPromptTemplateExamples.Pointwise
PointwisePreview = (
evaluation_preview.metrics.metric_prompt_template_examples.MetricPromptTemplateExamples.Pointwise
)
Pairwise = metric_prompt_template_examples.MetricPromptTemplateExamples.Pairwise
_TEST_PROJECT = "test-project"
_TEST_LOCATION = "us-central1"
_TEST_BUCKET = "gs://test-bucket"
_TEST_FILE_NAME = "test-file-name.csv"
_AUTORATER_INSTRUCTION = """
You are an expert evaluator. Your task is to evaluate the quality of the responses generated by AI models.
"""
_METRIC_DEFINITION = "You will be assessing Text Quality"
_CRITERIA = {
"Coherence": ("The response presents ideas in a logical and organized manner."),
"Fluency": "The text flows smoothly and naturally",
}
_POINTWISE_RATING_RUBRIC = {
"3": "(Good). Well-written.",
"2": "(Ok). Adequate writing with decent coherence and fluency.",
"1": "(Bad). Poorly written.",
}
_PAIRWISE_RATING_RUBRIC = {
"A": "Response A answers better than response B.",
"SAME": "Response A and B answers equally well.",
"B": "Response B answers better than response A.",
}
_EVALUATION_STEPS = {
"STEP 1": "Assess grammar correctness",
"STEP 2": "Assess word choice and flow",
}
_TEST_POINTWISE_METRIC = pointwise_metric.PointwiseMetric(
metric="test_pointwise_metric",
metric_prompt_template=metric_prompt_template.PointwiseMetricPromptTemplate(
metric_definition=_METRIC_DEFINITION,
criteria=_CRITERIA,
rating_rubric=_POINTWISE_RATING_RUBRIC,
evaluation_steps=_EVALUATION_STEPS,
),
)
_TEST_POINTWISE_METRIC_FREE_STRING = pointwise_metric.PointwiseMetric(
metric="test_pointwise_metric_str", metric_prompt_template="abc: {abc}"
)
_TEST_PAIRWISE_METRIC = pairwise_metric.PairwiseMetric(
metric="test_pairwise_metric",
metric_prompt_template=metric_prompt_template.PairwiseMetricPromptTemplate(
metric_definition=_METRIC_DEFINITION,
criteria=_CRITERIA,
rating_rubric=_PAIRWISE_RATING_RUBRIC,
evaluation_steps=_EVALUATION_STEPS,
),
)
_TEST_COMET = pointwise_metric.Comet(
version="COMET_22_SRC_REF",
source_language="en",
target_language="zh",
)
_TEST_METRICX = pointwise_metric.MetricX(
version="METRICX_24_SRC",
source_language="en",
target_language="zh",
)
_TEST_METRICS = (
"exact_match",
"bleu",
"rouge_1",
"rouge_2",
"rouge_l",
"rouge_l_sum",
Pointwise.COHERENCE,
Pointwise.FLUENCY,
Pointwise.SAFETY,
Pointwise.GROUNDEDNESS,
Pointwise.SUMMARIZATION_QUALITY,
Pointwise.VERBOSITY,
Pointwise.QUESTION_ANSWERING_QUALITY,
_TEST_POINTWISE_METRIC,
_TEST_PAIRWISE_METRIC,
)
_TEST_EVAL_DATASET_WITHOUT_PROMPT = pd.DataFrame(
{
"response": ["test", "text"],
"reference": ["test", "ref"],
"context": ["test", "context"],
"instruction": ["test", "instruction"],
}
)
_TEST_EVAL_DATASET_WITHOUT_RESPONSE = pd.DataFrame(
{
"prompt": ["test", "prompt"],
"reference": ["test", "ref"],
"context": ["test", "context"],
"instruction": ["test", "instruction"],
}
)
_TEST_AGENT_EVAL_DATASET_WITHOUT_RESPONSE = pd.DataFrame(
{
"prompt": ["test_input1", "test_input2"],
"reference_trajectory": [
[{"tool_name": "test_tool1"}, {"tool_name": "test_tool2"}],
[{"tool_name": "test_tool3"}, {"tool_name": "test_tool4"}],
],
},
)
_TEST_EVAL_DATASET_ALL_INCLUDED = pd.DataFrame(
{
"prompt": ["test_prompt", "text_prompt"],
"response": ["test", "text"],
"reference": ["test", "ref"],
"context": ["test", "context"],
"instruction": ["test", "instruction"],
"source": ["test", "source"],
}
)
_TEST_EVAL_DATASET_SINGLE = pd.DataFrame({"prompt": ["test_prompt", "text_prompt"]})
_TEST_JSONL_FILE_CONTENT = """{"prompt": "prompt", "reference": "reference"}\n
{"prompt":"test", "reference": "test"}\n
"""
_TEST_CSV_FILE_CONTENT = """reference,context,instruction\ntest,test,test\n
text,text,text\n
"""
_TEST_EXPERIMENT = "test-experiment"
_TEST_CSV = pd.DataFrame(
columns={
"response": ["text"],
"reference": ["ref"],
}
)
_EXPECTED_POINTWISE_PROMPT_TEMPLATE = """
# Instruction
hello
# Evaluation
## Metric Definition
this is eval metric
## Criteria
metric1: summarization
## Rating Rubric
0: bad
1: good
## Evaluation Steps
step1: start
step2: finish
## Evaluation Examples
Q: hi A: hello
# User Inputs and AI-generated Response
## User Inputs
### country
{country}
## AI-generated Response
{response}
"""
_EXPECTED_POINTWISE_PROMPT_TEMPLATE_WITH_DEFAULT_VALUES = """
# Instruction
You are an expert evaluator. Your task is to evaluate the quality of the responses generated by AI models. We will provide you with the user prompt and an AI-generated responses.
You should first read the user input carefully for analyzing the task, and then evaluate the quality of the responses based on the Criteria provided in the Evaluation section below.
You will assign the response a rating following the Rating Rubric and Evaluation Steps. Give step by step explanations for your rating, and only choose ratings from the Rating Rubric.
# Evaluation
## Criteria
Coherence: The response presents ideas in a logical and organized manner.
Fluency: The text flows smoothly and naturally
## Rating Rubric
1: (Bad). Poorly written.
2: (Ok). Adequate writing with decent coherence and fluency.
3: (Good). Well-written.
## Evaluation Steps
Step 1: Assess the response in aspects of all criteria provided. Provide assessment according to each criterion.
Step 2: Score based on the rating rubric. Give a brief rationale to explain your evaluation considering each individual criterion.
# User Inputs and AI-generated Response
## User Inputs
## AI-generated Response
{response}
"""
_EXPECTED_PAIRWISE_PROMPT_TEMPLATE = """
# Instruction
hello
# Evaluation
## Metric Definition
this is eval metric
## Criteria
metric1: summarization
## Rating Rubric
A: good
B: good
## Evaluation Steps
step1: start
step2: finish
## Evaluation Examples
Q: hi A: hello
# User Inputs and AI-generated Responses
## User Inputs
### country
{country}
## AI-generated Responses
### Response A
{baseline_model_response}
### Response B
{response}
"""
_EXPECTED_PAIRWISE_PROMPT_TEMPLATE_WITH_DEFAULT_VALUES = """
# Instruction
You are an expert evaluator. Your task is to evaluate the quality of the responses generated by two AI models. We will provide you with the user input and a pair of AI-generated responses (Response A and Response B).
You should first read the user input carefully for analyzing the task, and then evaluate the quality of the responses based on based on the Criteria provided in the Evaluation section below.
You will first judge responses individually, following the Rating Rubric and Evaluation Steps. Then you will give step by step explanations for your judgement, compare results to declare the winner based on the Rating Rubric and Evaluation Steps.
# Evaluation
## Criteria
Coherence: The response presents ideas in a logical and organized manner.
Fluency: The text flows smoothly and naturally
## Rating Rubric
A: Response A answers better than response B.
B: Response B answers better than response A.
SAME: Response A and B answers equally well.
## Evaluation Steps
Step 1: Analyze Response A based on all the Criteria.
Step 2: Analyze Response B based on all the Criteria.
Step 3: Compare the overall performance of Response A and Response B based on your analyses and assessment.
Step 4: Output your preference of "A", "SAME" or "B" to the pairwise_choice field according to the Rating Rubrics.
Step 5: Output your assessment reasoning in the explanation field
# User Inputs and AI-generated Responses
## User Inputs
## AI-generated Responses
### Response A
{baseline_model_response}
### Response B
{response}
"""
_MOCK_RUNNABLE_INFERENCE_RESPONSE = [
{
"input": "test_input",
"output": "test_output",
"intermediate_steps": [
[{"kwargs": {"tool": "test_tool1"}, "tool_output": "test_tool_output"}],
[{"kwargs": {"tool": "test_tool2"}, "tool_output": "test_tool_output"}],
],
},
{
"input": "test_input",
"output": "test_output",
"intermediate_steps": [
[{"kwargs": {"tool": "test_tool2"}, "tool_output": "test_tool_output"}],
[{"kwargs": {"tool": "test_tool3"}, "tool_output": "test_tool_output"}],
],
},
]
_MOCK_EXACT_MATCH_RESULT = (
gapic_evaluation_service_types.EvaluateInstancesResponse(
exact_match_results=gapic_evaluation_service_types.ExactMatchResults(
exact_match_metric_values=[
gapic_evaluation_service_types.ExactMatchMetricValue(score=1.0),
]
)
),
gapic_evaluation_service_types.EvaluateInstancesResponse(
exact_match_results=gapic_evaluation_service_types.ExactMatchResults(
exact_match_metric_values=[
gapic_evaluation_service_types.ExactMatchMetricValue(score=0.0),
]
)
),
)
_MOCK_TRAJECTORY_EXACT_MATCH_RESULT = (
gapic_evaluation_service_types_preview.EvaluateInstancesResponse(
trajectory_exact_match_results=gapic_evaluation_service_types_preview.TrajectoryExactMatchResults(
trajectory_exact_match_metric_values=[
gapic_evaluation_service_types_preview.TrajectoryExactMatchMetricValue(
score=1.0
),
]
)
),
gapic_evaluation_service_types_preview.EvaluateInstancesResponse(
trajectory_exact_match_results=gapic_evaluation_service_types_preview.TrajectoryExactMatchResults(
trajectory_exact_match_metric_values=[
gapic_evaluation_service_types_preview.TrajectoryExactMatchMetricValue(
score=0.0
),
]
)
),
)
_MOCK_POINTWISE_RESULT = (
gapic_evaluation_service_types.EvaluateInstancesResponse(
pointwise_metric_result=gapic_evaluation_service_types.PointwiseMetricResult(
score=5, explanation="explanation"
)
),
gapic_evaluation_service_types.EvaluateInstancesResponse(
pointwise_metric_result=gapic_evaluation_service_types.PointwiseMetricResult(
score=4, explanation="explanation"
)
),
)
_MOCK_PAIRWISE_RESULT = (
gapic_evaluation_service_types.EvaluateInstancesResponse(
pairwise_metric_result=gapic_evaluation_service_types.PairwiseMetricResult(
pairwise_choice=gapic_evaluation_service_types.PairwiseChoice.BASELINE,
explanation="explanation",
)
),
gapic_evaluation_service_types.EvaluateInstancesResponse(
pairwise_metric_result=gapic_evaluation_service_types.PairwiseMetricResult(
pairwise_choice=gapic_evaluation_service_types.PairwiseChoice.BASELINE,
explanation="explanation",
)
),
)
_MOCK_SUMMARIZATION_QUALITY_RESULT = (
gapic_evaluation_service_types.EvaluateInstancesResponse(
pointwise_metric_result=gapic_evaluation_service_types.PointwiseMetricResult(
score=5, explanation="explanation"
)
),
gapic_evaluation_service_types.EvaluateInstancesResponse(
pointwise_metric_result=gapic_evaluation_service_types.PointwiseMetricResult(
score=4, explanation="explanation"
)
),
)
_MOCK_COHERENCE_RESULT = (
gapic_evaluation_service_types_preview.EvaluateInstancesResponse(
pointwise_metric_result=gapic_evaluation_service_types_preview.PointwiseMetricResult(
score=5, explanation="explanation"
)
),
gapic_evaluation_service_types_preview.EvaluateInstancesResponse(
pointwise_metric_result=gapic_evaluation_service_types_preview.PointwiseMetricResult(
score=4, explanation="explanation"
)
),
)
_MOCK_PAIRWISE_SUMMARIZATION_QUALITY_RESULT = (
gapic_evaluation_service_types.EvaluateInstancesResponse(
pairwise_metric_result=gapic_evaluation_service_types.PairwiseMetricResult(
pairwise_choice=gapic_evaluation_service_types.PairwiseChoice.BASELINE,
explanation="explanation",
)
),
gapic_evaluation_service_types.EvaluateInstancesResponse(
pairwise_metric_result=gapic_evaluation_service_types.PairwiseMetricResult(
pairwise_choice=gapic_evaluation_service_types.PairwiseChoice.CANDIDATE,
explanation="explanation",
)
),
)
_MOCK_MODEL_INFERENCE_RESPONSE = generative_models.GenerationResponse.from_dict(
{
"candidates": [
{
"content": {"parts": [{"text": "test_response"}]},
}
]
}
)
MOCK_EVAL_RESULT = eval_base.EvalResult(
summary_metrics={
"row_count": 1,
"mock_metric/mean": 1.0,
"mock_metric/std": np.nan,
},
metrics_table=pd.DataFrame(
{
"response": ["test"],
"mock_metric": [1.0],
}
),
)
_EXPECTED_ROUGE_REQUESTS = (
gapic_evaluation_service_types.EvaluateInstancesRequest(
location=f"projects/{_TEST_PROJECT}/locations/{_TEST_LOCATION}",
rouge_input=gapic_evaluation_service_types.RougeInput(
metric_spec=gapic_evaluation_service_types.RougeSpec(
rouge_type="rougeLsum", use_stemmer=True, split_summaries=True
),
instances=[
gapic_evaluation_service_types.RougeInstance(
prediction="test_response", reference="test"
),
],
),
),
gapic_evaluation_service_types.EvaluateInstancesRequest(
location=f"projects/{_TEST_PROJECT}/locations/{_TEST_LOCATION}",
rouge_input=gapic_evaluation_service_types.RougeInput(
metric_spec=gapic_evaluation_service_types.RougeSpec(
rouge_type="rougeLsum", use_stemmer=True, split_summaries=True
),
instances=[
gapic_evaluation_service_types.RougeInstance(
prediction="test_response", reference="ref"
),
],
),
),
)
_MOCK_ROUGE_RESULT = (
gapic_evaluation_service_types.EvaluateInstancesResponse(
rouge_results=gapic_evaluation_service_types.RougeResults(
rouge_metric_values=[
gapic_evaluation_service_types.RougeMetricValue(score=1.0)
]
)
),
gapic_evaluation_service_types.EvaluateInstancesResponse(
rouge_results=gapic_evaluation_service_types.RougeResults(
rouge_metric_values=[
gapic_evaluation_service_types.RougeMetricValue(score=0.5)
]
)
),
)
_EXPECTED_COLUMN_MAPPING = {
"context": "context",
"reference": "reference",
"response": "response",
"instruction": "instruction",
"prompt": "prompt",
"source": "source",
}
_MOCK_MODEL_BASED_TRANSLATION_RESULT = (
# The order of the responses is important.
gapic_evaluation_service_types.EvaluateInstancesResponse(
comet_result=gapic_evaluation_service_types.CometResult(score=0.1)
),
gapic_evaluation_service_types.EvaluateInstancesResponse(
metricx_result=gapic_evaluation_service_types.MetricxResult(score=5)
),
gapic_evaluation_service_types.EvaluateInstancesResponse(
comet_result=gapic_evaluation_service_types.CometResult(score=0.9)
),
gapic_evaluation_service_types.EvaluateInstancesResponse(
metricx_result=gapic_evaluation_service_types.MetricxResult(score=20)
),
)
@pytest.fixture(scope="module")
def google_auth_mock():
with mock.patch.object(auth, "default") as google_auth_mock:
google_auth_mock.return_value = (
auth_credentials.AnonymousCredentials(),
_TEST_PROJECT,
)
yield google_auth_mock
@pytest.fixture
def mock_experiment_tracker():
with mock.patch.object(
metadata, "_experiment_tracker", autospec=True
) as mock_experiment_tracker:
yield mock_experiment_tracker
@pytest.fixture
def mock_storage_blob_from_string():
with mock.patch("google.cloud.storage.Blob.from_string") as mock_blob_from_string:
yield mock_blob_from_string
@pytest.mark.usefixtures("google_auth_mock")
class TestEvaluation:
def setup_method(self):
vertexai.init(
project=_TEST_PROJECT,
location=_TEST_LOCATION,
)
def teardown_method(self):
initializer.global_pool.shutdown(wait=True)
def test_create_eval_task(self):
test_eval_task = EvalTask(
dataset=_TEST_EVAL_DATASET_ALL_INCLUDED,
metrics=_TEST_METRICS,
experiment=_TEST_EXPERIMENT,
)
assert test_eval_task.dataset.equals(_TEST_EVAL_DATASET_ALL_INCLUDED)
assert test_eval_task.metrics == _TEST_METRICS
assert test_eval_task.experiment == _TEST_EXPERIMENT
assert test_eval_task._metric_column_mapping == _EXPECTED_COLUMN_MAPPING
@pytest.mark.parametrize("api_transport", ["grpc", "rest"])
def test_compute_exact_match_metric(self, api_transport):
aiplatform.init(
project=_TEST_PROJECT,
location=_TEST_LOCATION,
api_transport=api_transport,
)
eval_dataset = pd.DataFrame(
{
"response": ["test", "text"],
"reference": ["test", "ref"],
}
)
test_metrics = ["exact_match"]
test_eval_task = EvalTask(dataset=eval_dataset, metrics=test_metrics)
mock_metric_results = _MOCK_EXACT_MATCH_RESULT
with mock.patch.object(
target=gapic_evaluation_services.EvaluationServiceClient,
attribute="evaluate_instances",
side_effect=mock_metric_results,
):
test_result = test_eval_task.evaluate()
assert test_result.summary_metrics["row_count"] == 2
assert test_result.summary_metrics["exact_match/mean"] == 0.5
assert test_result.summary_metrics["exact_match/std"] == pytest.approx(0.7, 0.1)
assert list(test_result.metrics_table.columns.values) == [
"response",
"reference",
"exact_match/score",
]
assert test_result.metrics_table[["response", "reference"]].equals(eval_dataset)
assert list(test_result.metrics_table["exact_match/score"].values) == [
1.0,
0.0,
]
@pytest.mark.parametrize("api_transport", ["grpc", "rest"])
def test_compute_pointwise_metrics(self, api_transport):
aiplatform.init(
project=_TEST_PROJECT,
location=_TEST_LOCATION,
api_transport=api_transport,
)
test_metrics = [_TEST_POINTWISE_METRIC]
test_eval_task = EvalTask(
dataset=_TEST_EVAL_DATASET_ALL_INCLUDED, metrics=test_metrics
)
mock_metric_results = _MOCK_POINTWISE_RESULT
with mock.patch.object(
target=gapic_evaluation_services.EvaluationServiceClient,
attribute="evaluate_instances",
side_effect=mock_metric_results,
):
test_result = test_eval_task.evaluate()
assert test_result.summary_metrics["row_count"] == 2
assert test_result.summary_metrics["test_pointwise_metric/mean"] == 4.5
assert test_result.summary_metrics[
"test_pointwise_metric/std"
] == pytest.approx(0.7, 0.1)
assert set(test_result.metrics_table.columns.values) == set(
[
"prompt",
"response",
"context",
"instruction",
"reference",
"test_pointwise_metric/score",
"test_pointwise_metric/explanation",
"source",
]
)
assert test_result.metrics_table["response"].equals(
_TEST_EVAL_DATASET_ALL_INCLUDED["response"]
)
assert test_result.metrics_table["prompt"].equals(
_TEST_EVAL_DATASET_ALL_INCLUDED["prompt"]
)
assert list(
test_result.metrics_table["test_pointwise_metric/score"].values
) == [5, 4]
assert list(
test_result.metrics_table["test_pointwise_metric/explanation"].values
) == [
"explanation",
"explanation",
]
def test_compute_pointwise_metrics_free_string(self):
test_eval_task = EvalTask(
dataset=_TEST_EVAL_DATASET_ALL_INCLUDED,
metrics=[_TEST_POINTWISE_METRIC_FREE_STRING],
metric_column_mapping={"abc": "prompt"},
)
mock_metric_results = _MOCK_POINTWISE_RESULT
with mock.patch.object(
target=gapic_evaluation_services.EvaluationServiceClient,
attribute="evaluate_instances",
side_effect=mock_metric_results,
):
test_result = test_eval_task.evaluate()
assert test_result.summary_metrics["row_count"] == 2
assert test_result.summary_metrics["test_pointwise_metric_str/mean"] == 4.5
assert test_result.summary_metrics[
"test_pointwise_metric_str/std"
] == pytest.approx(0.7, 0.1)
assert set(test_result.metrics_table.columns.values) == set(
[
"prompt",
"response",
"context",
"instruction",
"reference",
"test_pointwise_metric_str/score",
"test_pointwise_metric_str/explanation",
"source",
]
)
assert test_result.metrics_table["response"].equals(
_TEST_EVAL_DATASET_ALL_INCLUDED["response"]
)
assert test_result.metrics_table["prompt"].equals(
_TEST_EVAL_DATASET_ALL_INCLUDED["prompt"]
)
assert list(
test_result.metrics_table["test_pointwise_metric_str/score"].values
) == [5, 4]
assert list(
test_result.metrics_table["test_pointwise_metric_str/explanation"].values
) == [
"explanation",
"explanation",
]
@pytest.mark.parametrize("api_transport", ["grpc", "rest"])
def test_compute_pointwise_metrics_metric_prompt_template_example(
self, api_transport
):
aiplatform.init(
project=_TEST_PROJECT,
location=_TEST_LOCATION,
api_transport=api_transport,
)
mock_model = mock.create_autospec(
generative_models.GenerativeModel, instance=True
)
mock_model.generate_content.return_value = _MOCK_MODEL_INFERENCE_RESPONSE
mock_model._model_name = "publishers/google/model/gemini-1.0-pro"
test_metrics = [Pointwise.SUMMARIZATION_QUALITY]
test_eval_task = EvalTask(
dataset=_TEST_EVAL_DATASET_WITHOUT_RESPONSE, metrics=test_metrics
)
mock_metric_results = _MOCK_SUMMARIZATION_QUALITY_RESULT
with mock.patch.object(
target=gapic_evaluation_services.EvaluationServiceClient,
attribute="evaluate_instances",
side_effect=mock_metric_results,
):
test_result = test_eval_task.evaluate(
model=mock_model,
prompt_template="{instruction} test prompt template {context}",
)
assert test_result.summary_metrics["row_count"] == 2
assert test_result.summary_metrics["summarization_quality/mean"] == 4.5
assert test_result.summary_metrics[
"summarization_quality/std"
] == pytest.approx(0.7, 0.1)
assert set(test_result.metrics_table.columns.values) == set(
[
"context",
"instruction",
"reference",
"prompt",
"response",
"summarization_quality/score",
"summarization_quality/explanation",
]
)
assert list(
test_result.metrics_table["summarization_quality/score"].values
) == [5, 4]
assert list(
test_result.metrics_table["summarization_quality/explanation"].values
) == [
"explanation",
"explanation",
]
@pytest.mark.parametrize("api_transport", ["grpc", "rest"])
def test_compute_pointwise_metrics_without_model_inference(self, api_transport):
aiplatform.init(
project=_TEST_PROJECT,
location=_TEST_LOCATION,
api_transport=api_transport,
)
test_metrics = [Pointwise.SUMMARIZATION_QUALITY]
test_eval_task = EvalTask(
dataset=_TEST_EVAL_DATASET_ALL_INCLUDED, metrics=test_metrics
)
mock_metric_results = _MOCK_SUMMARIZATION_QUALITY_RESULT
with mock.patch.object(
target=gapic_evaluation_services.EvaluationServiceClient,
attribute="evaluate_instances",
side_effect=mock_metric_results,
):
test_result = test_eval_task.evaluate()
assert test_result.summary_metrics["row_count"] == 2
assert test_result.summary_metrics["summarization_quality/mean"] == 4.5
assert test_result.summary_metrics[
"summarization_quality/std"
] == pytest.approx(0.7, 0.1)
assert set(test_result.metrics_table.columns.values) == set(
[
"context",
"instruction",
"reference",
"prompt",
"response",
"summarization_quality/score",
"summarization_quality/explanation",
"source",
]
)
assert list(
test_result.metrics_table["summarization_quality/score"].values
) == [5, 4]
assert list(
test_result.metrics_table["summarization_quality/explanation"].values
) == [
"explanation",
"explanation",
]
@pytest.mark.parametrize("api_transport", ["grpc", "rest"])
def test_compute_model_based_translation_metrics_without_model_inference(
self, api_transport
):
aiplatform.init(
project=_TEST_PROJECT,
location=_TEST_LOCATION,
api_transport=api_transport,
)
test_metrics = [_TEST_COMET, _TEST_METRICX]
test_eval_task = EvalTask(
dataset=_TEST_EVAL_DATASET_ALL_INCLUDED, metrics=test_metrics
)
mock_metric_results = _MOCK_MODEL_BASED_TRANSLATION_RESULT
with mock.patch.object(
target=gapic_evaluation_services.EvaluationServiceClient,
attribute="evaluate_instances",
side_effect=mock_metric_results,
):
test_result = test_eval_task.evaluate()
assert test_result.summary_metrics["row_count"] == 2
assert test_result.summary_metrics["comet/mean"] == 0.5
assert test_result.summary_metrics["metricx/mean"] == 12.5
assert test_result.summary_metrics["comet/std"] == pytest.approx(0.5, 0.6)
assert test_result.summary_metrics["metricx/std"] == pytest.approx(10, 11)
assert set(test_result.metrics_table.columns.values) == set(
[
"context",
"instruction",
"reference",
"prompt",
"response",
"source",
"comet/score",
"metricx/score",
]
)
assert list(test_result.metrics_table["comet/score"].values) == [0.1, 0.9]
assert list(test_result.metrics_table["metricx/score"].values) == [5, 20]
@pytest.mark.parametrize("api_transport", ["grpc", "rest"])
def test_compute_automatic_metrics_with_custom_metric_spec(self, api_transport):
aiplatform.init(
project=_TEST_PROJECT,
location=_TEST_LOCATION,
api_transport=api_transport,
)
mock_model = mock.create_autospec(
generative_models.GenerativeModel, instance=True
)
mock_model.generate_content.return_value = _MOCK_MODEL_INFERENCE_RESPONSE
mock_model._model_name = "publishers/google/model/gemini-1.0-pro"
test_metrics = [
_rouge.Rouge(
rouge_type="rougeLsum",
use_stemmer=True,
split_summaries=True,
)
]
test_eval_task = evaluation.EvalTask(
dataset=_TEST_EVAL_DATASET_WITHOUT_RESPONSE, metrics=test_metrics
)
with mock.patch.object(
target=gapic_evaluation_services.EvaluationServiceClient,
attribute="evaluate_instances",
side_effect=_MOCK_ROUGE_RESULT,
) as mock_evaluate_instances:
test_result = test_eval_task.evaluate(
model=mock_model,
)
assert test_result.summary_metrics["row_count"] == 2
assert test_result.summary_metrics["rouge/mean"] == 0.75
assert test_result.summary_metrics["rouge/std"] == pytest.approx(0.35, 0.1)
assert set(test_result.metrics_table.columns.values) == set(
[
"prompt",
"reference",
"response",
"context",
"instruction",
"rouge/score",
]
)
assert list(test_result.metrics_table["rouge/score"].values) == [1, 0.5]
api_requests = [
call.kwargs["request"] for call in mock_evaluate_instances.call_args_list
]
assert api_requests == list(_EXPECTED_ROUGE_REQUESTS)
@pytest.mark.parametrize("api_transport", ["grpc", "rest"])
def test_compute_pairwise_metrics(self, api_transport):
aiplatform.init(
project=_TEST_PROJECT,
location=_TEST_LOCATION,
api_transport=api_transport,
)
mock_baseline_model = mock.create_autospec(
generative_models.GenerativeModel, instance=True
)
mock_baseline_model.generate_content.return_value = (
_MOCK_MODEL_INFERENCE_RESPONSE
)
mock_baseline_model._model_name = "publishers/google/model/gemini-pro"
mock_candidate_model = mock.create_autospec(
generative_models.GenerativeModel, instance=True
)
mock_candidate_model.generate_content.return_value = (
_MOCK_MODEL_INFERENCE_RESPONSE
)
mock_candidate_model._model_name = "publishers/google/model/gemini-pro"
_TEST_PAIRWISE_METRIC._baseline_model = mock_baseline_model
test_metrics = [_TEST_PAIRWISE_METRIC]
test_eval_task = EvalTask(
dataset=_TEST_EVAL_DATASET_WITHOUT_RESPONSE, metrics=test_metrics
)
mock_metric_results = _MOCK_PAIRWISE_SUMMARIZATION_QUALITY_RESULT
with mock.patch.object(
target=gapic_evaluation_services.EvaluationServiceClient,
attribute="evaluate_instances",
side_effect=mock_metric_results,
):
test_result = test_eval_task.evaluate(
model=mock_candidate_model,
prompt_template="{instruction} test prompt template {context}",
)
_TEST_PAIRWISE_METRIC._baseline_model = None
assert test_result.summary_metrics["row_count"] == 2
assert set(test_result.metrics_table.columns.values) == set(
[
"context",
"instruction",
"prompt",
"response",
"reference",
"baseline_model_response",
"test_pairwise_metric/pairwise_choice",
"test_pairwise_metric/explanation",
]
)
assert list(
test_result.metrics_table["test_pairwise_metric/pairwise_choice"].values
) == ["BASELINE", "CANDIDATE"]
assert list(
test_result.metrics_table["test_pairwise_metric/explanation"].values
) == [
"explanation",
"explanation",
]
assert set(test_result.summary_metrics.keys()) == set(
[
"row_count",
"test_pairwise_metric/candidate_model_win_rate",
"test_pairwise_metric/baseline_model_win_rate",
]
)
assert (
test_result.summary_metrics["test_pairwise_metric/candidate_model_win_rate"]
== 0.5
)
assert (
test_result.summary_metrics["test_pairwise_metric/baseline_model_win_rate"]
== 0.5
)
@pytest.mark.parametrize("api_transport", ["grpc", "rest"])
def test_compute_pairwise_metrics_metric_prompt_template_example(
self, api_transport
):
aiplatform.init(
project=_TEST_PROJECT,